From 219e63075f726997f67e9c3b4ebc254ca3c3b237 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Thu, 12 Dec 2024 03:18:55 +0000 Subject: [PATCH 1/4] feat: Add support for opt-in debug logging fix: Fix typing issue with gRPC metadata when key ends in -bin chore: Update gapic-generator-python to v1.21.0 PiperOrigin-RevId: 705285820 Source-Link: https://github.com/googleapis/googleapis/commit/f9b8b9150f7fcd600b0acaeef91236b1843f5e49 Source-Link: https://github.com/googleapis/googleapis-gen/commit/ca1e0a1e472d6e6f5de883a5cb54724f112ce348 Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLW1hcHMtbWFwc3BsYXRmb3JtZGF0YXNldHMvLk93bEJvdC55YW1sIiwiaCI6ImNhMWUwYTFlNDcyZDZlNmY1ZGU4ODNhNWNiNTQ3MjRmMTEyY2UzNDgifQ== Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLW1hcHMtcGxhY2VzLy5Pd2xCb3QueWFtbCIsImgiOiJjYTFlMGExZTQ3MmQ2ZTZmNWRlODgzYTVjYjU0NzI0ZjExMmNlMzQ4In0= Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLW1hcHMtcm91dGVvcHRpbWl6YXRpb24vLk93bEJvdC55YW1sIiwiaCI6ImNhMWUwYTFlNDcyZDZlNmY1ZGU4ODNhNWNiNTQ3MjRmMTEyY2UzNDgifQ== Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLW1hcHMtcm91dGluZy8uT3dsQm90LnlhbWwiLCJoIjoiY2ExZTBhMWU0NzJkNmU2ZjVkZTg4M2E1Y2I1NDcyNGYxMTJjZTM0OCJ9 Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLW1hcHMtc29sYXIvLk93bEJvdC55YW1sIiwiaCI6ImNhMWUwYTFlNDcyZDZlNmY1ZGU4ODNhNWNiNTQ3MjRmMTEyY2UzNDgifQ== Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLXNob3BwaW5nLW1lcmNoYW50LWFjY291bnRzLy5Pd2xCb3QueWFtbCIsImgiOiJjYTFlMGExZTQ3MmQ2ZTZmNWRlODgzYTVjYjU0NzI0ZjExMmNlMzQ4In0= Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLXNob3BwaW5nLW1lcmNoYW50LWNvbnZlcnNpb25zLy5Pd2xCb3QueWFtbCIsImgiOiJjYTFlMGExZTQ3MmQ2ZTZmNWRlODgzYTVjYjU0NzI0ZjExMmNlMzQ4In0= Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLXNob3BwaW5nLW1lcmNoYW50LWRhdGFzb3VyY2VzLy5Pd2xCb3QueWFtbCIsImgiOiJjYTFlMGExZTQ3MmQ2ZTZmNWRlODgzYTVjYjU0NzI0ZjExMmNlMzQ4In0= Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLXNob3BwaW5nLW1lcmNoYW50LWludmVudG9yaWVzLy5Pd2xCb3QueWFtbCIsImgiOiJjYTFlMGExZTQ3MmQ2ZTZmNWRlODgzYTVjYjU0NzI0ZjExMmNlMzQ4In0= Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLXNob3BwaW5nLW1lcmNoYW50LWxmcC8uT3dsQm90LnlhbWwiLCJoIjoiY2ExZTBhMWU0NzJkNmU2ZjVkZTg4M2E1Y2I1NDcyNGYxMTJjZTM0OCJ9 Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLXNob3BwaW5nLW1lcmNoYW50LW5vdGlmaWNhdGlvbnMvLk93bEJvdC55YW1sIiwiaCI6ImNhMWUwYTFlNDcyZDZlNmY1ZGU4ODNhNWNiNTQ3MjRmMTEyY2UzNDgifQ== Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLXNob3BwaW5nLW1lcmNoYW50LXByb21vdGlvbnMvLk93bEJvdC55YW1sIiwiaCI6ImNhMWUwYTFlNDcyZDZlNmY1ZGU4ODNhNWNiNTQ3MjRmMTEyY2UzNDgifQ== Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLXNob3BwaW5nLW1lcmNoYW50LXF1b3RhLy5Pd2xCb3QueWFtbCIsImgiOiJjYTFlMGExZTQ3MmQ2ZTZmNWRlODgzYTVjYjU0NzI0ZjExMmNlMzQ4In0= Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLXNob3BwaW5nLW1lcmNoYW50LXJlcG9ydHMvLk93bEJvdC55YW1sIiwiaCI6ImNhMWUwYTFlNDcyZDZlNmY1ZGU4ODNhNWNiNTQ3MjRmMTEyY2UzNDgifQ== Copy-Tag: eyJwIjoicGFja2FnZXMvZ3JhZmVhcy8uT3dsQm90LnlhbWwiLCJoIjoiY2ExZTBhMWU0NzJkNmU2ZjVkZTg4M2E1Y2I1NDcyNGYxMTJjZTM0OCJ9 --- .../v1/.coveragerc | 13 + .../v1/.flake8 | 33 + .../v1/MANIFEST.in | 2 + .../v1/README.rst | 49 + .../v1/docs/_static/custom.css | 3 + .../v1/docs/conf.py | 376 + .../v1/docs/index.rst | 7 + .../maps_platform_datasets.rst | 10 + .../mapsplatformdatasets_v1/services_.rst | 6 + .../docs/mapsplatformdatasets_v1/types_.rst | 6 + .../maps/mapsplatformdatasets/__init__.py | 55 + .../mapsplatformdatasets/gapic_version.py | 16 + .../google/maps/mapsplatformdatasets/py.typed | 2 + .../maps/mapsplatformdatasets_v1/__init__.py | 56 + .../gapic_metadata.json | 118 + .../mapsplatformdatasets_v1/gapic_version.py | 16 + .../maps/mapsplatformdatasets_v1/py.typed | 2 + .../services/__init__.py | 15 + .../maps_platform_datasets/__init__.py | 22 + .../maps_platform_datasets/async_client.py | 941 ++ .../services/maps_platform_datasets/client.py | 1271 ++ .../services/maps_platform_datasets/pagers.py | 307 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../maps_platform_datasets/transports/base.py | 254 + .../maps_platform_datasets/transports/grpc.py | 480 + .../transports/grpc_asyncio.py | 552 + .../maps_platform_datasets/transports/rest.py | 1051 ++ .../transports/rest_base.py | 336 + .../mapsplatformdatasets_v1/types/__init__.py | 52 + .../types/data_source.py | 97 + .../mapsplatformdatasets_v1/types/dataset.py | 236 + .../types/maps_platform_datasets.py | 265 + .../types/maps_platform_datasets_service.py | 26 + .../v1/mypy.ini | 3 + .../v1/noxfile.py | 280 + ..._platform_datasets_create_dataset_async.py | 52 + ...s_platform_datasets_create_dataset_sync.py | 52 + ..._platform_datasets_delete_dataset_async.py | 50 + ...s_platform_datasets_delete_dataset_sync.py | 50 + ...orm_datasets_fetch_dataset_errors_async.py | 53 + ...form_datasets_fetch_dataset_errors_sync.py | 53 + ...aps_platform_datasets_get_dataset_async.py | 52 + ...maps_platform_datasets_get_dataset_sync.py | 52 + ...s_platform_datasets_list_datasets_async.py | 53 + ...ps_platform_datasets_list_datasets_sync.py | 53 + ..._datasets_update_dataset_metadata_async.py | 51 + ...m_datasets_update_dataset_metadata_sync.py | 51 + ...a_google.maps.mapsplatformdatasets.v1.json | 991 ++ .../fixup_mapsplatformdatasets_v1_keywords.py | 181 + .../v1/setup.py | 98 + .../v1/testing/constraints-3.10.txt | 6 + .../v1/testing/constraints-3.11.txt | 6 + .../v1/testing/constraints-3.12.txt | 6 + .../v1/testing/constraints-3.13.txt | 6 + .../v1/testing/constraints-3.7.txt | 10 + .../v1/testing/constraints-3.8.txt | 6 + .../v1/testing/constraints-3.9.txt | 6 + .../v1/tests/__init__.py | 16 + .../v1/tests/unit/__init__.py | 16 + .../v1/tests/unit/gapic/__init__.py | 16 + .../gapic/mapsplatformdatasets_v1/__init__.py | 16 + .../test_maps_platform_datasets.py | 6115 ++++++++ .../google-maps-places/v1/.coveragerc | 13 + owl-bot-staging/google-maps-places/v1/.flake8 | 33 + .../google-maps-places/v1/MANIFEST.in | 2 + .../google-maps-places/v1/README.rst | 49 + .../v1/docs/_static/custom.css | 3 + .../google-maps-places/v1/docs/conf.py | 376 + .../google-maps-places/v1/docs/index.rst | 7 + .../v1/docs/places_v1/places.rst | 6 + .../v1/docs/places_v1/services_.rst | 6 + .../v1/docs/places_v1/types_.rst | 6 + .../v1/google/maps/places/__init__.py | 83 + .../v1/google/maps/places/gapic_version.py | 16 + .../v1/google/maps/places/py.typed | 2 + .../v1/google/maps/places_v1/__init__.py | 84 + .../google/maps/places_v1/gapic_metadata.json | 103 + .../v1/google/maps/places_v1/gapic_version.py | 16 + .../v1/google/maps/places_v1/py.typed | 2 + .../maps/places_v1/services/__init__.py | 15 + .../places_v1/services/places/__init__.py | 22 + .../places_v1/services/places/async_client.py | 724 + .../maps/places_v1/services/places/client.py | 1085 ++ .../services/places/transports/README.rst | 9 + .../services/places/transports/__init__.py | 38 + .../services/places/transports/base.py | 210 + .../services/places/transports/grpc.py | 457 + .../places/transports/grpc_asyncio.py | 497 + .../services/places/transports/rest.py | 946 ++ .../services/places/transports/rest_base.py | 307 + .../google/maps/places_v1/types/__init__.py | 108 + .../maps/places_v1/types/attribution.py | 65 + .../maps/places_v1/types/content_block.py | 68 + .../places_v1/types/contextual_content.py | 218 + .../maps/places_v1/types/ev_charging.py | 176 + .../maps/places_v1/types/fuel_options.py | 143 + .../google/maps/places_v1/types/geometry.py | 58 + .../v1/google/maps/places_v1/types/photo.py | 69 + .../v1/google/maps/places_v1/types/place.py | 1286 ++ .../maps/places_v1/types/places_service.py | 1340 ++ .../google/maps/places_v1/types/polyline.py | 62 + .../maps/places_v1/types/price_range.py | 59 + .../google/maps/places_v1/types/reference.py | 60 + .../v1/google/maps/places_v1/types/review.py | 94 + .../maps/places_v1/types/route_modifiers.py | 76 + .../places_v1/types/routing_preference.py | 71 + .../maps/places_v1/types/routing_summary.py | 95 + .../maps/places_v1/types/travel_mode.py | 63 + .../google-maps-places/v1/mypy.ini | 3 + .../google-maps-places/v1/noxfile.py | 280 + ...erated_places_autocomplete_places_async.py | 52 + ...nerated_places_autocomplete_places_sync.py | 52 + ..._generated_places_get_photo_media_async.py | 52 + ...1_generated_places_get_photo_media_sync.py | 52 + ...ces_v1_generated_places_get_place_async.py | 52 + ...aces_v1_generated_places_get_place_sync.py | 52 + ...v1_generated_places_search_nearby_async.py | 55 + ..._v1_generated_places_search_nearby_sync.py | 55 + ...s_v1_generated_places_search_text_async.py | 52 + ...es_v1_generated_places_search_text_sync.py | 52 + ...nippet_metadata_google.maps.places.v1.json | 796 + .../v1/scripts/fixup_places_v1_keywords.py | 180 + .../google-maps-places/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 | 7 + .../v1/testing/constraints-3.7.txt | 11 + .../v1/testing/constraints-3.8.txt | 7 + .../v1/testing/constraints-3.9.txt | 7 + .../google-maps-places/v1/tests/__init__.py | 16 + .../v1/tests/unit/__init__.py | 16 + .../v1/tests/unit/gapic/__init__.py | 16 + .../v1/tests/unit/gapic/places_v1/__init__.py | 16 + .../tests/unit/gapic/places_v1/test_places.py | 4467 ++++++ .../v1/.coveragerc | 13 + .../google-maps-routeoptimization/v1/.flake8 | 33 + .../v1/MANIFEST.in | 2 + .../v1/README.rst | 49 + .../v1/docs/_static/custom.css | 3 + .../v1/docs/conf.py | 376 + .../v1/docs/index.rst | 7 + .../route_optimization.rst | 6 + .../docs/routeoptimization_v1/services_.rst | 6 + .../v1/docs/routeoptimization_v1/types_.rst | 6 + .../google/maps/routeoptimization/__init__.py | 81 + .../maps/routeoptimization/gapic_version.py | 16 + .../v1/google/maps/routeoptimization/py.typed | 2 + .../maps/routeoptimization_v1/__init__.py | 82 + .../routeoptimization_v1/gapic_metadata.json | 58 + .../routeoptimization_v1/gapic_version.py | 16 + .../google/maps/routeoptimization_v1/py.typed | 2 + .../routeoptimization_v1/services/__init__.py | 15 + .../services/route_optimization/__init__.py | 22 + .../route_optimization/async_client.py | 576 + .../services/route_optimization/client.py | 905 ++ .../route_optimization/transports/README.rst | 9 + .../route_optimization/transports/__init__.py | 38 + .../route_optimization/transports/base.py | 198 + .../route_optimization/transports/grpc.py | 471 + .../transports/grpc_asyncio.py | 510 + .../route_optimization/transports/rest.py | 692 + .../transports/rest_base.py | 221 + .../routeoptimization_v1/types/__init__.py | 74 + .../types/route_optimization_service.py | 3776 +++++ .../google-maps-routeoptimization/v1/mypy.ini | 3 + .../v1/noxfile.py | 280 + ...optimization_batch_optimize_tours_async.py | 63 + ..._optimization_batch_optimize_tours_sync.py | 63 + ...route_optimization_optimize_tours_async.py | 52 + ..._route_optimization_optimize_tours_sync.py | 52 + ...data_google.maps.routeoptimization.v1.json | 321 + .../fixup_routeoptimization_v1_keywords.py | 177 + .../google-maps-routeoptimization/v1/setup.py | 98 + .../v1/testing/constraints-3.10.txt | 6 + .../v1/testing/constraints-3.11.txt | 6 + .../v1/testing/constraints-3.12.txt | 6 + .../v1/testing/constraints-3.13.txt | 6 + .../v1/testing/constraints-3.7.txt | 10 + .../v1/testing/constraints-3.8.txt | 6 + .../v1/testing/constraints-3.9.txt | 6 + .../v1/tests/__init__.py | 16 + .../v1/tests/unit/__init__.py | 16 + .../v1/tests/unit/gapic/__init__.py | 16 + .../gapic/routeoptimization_v1/__init__.py | 16 + .../test_route_optimization.py | 2698 ++++ .../google-maps-routing/v2/.coveragerc | 13 + .../google-maps-routing/v2/.flake8 | 33 + .../google-maps-routing/v2/MANIFEST.in | 2 + .../google-maps-routing/v2/README.rst | 49 + .../v2/docs/_static/custom.css | 3 + .../google-maps-routing/v2/docs/conf.py | 376 + .../google-maps-routing/v2/docs/index.rst | 7 + .../v2/docs/routing_v2/routes.rst | 6 + .../v2/docs/routing_v2/services_.rst | 6 + .../v2/docs/routing_v2/types_.rst | 6 + .../v2/google/maps/routing/__init__.py | 115 + .../v2/google/maps/routing/gapic_version.py | 16 + .../v2/google/maps/routing/py.typed | 2 + .../v2/google/maps/routing_v2/__init__.py | 116 + .../maps/routing_v2/gapic_metadata.json | 58 + .../google/maps/routing_v2/gapic_version.py | 16 + .../v2/google/maps/routing_v2/py.typed | 2 + .../maps/routing_v2/services/__init__.py | 15 + .../routing_v2/services/routes/__init__.py | 22 + .../services/routes/async_client.py | 486 + .../maps/routing_v2/services/routes/client.py | 813 ++ .../services/routes/transports/README.rst | 9 + .../services/routes/transports/__init__.py | 38 + .../services/routes/transports/base.py | 167 + .../services/routes/transports/grpc.py | 446 + .../routes/transports/grpc_asyncio.py | 471 + .../services/routes/transports/rest.py | 465 + .../services/routes/transports/rest_base.py | 185 + .../google/maps/routing_v2/types/__init__.py | 154 + .../maps/routing_v2/types/fallback_info.py | 105 + .../routing_v2/types/geocoding_results.py | 127 + .../maps/routing_v2/types/localized_time.py | 58 + .../google/maps/routing_v2/types/location.py | 63 + .../google/maps/routing_v2/types/maneuver.py | 103 + .../types/navigation_instruction.py | 58 + .../google/maps/routing_v2/types/polyline.py | 113 + .../maps/routing_v2/types/polyline_details.py | 150 + .../v2/google/maps/routing_v2/types/route.py | 799 + .../maps/routing_v2/types/route_label.py | 62 + .../maps/routing_v2/types/route_modifiers.py | 98 + .../routing_v2/types/route_travel_mode.py | 63 + .../maps/routing_v2/types/routes_service.py | 748 + .../routing_v2/types/routing_preference.py | 71 + .../types/speed_reading_interval.py | 92 + .../google/maps/routing_v2/types/toll_info.py | 57 + .../maps/routing_v2/types/toll_passes.py | 376 + .../maps/routing_v2/types/traffic_model.py | 64 + .../google/maps/routing_v2/types/transit.py | 259 + .../routing_v2/types/transit_preferences.py | 97 + .../v2/google/maps/routing_v2/types/units.py | 49 + .../routing_v2/types/vehicle_emission_type.py | 56 + .../maps/routing_v2/types/vehicle_info.py | 51 + .../google/maps/routing_v2/types/waypoint.py | 126 + .../google-maps-routing/v2/mypy.ini | 3 + .../google-maps-routing/v2/noxfile.py | 280 + ...rated_routes_compute_route_matrix_async.py | 52 + ...erated_routes_compute_route_matrix_sync.py | 52 + ...2_generated_routes_compute_routes_async.py | 51 + ...v2_generated_routes_compute_routes_sync.py | 51 + ...ippet_metadata_google.maps.routing.v2.json | 321 + .../v2/scripts/fixup_routing_v2_keywords.py | 177 + .../google-maps-routing/v2/setup.py | 99 + .../v2/testing/constraints-3.10.txt | 7 + .../v2/testing/constraints-3.11.txt | 7 + .../v2/testing/constraints-3.12.txt | 7 + .../v2/testing/constraints-3.13.txt | 7 + .../v2/testing/constraints-3.7.txt | 11 + .../v2/testing/constraints-3.8.txt | 7 + .../v2/testing/constraints-3.9.txt | 7 + .../google-maps-routing/v2/tests/__init__.py | 16 + .../v2/tests/unit/__init__.py | 16 + .../v2/tests/unit/gapic/__init__.py | 16 + .../tests/unit/gapic/routing_v2/__init__.py | 16 + .../unit/gapic/routing_v2/test_routes.py | 2336 +++ .../google-maps-solar/v1/.coveragerc | 13 + owl-bot-staging/google-maps-solar/v1/.flake8 | 33 + .../google-maps-solar/v1/MANIFEST.in | 2 + .../google-maps-solar/v1/README.rst | 49 + .../v1/docs/_static/custom.css | 3 + .../google-maps-solar/v1/docs/conf.py | 376 + .../google-maps-solar/v1/docs/index.rst | 7 + .../v1/docs/solar_v1/services_.rst | 6 + .../v1/docs/solar_v1/solar.rst | 6 + .../v1/docs/solar_v1/types_.rst | 6 + .../v1/google/maps/solar/__init__.py | 69 + .../v1/google/maps/solar/gapic_version.py | 16 + .../v1/google/maps/solar/py.typed | 2 + .../v1/google/maps/solar_v1/__init__.py | 70 + .../google/maps/solar_v1/gapic_metadata.json | 73 + .../v1/google/maps/solar_v1/gapic_version.py | 16 + .../v1/google/maps/solar_v1/py.typed | 2 + .../google/maps/solar_v1/services/__init__.py | 15 + .../maps/solar_v1/services/solar/__init__.py | 22 + .../solar_v1/services/solar/async_client.py | 549 + .../maps/solar_v1/services/solar/client.py | 876 ++ .../services/solar/transports/README.rst | 9 + .../services/solar/transports/__init__.py | 38 + .../services/solar/transports/base.py | 210 + .../services/solar/transports/grpc.py | 404 + .../services/solar/transports/grpc_asyncio.py | 461 + .../services/solar/transports/rest.py | 694 + .../services/solar/transports/rest_base.py | 203 + .../v1/google/maps/solar_v1/types/__init__.py | 62 + .../maps/solar_v1/types/solar_service.py | 1306 ++ owl-bot-staging/google-maps-solar/v1/mypy.ini | 3 + .../google-maps-solar/v1/noxfile.py | 280 + ...snippet_metadata_google.maps.solar.v1.json | 474 + ...ar_find_closest_building_insights_async.py | 51 + ...lar_find_closest_building_insights_sync.py | 51 + ...1_generated_solar_get_data_layers_async.py | 52 + ...v1_generated_solar_get_data_layers_sync.py | 52 + ...r_v1_generated_solar_get_geo_tiff_async.py | 52 + ...ar_v1_generated_solar_get_geo_tiff_sync.py | 52 + .../v1/scripts/fixup_solar_v1_keywords.py | 178 + owl-bot-staging/google-maps-solar/v1/setup.py | 98 + .../v1/testing/constraints-3.10.txt | 6 + .../v1/testing/constraints-3.11.txt | 6 + .../v1/testing/constraints-3.12.txt | 6 + .../v1/testing/constraints-3.13.txt | 6 + .../v1/testing/constraints-3.7.txt | 10 + .../v1/testing/constraints-3.8.txt | 6 + .../v1/testing/constraints-3.9.txt | 6 + .../google-maps-solar/v1/tests/__init__.py | 16 + .../v1/tests/unit/__init__.py | 16 + .../v1/tests/unit/gapic/__init__.py | 16 + .../v1/tests/unit/gapic/solar_v1/__init__.py | 16 + .../tests/unit/gapic/solar_v1/test_solar.py | 2872 ++++ .../v1beta/.coveragerc | 13 + .../v1beta/.flake8 | 33 + .../v1beta/MANIFEST.in | 2 + .../v1beta/README.rst | 49 + .../v1beta/docs/_static/custom.css | 3 + .../v1beta/docs/conf.py | 376 + .../v1beta/docs/index.rst | 7 + .../account_issue_service.rst | 10 + .../account_tax_service.rst | 10 + .../accounts_service.rst | 10 + .../autofeed_settings_service.rst | 6 + .../business_identity_service.rst | 6 + .../business_info_service.rst | 6 + .../email_preferences_service.rst | 6 + .../homepage_service.rst | 6 + .../online_return_policy_service.rst | 10 + .../programs_service.rst | 10 + .../regions_service.rst | 10 + .../merchant_accounts_v1beta/services_.rst | 20 + .../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 + .../shopping/merchant_accounts/__init__.py | 271 + .../merchant_accounts/gapic_version.py | 16 + .../shopping/merchant_accounts/py.typed | 2 + .../merchant_accounts_v1beta/__init__.py | 272 + .../gapic_metadata.json | 969 ++ .../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 | 381 + .../services/account_issue_service/client.py | 725 + .../services/account_issue_service/pagers.py | 166 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../account_issue_service/transports/base.py | 154 + .../account_issue_service/transports/grpc.py | 348 + .../transports/grpc_asyncio.py | 368 + .../account_issue_service/transports/rest.py | 326 + .../transports/rest_base.py | 128 + .../services/account_tax_service/__init__.py | 22 + .../account_tax_service/async_client.py | 616 + .../services/account_tax_service/client.py | 949 ++ .../services/account_tax_service/pagers.py | 166 + .../account_tax_service/transports/README.rst | 9 + .../transports/__init__.py | 38 + .../account_tax_service/transports/base.py | 183 + .../account_tax_service/transports/grpc.py | 408 + .../transports/grpc_asyncio.py | 438 + .../account_tax_service/transports/rest.py | 648 + .../transports/rest_base.py | 213 + .../services/accounts_service/__init__.py | 22 + .../services/accounts_service/async_client.py | 886 ++ .../services/accounts_service/client.py | 1236 ++ .../services/accounts_service/pagers.py | 305 + .../accounts_service/transports/README.rst | 9 + .../accounts_service/transports/__init__.py | 38 + .../accounts_service/transports/base.py | 225 + .../accounts_service/transports/grpc.py | 502 + .../transports/grpc_asyncio.py | 547 + .../accounts_service/transports/rest.py | 1040 ++ .../accounts_service/transports/rest_base.py | 326 + .../autofeed_settings_service/__init__.py | 22 + .../autofeed_settings_service/async_client.py | 487 + .../autofeed_settings_service/client.py | 821 ++ .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 168 + .../transports/grpc.py | 375 + .../transports/grpc_asyncio.py | 400 + .../transports/rest.py | 488 + .../transports/rest_base.py | 175 + .../business_identity_service/__init__.py | 22 + .../business_identity_service/async_client.py | 482 + .../business_identity_service/client.py | 816 ++ .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 168 + .../transports/grpc.py | 376 + .../transports/grpc_asyncio.py | 401 + .../transports/rest.py | 486 + .../transports/rest_base.py | 175 + .../business_info_service/__init__.py | 22 + .../business_info_service/async_client.py | 482 + .../services/business_info_service/client.py | 816 ++ .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../business_info_service/transports/base.py | 168 + .../business_info_service/transports/grpc.py | 374 + .../transports/grpc_asyncio.py | 399 + .../business_info_service/transports/rest.py | 483 + .../transports/rest_base.py | 175 + .../email_preferences_service/__init__.py | 22 + .../email_preferences_service/async_client.py | 505 + .../email_preferences_service/client.py | 839 ++ .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 168 + .../transports/grpc.py | 391 + .../transports/grpc_asyncio.py | 416 + .../transports/rest.py | 494 + .../transports/rest_base.py | 175 + .../services/homepage_service/__init__.py | 22 + .../services/homepage_service/async_client.py | 652 + .../services/homepage_service/client.py | 986 ++ .../homepage_service/transports/README.rst | 9 + .../homepage_service/transports/__init__.py | 38 + .../homepage_service/transports/base.py | 197 + .../homepage_service/transports/grpc.py | 440 + .../transports/grpc_asyncio.py | 475 + .../homepage_service/transports/rest.py | 786 + .../homepage_service/transports/rest_base.py | 270 + .../online_return_policy_service/__init__.py | 22 + .../async_client.py | 495 + .../online_return_policy_service/client.py | 829 ++ .../online_return_policy_service/pagers.py | 166 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 168 + .../transports/grpc.py | 380 + .../transports/grpc_asyncio.py | 405 + .../transports/rest.py | 492 + .../transports/rest_base.py | 165 + .../services/programs_service/__init__.py | 22 + .../services/programs_service/async_client.py | 732 + .../services/programs_service/client.py | 1064 ++ .../services/programs_service/pagers.py | 166 + .../programs_service/transports/README.rst | 9 + .../programs_service/transports/__init__.py | 38 + .../programs_service/transports/base.py | 196 + .../programs_service/transports/grpc.py | 438 + .../transports/grpc_asyncio.py | 473 + .../programs_service/transports/rest.py | 825 ++ .../programs_service/transports/rest_base.py | 259 + .../services/regions_service/__init__.py | 22 + .../services/regions_service/async_client.py | 838 ++ .../services/regions_service/client.py | 1178 ++ .../services/regions_service/pagers.py | 166 + .../regions_service/transports/README.rst | 9 + .../regions_service/transports/__init__.py | 38 + .../regions_service/transports/base.py | 211 + .../regions_service/transports/grpc.py | 460 + .../transports/grpc_asyncio.py | 500 + .../regions_service/transports/rest.py | 916 ++ .../regions_service/transports/rest_base.py | 297 + .../shipping_settings_service/__init__.py | 22 + .../shipping_settings_service/async_client.py | 456 + .../shipping_settings_service/client.py | 791 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 168 + .../transports/grpc.py | 376 + .../transports/grpc_asyncio.py | 401 + .../transports/rest.py | 485 + .../transports/rest_base.py | 175 + .../__init__.py | 22 + .../async_client.py | 530 + .../client.py | 882 ++ .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 168 + .../transports/grpc.py | 376 + .../transports/grpc_asyncio.py | 401 + .../transports/rest.py | 537 + .../transports/rest_base.py | 165 + .../terms_of_service_service/__init__.py | 22 + .../terms_of_service_service/async_client.py | 537 + .../terms_of_service_service/client.py | 880 ++ .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 183 + .../transports/grpc.py | 404 + .../transports/grpc_asyncio.py | 434 + .../transports/rest.py | 584 + .../transports/rest_base.py | 203 + .../services/user_service/__init__.py | 22 + .../services/user_service/async_client.py | 818 ++ .../services/user_service/client.py | 1158 ++ .../services/user_service/pagers.py | 166 + .../user_service/transports/README.rst | 9 + .../user_service/transports/__init__.py | 38 + .../services/user_service/transports/base.py | 212 + .../services/user_service/transports/grpc.py | 456 + .../user_service/transports/grpc_asyncio.py | 496 + .../services/user_service/transports/rest.py | 895 ++ .../user_service/transports/rest_base.py | 298 + .../types/__init__.py | 248 + .../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/businessidentity.py | 204 + .../types/businessinfo.py | 148 + .../types/customerservice.py | 74 + .../types/emailpreferences.py | 121 + .../types/homepage.py | 139 + .../types/online_return_policy.py | 405 + .../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 | 280 + ...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 + ...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 + ...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 + ...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 + ..._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 | 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 | 7284 ++++++++++ ...fixup_merchant_accounts_v1beta_keywords.py | 220 + .../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 | 7 + .../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 | 2368 +++ .../test_account_tax_service.py | 3745 +++++ .../test_accounts_service.py | 5584 +++++++ .../test_autofeed_settings_service.py | 2836 ++++ .../test_business_identity_service.py | 2822 ++++ .../test_business_info_service.py | 2840 ++++ .../test_email_preferences_service.py | 2824 ++++ .../test_homepage_service.py | 3903 +++++ .../test_online_return_policy_service.py | 3064 ++++ .../test_programs_service.py | 4373 ++++++ .../test_regions_service.py | 5154 +++++++ .../test_shipping_settings_service.py | 2679 ++++ ...erms_of_service_agreement_state_service.py | 2800 ++++ .../test_terms_of_service_service.py | 3277 +++++ .../test_user_service.py | 5164 +++++++ .../v1beta/.coveragerc | 13 + .../v1beta/.flake8 | 33 + .../v1beta/MANIFEST.in | 2 + .../v1beta/README.rst | 49 + .../v1beta/docs/_static/custom.css | 3 + .../v1beta/docs/conf.py | 376 + .../v1beta/docs/index.rst | 7 + .../conversion_sources_service.rst | 10 + .../merchant_conversions_v1beta/services_.rst | 6 + .../merchant_conversions_v1beta/types_.rst | 6 + .../shopping/merchant_conversions/__init__.py | 49 + .../merchant_conversions/gapic_version.py | 16 + .../shopping/merchant_conversions/py.typed | 2 + .../merchant_conversions_v1beta/__init__.py | 50 + .../gapic_metadata.json | 118 + .../gapic_version.py | 16 + .../merchant_conversions_v1beta/py.typed | 2 + .../services/__init__.py | 15 + .../conversion_sources_service/__init__.py | 22 + .../async_client.py | 928 ++ .../conversion_sources_service/client.py | 1259 ++ .../conversion_sources_service/pagers.py | 166 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 225 + .../transports/grpc.py | 488 + .../transports/grpc_asyncio.py | 533 + .../transports/rest.py | 1067 ++ .../transports/rest_base.py | 344 + .../types/__init__.py | 42 + .../types/conversionsources.py | 484 + .../v1beta/mypy.ini | 3 + .../v1beta/noxfile.py | 280 + ..._service_create_conversion_source_async.py | 56 + ...s_service_create_conversion_source_sync.py | 56 + ..._service_delete_conversion_source_async.py | 50 + ...s_service_delete_conversion_source_sync.py | 50 + ...ces_service_get_conversion_source_async.py | 52 + ...rces_service_get_conversion_source_sync.py | 52 + ...s_service_list_conversion_sources_async.py | 53 + ...es_service_list_conversion_sources_sync.py | 53 + ...ervice_undelete_conversion_source_async.py | 52 + ...service_undelete_conversion_source_sync.py | 52 + ..._service_update_conversion_source_async.py | 55 + ...s_service_update_conversion_source_sync.py | 55 + ....shopping.merchant.conversions.v1beta.json | 983 ++ ...up_merchant_conversions_v1beta_keywords.py | 181 + .../v1beta/setup.py | 98 + .../v1beta/testing/constraints-3.10.txt | 6 + .../v1beta/testing/constraints-3.11.txt | 6 + .../v1beta/testing/constraints-3.12.txt | 6 + .../v1beta/testing/constraints-3.13.txt | 6 + .../v1beta/testing/constraints-3.7.txt | 10 + .../v1beta/testing/constraints-3.8.txt | 6 + .../v1beta/testing/constraints-3.9.txt | 6 + .../v1beta/tests/__init__.py | 16 + .../v1beta/tests/unit/__init__.py | 16 + .../v1beta/tests/unit/gapic/__init__.py | 16 + .../merchant_conversions_v1beta/__init__.py | 16 + .../test_conversion_sources_service.py | 5664 ++++++++ .../v1beta/.coveragerc | 13 + .../v1beta/.flake8 | 33 + .../v1beta/MANIFEST.in | 2 + .../v1beta/README.rst | 49 + .../v1beta/docs/_static/custom.css | 3 + .../v1beta/docs/conf.py | 376 + .../v1beta/docs/index.rst | 7 + .../data_sources_service.rst | 10 + .../file_uploads_service.rst | 6 + .../merchant_datasources_v1beta/services_.rst | 7 + .../merchant_datasources_v1beta/types_.rst | 6 + .../shopping/merchant_datasources/__init__.py | 65 + .../merchant_datasources/gapic_version.py | 16 + .../shopping/merchant_datasources/py.typed | 2 + .../merchant_datasources_v1beta/__init__.py | 66 + .../gapic_metadata.json | 152 + .../gapic_version.py | 16 + .../merchant_datasources_v1beta/py.typed | 2 + .../services/__init__.py | 15 + .../services/data_sources_service/__init__.py | 22 + .../data_sources_service/async_client.py | 913 ++ .../services/data_sources_service/client.py | 1244 ++ .../services/data_sources_service/pagers.py | 166 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../data_sources_service/transports/base.py | 225 + .../data_sources_service/transports/grpc.py | 493 + .../transports/grpc_asyncio.py | 538 + .../data_sources_service/transports/rest.py | 1016 ++ .../transports/rest_base.py | 344 + .../services/file_uploads_service/__init__.py | 22 + .../file_uploads_service/async_client.py | 372 + .../services/file_uploads_service/client.py | 707 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../file_uploads_service/transports/base.py | 154 + .../file_uploads_service/transports/grpc.py | 348 + .../transports/grpc_asyncio.py | 368 + .../file_uploads_service/transports/rest.py | 334 + .../transports/rest_base.py | 128 + .../types/__init__.py | 60 + .../types/datasources.py | 351 + .../types/datasourcetypes.py | 372 + .../types/fileinputs.py | 201 + .../types/fileuploads.py | 205 + .../v1beta/mypy.ini | 3 + .../v1beta/noxfile.py | 280 + ...ources_service_create_data_source_async.py | 57 + ...sources_service_create_data_source_sync.py | 57 + ...ources_service_delete_data_source_async.py | 50 + ...sources_service_delete_data_source_sync.py | 50 + ...sources_service_fetch_data_source_async.py | 50 + ..._sources_service_fetch_data_source_sync.py | 50 + ...a_sources_service_get_data_source_async.py | 52 + ...ta_sources_service_get_data_source_sync.py | 52 + ...sources_service_list_data_sources_async.py | 53 + ..._sources_service_list_data_sources_sync.py | 53 + ...ources_service_update_data_source_async.py | 56 + ...sources_service_update_data_source_sync.py | 56 + ...e_uploads_service_get_file_upload_async.py | 52 + ...le_uploads_service_get_file_upload_sync.py | 52 + ....shopping.merchant.datasources.v1beta.json | 1138 ++ ...up_merchant_datasources_v1beta_keywords.py | 182 + .../v1beta/setup.py | 98 + .../v1beta/testing/constraints-3.10.txt | 6 + .../v1beta/testing/constraints-3.11.txt | 6 + .../v1beta/testing/constraints-3.12.txt | 6 + .../v1beta/testing/constraints-3.13.txt | 6 + .../v1beta/testing/constraints-3.7.txt | 10 + .../v1beta/testing/constraints-3.8.txt | 6 + .../v1beta/testing/constraints-3.9.txt | 6 + .../v1beta/tests/__init__.py | 16 + .../v1beta/tests/unit/__init__.py | 16 + .../v1beta/tests/unit/gapic/__init__.py | 16 + .../merchant_datasources_v1beta/__init__.py | 16 + .../test_data_sources_service.py | 5650 ++++++++ .../test_file_uploads_service.py | 2121 +++ .../v1beta/.coveragerc | 13 + .../v1beta/.flake8 | 33 + .../v1beta/MANIFEST.in | 2 + .../v1beta/README.rst | 49 + .../v1beta/docs/_static/custom.css | 3 + .../v1beta/docs/conf.py | 376 + .../v1beta/docs/index.rst | 7 + .../local_inventory_service.rst | 10 + .../regional_inventory_service.rst | 10 + .../merchant_inventories_v1beta/services_.rst | 7 + .../merchant_inventories_v1beta/types_.rst | 6 + .../shopping/merchant_inventories/__init__.py | 51 + .../merchant_inventories/gapic_version.py | 16 + .../shopping/merchant_inventories/py.typed | 2 + .../merchant_inventories_v1beta/__init__.py | 52 + .../gapic_metadata.json | 137 + .../gapic_version.py | 16 + .../merchant_inventories_v1beta/py.typed | 2 + .../services/__init__.py | 15 + .../local_inventory_service/__init__.py | 22 + .../local_inventory_service/async_client.py | 585 + .../local_inventory_service/client.py | 919 ++ .../local_inventory_service/pagers.py | 166 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 183 + .../transports/grpc.py | 419 + .../transports/grpc_asyncio.py | 449 + .../transports/rest.py | 594 + .../transports/rest_base.py | 213 + .../regional_inventory_service/__init__.py | 22 + .../async_client.py | 591 + .../regional_inventory_service/client.py | 925 ++ .../regional_inventory_service/pagers.py | 166 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 183 + .../transports/grpc.py | 420 + .../transports/grpc_asyncio.py | 450 + .../transports/rest.py | 598 + .../transports/rest_base.py | 213 + .../types/__init__.py | 42 + .../types/localinventory.py | 281 + .../types/regionalinventory.py | 236 + .../v1beta/mypy.ini | 3 + .../v1beta/noxfile.py | 280 + ...ry_service_delete_local_inventory_async.py | 50 + ...ory_service_delete_local_inventory_sync.py | 50 + ...ry_service_insert_local_inventory_async.py | 56 + ...ory_service_insert_local_inventory_sync.py | 56 + ...ry_service_list_local_inventories_async.py | 53 + ...ory_service_list_local_inventories_sync.py | 53 + ...service_delete_regional_inventory_async.py | 50 + ..._service_delete_regional_inventory_sync.py | 50 + ...service_insert_regional_inventory_async.py | 56 + ..._service_insert_regional_inventory_sync.py | 56 + ...service_list_regional_inventories_async.py | 53 + ..._service_list_regional_inventories_sync.py | 53 + ....shopping.merchant.inventories.v1beta.json | 953 ++ ...up_merchant_inventories_v1beta_keywords.py | 181 + .../v1beta/setup.py | 99 + .../v1beta/testing/constraints-3.10.txt | 7 + .../v1beta/testing/constraints-3.11.txt | 7 + .../v1beta/testing/constraints-3.12.txt | 7 + .../v1beta/testing/constraints-3.13.txt | 7 + .../v1beta/testing/constraints-3.7.txt | 11 + .../v1beta/testing/constraints-3.8.txt | 7 + .../v1beta/testing/constraints-3.9.txt | 7 + .../v1beta/tests/__init__.py | 16 + .../v1beta/tests/unit/__init__.py | 16 + .../v1beta/tests/unit/gapic/__init__.py | 16 + .../merchant_inventories_v1beta/__init__.py | 16 + .../test_local_inventory_service.py | 3612 +++++ .../test_regional_inventory_service.py | 3584 +++++ .../v1beta/.coveragerc | 13 + .../v1beta/.flake8 | 33 + .../v1beta/MANIFEST.in | 2 + .../v1beta/README.rst | 49 + .../v1beta/docs/_static/custom.css | 3 + .../v1beta/docs/conf.py | 376 + .../v1beta/docs/index.rst | 7 + .../lfp_inventory_service.rst | 6 + .../merchant_lfp_v1beta/lfp_sale_service.rst | 6 + .../merchant_lfp_v1beta/lfp_store_service.rst | 10 + .../docs/merchant_lfp_v1beta/services_.rst | 8 + .../docs/merchant_lfp_v1beta/types_.rst | 6 + .../google/shopping/merchant_lfp/__init__.py | 55 + .../shopping/merchant_lfp/gapic_version.py | 16 + .../google/shopping/merchant_lfp/py.typed | 2 + .../shopping/merchant_lfp_v1beta/__init__.py | 56 + .../merchant_lfp_v1beta/gapic_metadata.json | 156 + .../merchant_lfp_v1beta/gapic_version.py | 16 + .../shopping/merchant_lfp_v1beta/py.typed | 2 + .../merchant_lfp_v1beta/services/__init__.py | 15 + .../lfp_inventory_service/__init__.py | 22 + .../lfp_inventory_service/async_client.py | 357 + .../services/lfp_inventory_service/client.py | 693 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../lfp_inventory_service/transports/base.py | 154 + .../lfp_inventory_service/transports/grpc.py | 351 + .../transports/grpc_asyncio.py | 371 + .../lfp_inventory_service/transports/rest.py | 331 + .../transports/rest_base.py | 138 + .../services/lfp_sale_service/__init__.py | 22 + .../services/lfp_sale_service/async_client.py | 357 + .../services/lfp_sale_service/client.py | 693 + .../lfp_sale_service/transports/README.rst | 9 + .../lfp_sale_service/transports/__init__.py | 38 + .../lfp_sale_service/transports/base.py | 154 + .../lfp_sale_service/transports/grpc.py | 349 + .../transports/grpc_asyncio.py | 369 + .../lfp_sale_service/transports/rest.py | 332 + .../lfp_sale_service/transports/rest_base.py | 138 + .../services/lfp_store_service/__init__.py | 22 + .../lfp_store_service/async_client.py | 714 + .../services/lfp_store_service/client.py | 1046 ++ .../services/lfp_store_service/pagers.py | 166 + .../lfp_store_service/transports/README.rst | 9 + .../lfp_store_service/transports/__init__.py | 38 + .../lfp_store_service/transports/base.py | 197 + .../lfp_store_service/transports/grpc.py | 431 + .../transports/grpc_asyncio.py | 466 + .../lfp_store_service/transports/rest.py | 756 + .../lfp_store_service/transports/rest_base.py | 250 + .../merchant_lfp_v1beta/types/__init__.py | 44 + .../merchant_lfp_v1beta/types/lfpinventory.py | 200 + .../merchant_lfp_v1beta/types/lfpsale.py | 165 + .../merchant_lfp_v1beta/types/lfpstore.py | 308 + .../v1beta/mypy.ini | 3 + .../v1beta/noxfile.py | 280 + ...tory_service_insert_lfp_inventory_async.py | 61 + ...ntory_service_insert_lfp_inventory_sync.py | 61 + ..._lfp_sale_service_insert_lfp_sale_async.py | 62 + ...d_lfp_sale_service_insert_lfp_sale_sync.py | 62 + ...fp_store_service_delete_lfp_store_async.py | 50 + ...lfp_store_service_delete_lfp_store_sync.py | 50 + ...d_lfp_store_service_get_lfp_store_async.py | 52 + ...ed_lfp_store_service_get_lfp_store_sync.py | 52 + ...fp_store_service_insert_lfp_store_async.py | 58 + ...lfp_store_service_insert_lfp_store_sync.py | 58 + ...lfp_store_service_list_lfp_stores_async.py | 54 + ..._lfp_store_service_list_lfp_stores_sync.py | 54 + ...a_google.shopping.merchant.lfp.v1beta.json | 967 ++ .../fixup_merchant_lfp_v1beta_keywords.py | 181 + .../v1beta/setup.py | 99 + .../v1beta/testing/constraints-3.10.txt | 7 + .../v1beta/testing/constraints-3.11.txt | 7 + .../v1beta/testing/constraints-3.12.txt | 7 + .../v1beta/testing/constraints-3.13.txt | 7 + .../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 + .../gapic/merchant_lfp_v1beta/__init__.py | 16 + .../test_lfp_inventory_service.py | 2095 +++ .../test_lfp_sale_service.py | 2077 +++ .../test_lfp_store_service.py | 4514 ++++++ .../v1beta/.coveragerc | 13 + .../v1beta/.flake8 | 33 + .../v1beta/MANIFEST.in | 2 + .../v1beta/README.rst | 49 + .../v1beta/docs/_static/custom.css | 3 + .../v1beta/docs/conf.py | 376 + .../v1beta/docs/index.rst | 7 + .../notifications_api_service.rst | 10 + .../services_.rst | 6 + .../merchant_notifications_v1beta/types_.rst | 6 + .../merchant_notifications/__init__.py | 49 + .../merchant_notifications/gapic_version.py | 16 + .../shopping/merchant_notifications/py.typed | 2 + .../merchant_notifications_v1beta/__init__.py | 50 + .../gapic_metadata.json | 103 + .../gapic_version.py | 16 + .../merchant_notifications_v1beta/py.typed | 2 + .../services/__init__.py | 15 + .../notifications_api_service/__init__.py | 22 + .../notifications_api_service/async_client.py | 836 ++ .../notifications_api_service/client.py | 1167 ++ .../notifications_api_service/pagers.py | 166 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 211 + .../transports/grpc.py | 475 + .../transports/grpc_asyncio.py | 515 + .../transports/rest.py | 909 ++ .../transports/rest_base.py | 297 + .../types/__init__.py | 42 + .../types/notificationsapi.py | 424 + .../v1beta/mypy.ini | 3 + .../v1beta/noxfile.py | 280 + ..._create_notification_subscription_async.py | 56 + ...e_create_notification_subscription_sync.py | 56 + ..._delete_notification_subscription_async.py | 50 + ...e_delete_notification_subscription_sync.py | 50 + ...ice_get_notification_subscription_async.py | 52 + ...vice_get_notification_subscription_sync.py | 52 + ...e_list_notification_subscriptions_async.py | 53 + ...ce_list_notification_subscriptions_sync.py | 53 + ..._update_notification_subscription_async.py | 55 + ...e_update_notification_subscription_sync.py | 55 + ...hopping.merchant.notifications.v1beta.json | 830 ++ ..._merchant_notifications_v1beta_keywords.py | 180 + .../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 | 7 + .../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_notifications_v1beta/__init__.py | 16 + .../test_notifications_api_service.py | 5136 +++++++ .../v1beta/.coveragerc | 13 + .../v1beta/.flake8 | 33 + .../v1beta/MANIFEST.in | 2 + .../v1beta/README.rst | 49 + .../v1beta/docs/_static/custom.css | 3 + .../v1beta/docs/conf.py | 376 + .../v1beta/docs/index.rst | 7 + .../promotions_service.rst | 10 + .../merchant_promotions_v1beta/services_.rst | 6 + .../merchant_promotions_v1beta/types_.rst | 6 + .../shopping/merchant_promotions/__init__.py | 51 + .../merchant_promotions/gapic_version.py | 16 + .../shopping/merchant_promotions/py.typed | 2 + .../merchant_promotions_v1beta/__init__.py | 52 + .../gapic_metadata.json | 73 + .../gapic_version.py | 16 + .../merchant_promotions_v1beta/py.typed | 2 + .../services/__init__.py | 15 + .../services/promotions_service/__init__.py | 22 + .../promotions_service/async_client.py | 612 + .../services/promotions_service/client.py | 946 ++ .../services/promotions_service/pagers.py | 166 + .../promotions_service/transports/README.rst | 9 + .../promotions_service/transports/__init__.py | 38 + .../promotions_service/transports/base.py | 182 + .../promotions_service/transports/grpc.py | 411 + .../transports/grpc_asyncio.py | 441 + .../promotions_service/transports/rest.py | 657 + .../transports/rest_base.py | 212 + .../types/__init__.py | 46 + .../types/promotions.py | 277 + .../types/promotions_common.py | 671 + .../v1beta/mypy.ini | 3 + .../v1beta/noxfile.py | 280 + ..._promotions_service_get_promotion_async.py | 52 + ...d_promotions_service_get_promotion_sync.py | 52 + ...omotions_service_insert_promotion_async.py | 60 + ...romotions_service_insert_promotion_sync.py | 60 + ...romotions_service_list_promotions_async.py | 53 + ...promotions_service_list_promotions_sync.py | 53 + ...e.shopping.merchant.promotions.v1beta.json | 490 + ...xup_merchant_promotions_v1beta_keywords.py | 178 + .../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 | 7 + .../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_promotions_v1beta/__init__.py | 16 + .../test_promotions_service.py | 3614 +++++ .../v1beta/.coveragerc | 13 + .../v1beta/.flake8 | 33 + .../v1beta/MANIFEST.in | 2 + .../v1beta/README.rst | 49 + .../v1beta/docs/_static/custom.css | 3 + .../v1beta/docs/conf.py | 376 + .../v1beta/docs/index.rst | 7 + .../merchant_quota_v1beta/quota_service.rst | 10 + .../docs/merchant_quota_v1beta/services_.rst | 6 + .../docs/merchant_quota_v1beta/types_.rst | 6 + .../shopping/merchant_quota/__init__.py | 35 + .../shopping/merchant_quota/gapic_version.py | 16 + .../google/shopping/merchant_quota/py.typed | 2 + .../merchant_quota_v1beta/__init__.py | 36 + .../merchant_quota_v1beta/gapic_metadata.json | 43 + .../merchant_quota_v1beta/gapic_version.py | 16 + .../shopping/merchant_quota_v1beta/py.typed | 2 + .../services/__init__.py | 15 + .../services/quota_service/__init__.py | 22 + .../services/quota_service/async_client.py | 384 + .../services/quota_service/client.py | 719 + .../services/quota_service/pagers.py | 166 + .../quota_service/transports/README.rst | 9 + .../quota_service/transports/__init__.py | 38 + .../services/quota_service/transports/base.py | 154 + .../services/quota_service/transports/grpc.py | 349 + .../quota_service/transports/grpc_asyncio.py | 369 + .../services/quota_service/transports/rest.py | 330 + .../quota_service/transports/rest_base.py | 128 + .../merchant_quota_v1beta/types/__init__.py | 28 + .../merchant_quota_v1beta/types/quota.py | 184 + .../v1beta/mypy.ini | 3 + .../v1beta/noxfile.py | 280 + ...d_quota_service_list_quota_groups_async.py | 53 + ...ed_quota_service_list_quota_groups_sync.py | 53 + ...google.shopping.merchant.quota.v1beta.json | 176 + .../fixup_merchant_quota_v1beta_keywords.py | 176 + .../v1beta/setup.py | 98 + .../v1beta/testing/constraints-3.10.txt | 6 + .../v1beta/testing/constraints-3.11.txt | 6 + .../v1beta/testing/constraints-3.12.txt | 6 + .../v1beta/testing/constraints-3.13.txt | 6 + .../v1beta/testing/constraints-3.7.txt | 10 + .../v1beta/testing/constraints-3.8.txt | 6 + .../v1beta/testing/constraints-3.9.txt | 6 + .../v1beta/tests/__init__.py | 16 + .../v1beta/tests/unit/__init__.py | 16 + .../v1beta/tests/unit/gapic/__init__.py | 16 + .../gapic/merchant_quota_v1beta/__init__.py | 16 + .../test_quota_service.py | 2347 +++ .../v1beta/.coveragerc | 13 + .../v1beta/.flake8 | 33 + .../v1beta/MANIFEST.in | 2 + .../v1beta/README.rst | 49 + .../v1beta/docs/_static/custom.css | 3 + .../v1beta/docs/conf.py | 376 + .../v1beta/docs/index.rst | 7 + .../report_service.rst | 10 + .../merchant_reports_v1beta/services_.rst | 6 + .../docs/merchant_reports_v1beta/types_.rst | 6 + .../shopping/merchant_reports/__init__.py | 63 + .../merchant_reports/gapic_version.py | 16 + .../google/shopping/merchant_reports/py.typed | 2 + .../merchant_reports_v1beta/__init__.py | 64 + .../gapic_metadata.json | 43 + .../merchant_reports_v1beta/gapic_version.py | 16 + .../shopping/merchant_reports_v1beta/py.typed | 2 + .../services/__init__.py | 15 + .../services/report_service/__init__.py | 22 + .../services/report_service/async_client.py | 385 + .../services/report_service/client.py | 711 + .../services/report_service/pagers.py | 166 + .../report_service/transports/README.rst | 9 + .../report_service/transports/__init__.py | 38 + .../report_service/transports/base.py | 154 + .../report_service/transports/grpc.py | 352 + .../report_service/transports/grpc_asyncio.py | 372 + .../report_service/transports/rest.py | 333 + .../report_service/transports/rest_base.py | 138 + .../merchant_reports_v1beta/types/__init__.py | 56 + .../merchant_reports_v1beta/types/reports.py | 2521 ++++ .../v1beta/mypy.ini | 3 + .../v1beta/noxfile.py | 280 + ...a_generated_report_service_search_async.py | 54 + ...ta_generated_report_service_search_sync.py | 54 + ...ogle.shopping.merchant.reports.v1beta.json | 176 + .../fixup_merchant_reports_v1beta_keywords.py | 176 + .../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 | 7 + .../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 + .../gapic/merchant_reports_v1beta/__init__.py | 16 + .../test_report_service.py | 2333 +++ owl-bot-staging/grafeas/v1/.coveragerc | 13 + owl-bot-staging/grafeas/v1/.flake8 | 33 + owl-bot-staging/grafeas/v1/MANIFEST.in | 2 + owl-bot-staging/grafeas/v1/README.rst | 49 + .../grafeas/v1/docs/_static/custom.css | 3 + owl-bot-staging/grafeas/v1/docs/conf.py | 376 + .../grafeas/v1/docs/grafeas_v1/grafeas.rst | 10 + .../grafeas/v1/docs/grafeas_v1/services_.rst | 6 + .../grafeas/v1/docs/grafeas_v1/types_.rst | 6 + owl-bot-staging/grafeas/v1/docs/index.rst | 7 + .../grafeas/v1/grafeas/grafeas/__init__.py | 211 + .../v1/grafeas/grafeas/gapic_version.py | 16 + .../grafeas/v1/grafeas/grafeas/py.typed | 2 + .../grafeas/v1/grafeas/grafeas_v1/__init__.py | 212 + .../v1/grafeas/grafeas_v1/gapic_metadata.json | 238 + .../v1/grafeas/grafeas_v1/gapic_version.py | 16 + .../grafeas/v1/grafeas/grafeas_v1/py.typed | 2 + .../grafeas/grafeas_v1/services/__init__.py | 15 + .../grafeas_v1/services/grafeas/__init__.py | 22 + .../services/grafeas/async_client.py | 1886 +++ .../grafeas_v1/services/grafeas/client.py | 2225 +++ .../grafeas_v1/services/grafeas/pagers.py | 444 + .../services/grafeas/transports/README.rst | 9 + .../services/grafeas/transports/__init__.py | 38 + .../services/grafeas/transports/base.py | 416 + .../services/grafeas/transports/grpc.py | 708 + .../grafeas/transports/grpc_asyncio.py | 873 ++ .../services/grafeas/transports/rest.py | 2241 +++ .../services/grafeas/transports/rest_base.py | 732 + .../v1/grafeas/grafeas_v1/types/__init__.py | 244 + .../grafeas/grafeas_v1/types/attestation.py | 148 + .../v1/grafeas/grafeas_v1/types/build.py | 115 + .../v1/grafeas/grafeas_v1/types/common.py | 295 + .../v1/grafeas/grafeas_v1/types/compliance.py | 215 + .../v1/grafeas/grafeas_v1/types/cvss.py | 464 + .../v1/grafeas/grafeas_v1/types/deployment.py | 125 + .../v1/grafeas/grafeas_v1/types/discovery.py | 281 + .../grafeas_v1/types/dsse_attestation.py | 102 + .../v1/grafeas/grafeas_v1/types/grafeas.py | 921 ++ .../v1/grafeas/grafeas_v1/types/image.py | 158 + .../grafeas_v1/types/intoto_provenance.py | 248 + .../grafeas_v1/types/intoto_statement.py | 353 + .../v1/grafeas/grafeas_v1/types/package.py | 378 + .../v1/grafeas/grafeas_v1/types/provenance.py | 597 + .../v1/grafeas/grafeas_v1/types/sbom.py | 171 + .../v1/grafeas/grafeas_v1/types/severity.py | 56 + .../grafeas_v1/types/slsa_provenance.py | 258 + .../types/slsa_provenance_zero_two.py | 242 + .../v1/grafeas/grafeas_v1/types/upgrade.py | 266 + .../v1/grafeas/grafeas_v1/types/vex.py | 384 + .../grafeas/grafeas_v1/types/vulnerability.py | 594 + owl-bot-staging/grafeas/v1/mypy.ini | 3 + owl-bot-staging/grafeas/v1/noxfile.py | 280 + ...erated_grafeas_batch_create_notes_async.py | 52 + ...nerated_grafeas_batch_create_notes_sync.py | 52 + ..._grafeas_batch_create_occurrences_async.py | 52 + ...d_grafeas_batch_create_occurrences_sync.py | 52 + ..._v1_generated_grafeas_create_note_async.py | 53 + ...s_v1_generated_grafeas_create_note_sync.py | 53 + ...nerated_grafeas_create_occurrence_async.py | 52 + ...enerated_grafeas_create_occurrence_sync.py | 52 + ..._v1_generated_grafeas_delete_note_async.py | 50 + ...s_v1_generated_grafeas_delete_note_sync.py | 50 + ...nerated_grafeas_delete_occurrence_async.py | 50 + ...enerated_grafeas_delete_occurrence_sync.py | 50 + ...sis_v1_generated_grafeas_get_note_async.py | 52 + ...ysis_v1_generated_grafeas_get_note_sync.py | 52 + ..._generated_grafeas_get_occurrence_async.py | 52 + ...rated_grafeas_get_occurrence_note_async.py | 52 + ...erated_grafeas_get_occurrence_note_sync.py | 52 + ...1_generated_grafeas_get_occurrence_sync.py | 52 + ...ted_grafeas_list_note_occurrences_async.py | 53 + ...ated_grafeas_list_note_occurrences_sync.py | 53 + ...s_v1_generated_grafeas_list_notes_async.py | 53 + ...is_v1_generated_grafeas_list_notes_sync.py | 53 + ...enerated_grafeas_list_occurrences_async.py | 53 + ...generated_grafeas_list_occurrences_sync.py | 53 + ..._v1_generated_grafeas_update_note_async.py | 52 + ...s_v1_generated_grafeas_update_note_sync.py | 52 + ...nerated_grafeas_update_occurrence_async.py | 52 + ...enerated_grafeas_update_occurrence_sync.py | 52 + .../snippet_metadata_grafeas.v1.json | 2353 +++ .../v1/scripts/fixup_grafeas_v1_keywords.py | 189 + owl-bot-staging/grafeas/v1/setup.py | 98 + .../grafeas/v1/testing/constraints-3.10.txt | 6 + .../grafeas/v1/testing/constraints-3.11.txt | 6 + .../grafeas/v1/testing/constraints-3.12.txt | 6 + .../grafeas/v1/testing/constraints-3.13.txt | 6 + .../grafeas/v1/testing/constraints-3.7.txt | 10 + .../grafeas/v1/testing/constraints-3.8.txt | 6 + .../grafeas/v1/testing/constraints-3.9.txt | 6 + owl-bot-staging/grafeas/v1/tests/__init__.py | 16 + .../grafeas/v1/tests/unit/__init__.py | 16 + .../grafeas/v1/tests/unit/gapic/__init__.py | 16 + .../tests/unit/gapic/grafeas_v1/__init__.py | 16 + .../unit/gapic/grafeas_v1/test_grafeas.py | 11993 ++++++++++++++++ 1252 files changed, 338707 insertions(+) create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/.coveragerc create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/.flake8 create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/MANIFEST.in create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/README.rst create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/_static/custom.css create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/conf.py create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/index.rst create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/mapsplatformdatasets_v1/maps_platform_datasets.rst create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/mapsplatformdatasets_v1/services_.rst create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/mapsplatformdatasets_v1/types_.rst create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets/__init__.py create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets/gapic_version.py create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets/py.typed create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/__init__.py create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/gapic_metadata.json create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/gapic_version.py create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/py.typed create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/__init__.py create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/__init__.py create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/async_client.py create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/client.py create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/pagers.py create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/README.rst create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/__init__.py create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/base.py create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/grpc.py create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/rest.py create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/rest_base.py create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/types/__init__.py create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/types/data_source.py create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/types/dataset.py create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/types/maps_platform_datasets.py create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/types/maps_platform_datasets_service.py create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/mypy.ini create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/noxfile.py create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_create_dataset_async.py create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_create_dataset_sync.py create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_delete_dataset_async.py create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_delete_dataset_sync.py create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_fetch_dataset_errors_async.py create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_fetch_dataset_errors_sync.py create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_get_dataset_async.py create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_get_dataset_sync.py create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_list_datasets_async.py create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_list_datasets_sync.py create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_update_dataset_metadata_async.py create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_update_dataset_metadata_sync.py create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/snippet_metadata_google.maps.mapsplatformdatasets.v1.json create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/scripts/fixup_mapsplatformdatasets_v1_keywords.py create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/setup.py create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.13.txt create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/tests/__init__.py create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/tests/unit/gapic/mapsplatformdatasets_v1/__init__.py create mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/tests/unit/gapic/mapsplatformdatasets_v1/test_maps_platform_datasets.py create mode 100644 owl-bot-staging/google-maps-places/v1/.coveragerc create mode 100644 owl-bot-staging/google-maps-places/v1/.flake8 create mode 100644 owl-bot-staging/google-maps-places/v1/MANIFEST.in create mode 100644 owl-bot-staging/google-maps-places/v1/README.rst create mode 100644 owl-bot-staging/google-maps-places/v1/docs/_static/custom.css create mode 100644 owl-bot-staging/google-maps-places/v1/docs/conf.py create mode 100644 owl-bot-staging/google-maps-places/v1/docs/index.rst create mode 100644 owl-bot-staging/google-maps-places/v1/docs/places_v1/places.rst create mode 100644 owl-bot-staging/google-maps-places/v1/docs/places_v1/services_.rst create mode 100644 owl-bot-staging/google-maps-places/v1/docs/places_v1/types_.rst create mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places/__init__.py create mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places/gapic_version.py create mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places/py.typed create mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/__init__.py create mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/gapic_metadata.json create mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/gapic_version.py create mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/py.typed create mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/__init__.py create mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/__init__.py create mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/async_client.py create mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/client.py create mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/README.rst create mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/__init__.py create mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/base.py create mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/grpc.py create mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/rest.py create mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/rest_base.py create mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/__init__.py create mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/attribution.py create mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/content_block.py create mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/contextual_content.py create mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/ev_charging.py create mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/fuel_options.py create mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/geometry.py create mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/photo.py create mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/place.py create mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/places_service.py create mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/polyline.py create mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/price_range.py create mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/reference.py create mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/review.py create mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/route_modifiers.py create mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/routing_preference.py create mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/routing_summary.py create mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/travel_mode.py create mode 100644 owl-bot-staging/google-maps-places/v1/mypy.ini create mode 100644 owl-bot-staging/google-maps-places/v1/noxfile.py create mode 100644 owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_autocomplete_places_async.py create mode 100644 owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_autocomplete_places_sync.py create mode 100644 owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_photo_media_async.py create mode 100644 owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_photo_media_sync.py create mode 100644 owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_place_async.py create mode 100644 owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_place_sync.py create mode 100644 owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_nearby_async.py create mode 100644 owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_nearby_sync.py create mode 100644 owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_text_async.py create mode 100644 owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_text_sync.py create mode 100644 owl-bot-staging/google-maps-places/v1/samples/generated_samples/snippet_metadata_google.maps.places.v1.json create mode 100644 owl-bot-staging/google-maps-places/v1/scripts/fixup_places_v1_keywords.py create mode 100644 owl-bot-staging/google-maps-places/v1/setup.py create mode 100644 owl-bot-staging/google-maps-places/v1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-maps-places/v1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-maps-places/v1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-maps-places/v1/testing/constraints-3.13.txt create mode 100644 owl-bot-staging/google-maps-places/v1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-maps-places/v1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-maps-places/v1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-maps-places/v1/tests/__init__.py create mode 100644 owl-bot-staging/google-maps-places/v1/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-maps-places/v1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-maps-places/v1/tests/unit/gapic/places_v1/__init__.py create mode 100644 owl-bot-staging/google-maps-places/v1/tests/unit/gapic/places_v1/test_places.py create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/.coveragerc create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/.flake8 create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/MANIFEST.in create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/README.rst create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/docs/_static/custom.css create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/docs/conf.py create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/docs/index.rst create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/docs/routeoptimization_v1/route_optimization.rst create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/docs/routeoptimization_v1/services_.rst create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/docs/routeoptimization_v1/types_.rst create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization/__init__.py create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization/gapic_version.py create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization/py.typed create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/__init__.py create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/gapic_metadata.json create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/gapic_version.py create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/py.typed create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/__init__.py create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/__init__.py create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/async_client.py create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/client.py create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/README.rst create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/__init__.py create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/base.py create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/grpc.py create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/rest.py create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/rest_base.py create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/types/__init__.py create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/types/route_optimization_service.py create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/mypy.ini create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/noxfile.py create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/samples/generated_samples/routeoptimization_v1_generated_route_optimization_batch_optimize_tours_async.py create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/samples/generated_samples/routeoptimization_v1_generated_route_optimization_batch_optimize_tours_sync.py create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/samples/generated_samples/routeoptimization_v1_generated_route_optimization_optimize_tours_async.py create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/samples/generated_samples/routeoptimization_v1_generated_route_optimization_optimize_tours_sync.py create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/samples/generated_samples/snippet_metadata_google.maps.routeoptimization.v1.json create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/scripts/fixup_routeoptimization_v1_keywords.py create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/setup.py create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.13.txt create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/tests/__init__.py create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/tests/unit/gapic/routeoptimization_v1/__init__.py create mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/tests/unit/gapic/routeoptimization_v1/test_route_optimization.py create mode 100644 owl-bot-staging/google-maps-routing/v2/.coveragerc create mode 100644 owl-bot-staging/google-maps-routing/v2/.flake8 create mode 100644 owl-bot-staging/google-maps-routing/v2/MANIFEST.in create mode 100644 owl-bot-staging/google-maps-routing/v2/README.rst create mode 100644 owl-bot-staging/google-maps-routing/v2/docs/_static/custom.css create mode 100644 owl-bot-staging/google-maps-routing/v2/docs/conf.py create mode 100644 owl-bot-staging/google-maps-routing/v2/docs/index.rst create mode 100644 owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst create mode 100644 owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services_.rst create mode 100644 owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types_.rst create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/README.rst create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest_base.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/localized_time.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline_details.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/traffic_model.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/transit.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/transit_preferences.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py create mode 100644 owl-bot-staging/google-maps-routing/v2/mypy.ini create mode 100644 owl-bot-staging/google-maps-routing/v2/noxfile.py create mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py create mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py create mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py create mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py create mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json create mode 100644 owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py create mode 100644 owl-bot-staging/google-maps-routing/v2/setup.py create mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.13.txt create mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-maps-routing/v2/tests/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py create mode 100644 owl-bot-staging/google-maps-solar/v1/.coveragerc create mode 100644 owl-bot-staging/google-maps-solar/v1/.flake8 create mode 100644 owl-bot-staging/google-maps-solar/v1/MANIFEST.in create mode 100644 owl-bot-staging/google-maps-solar/v1/README.rst create mode 100644 owl-bot-staging/google-maps-solar/v1/docs/_static/custom.css create mode 100644 owl-bot-staging/google-maps-solar/v1/docs/conf.py create mode 100644 owl-bot-staging/google-maps-solar/v1/docs/index.rst create mode 100644 owl-bot-staging/google-maps-solar/v1/docs/solar_v1/services_.rst create mode 100644 owl-bot-staging/google-maps-solar/v1/docs/solar_v1/solar.rst create mode 100644 owl-bot-staging/google-maps-solar/v1/docs/solar_v1/types_.rst create mode 100644 owl-bot-staging/google-maps-solar/v1/google/maps/solar/__init__.py create mode 100644 owl-bot-staging/google-maps-solar/v1/google/maps/solar/gapic_version.py create mode 100644 owl-bot-staging/google-maps-solar/v1/google/maps/solar/py.typed create mode 100644 owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/__init__.py create mode 100644 owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/gapic_metadata.json create mode 100644 owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/gapic_version.py create mode 100644 owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/py.typed create mode 100644 owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/__init__.py create mode 100644 owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/__init__.py create mode 100644 owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/async_client.py create mode 100644 owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/client.py create mode 100644 owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/README.rst create mode 100644 owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/__init__.py create mode 100644 owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/base.py create mode 100644 owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/grpc.py create mode 100644 owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/rest.py create mode 100644 owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/rest_base.py create mode 100644 owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/types/__init__.py create mode 100644 owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/types/solar_service.py create mode 100644 owl-bot-staging/google-maps-solar/v1/mypy.ini create mode 100644 owl-bot-staging/google-maps-solar/v1/noxfile.py create mode 100644 owl-bot-staging/google-maps-solar/v1/samples/generated_samples/snippet_metadata_google.maps.solar.v1.json create mode 100644 owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_find_closest_building_insights_async.py create mode 100644 owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_find_closest_building_insights_sync.py create mode 100644 owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_get_data_layers_async.py create mode 100644 owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_get_data_layers_sync.py create mode 100644 owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_get_geo_tiff_async.py create mode 100644 owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_get_geo_tiff_sync.py create mode 100644 owl-bot-staging/google-maps-solar/v1/scripts/fixup_solar_v1_keywords.py create mode 100644 owl-bot-staging/google-maps-solar/v1/setup.py create mode 100644 owl-bot-staging/google-maps-solar/v1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-maps-solar/v1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-maps-solar/v1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-maps-solar/v1/testing/constraints-3.13.txt create mode 100644 owl-bot-staging/google-maps-solar/v1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-maps-solar/v1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-maps-solar/v1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-maps-solar/v1/tests/__init__.py create mode 100644 owl-bot-staging/google-maps-solar/v1/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-maps-solar/v1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-maps-solar/v1/tests/unit/gapic/solar_v1/__init__.py create mode 100644 owl-bot-staging/google-maps-solar/v1/tests/unit/gapic/solar_v1/test_solar.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/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/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/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/email_preferences_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/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/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/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/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/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/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/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/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/homepage.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_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_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_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_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_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_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_email_preferences_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_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 create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/.coveragerc create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/.flake8 create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/MANIFEST.in create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/_static/custom.css create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/conf.py create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/index.rst create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/merchant_conversions_v1beta/conversion_sources_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/merchant_conversions_v1beta/services_.rst create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/merchant_conversions_v1beta/types_.rst create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions/gapic_version.py create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions/py.typed create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/gapic_metadata.json create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/gapic_version.py create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/py.typed create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/pagers.py create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/types/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/types/conversionsources.py create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/mypy.ini create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/noxfile.py create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_create_conversion_source_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_create_conversion_source_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_delete_conversion_source_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_delete_conversion_source_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_get_conversion_source_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_get_conversion_source_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_list_conversion_sources_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_list_conversion_sources_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_undelete_conversion_source_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_undelete_conversion_source_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_update_conversion_source_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_update_conversion_source_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.conversions.v1beta.json create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/scripts/fixup_merchant_conversions_v1beta_keywords.py create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/setup.py create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.13.txt create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/tests/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/tests/unit/gapic/merchant_conversions_v1beta/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/tests/unit/gapic/merchant_conversions_v1beta/test_conversion_sources_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/.coveragerc create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/.flake8 create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/MANIFEST.in create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/_static/custom.css create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/conf.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/index.rst create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/merchant_datasources_v1beta/data_sources_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/merchant_datasources_v1beta/file_uploads_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/merchant_datasources_v1beta/services_.rst create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/merchant_datasources_v1beta/types_.rst create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources/gapic_version.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources/py.typed create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/gapic_metadata.json create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/gapic_version.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/py.typed create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/pagers.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/types/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/types/datasources.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/types/datasourcetypes.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/types/fileinputs.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/types/fileuploads.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/mypy.ini create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/noxfile.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_create_data_source_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_create_data_source_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_delete_data_source_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_delete_data_source_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_fetch_data_source_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_fetch_data_source_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_get_data_source_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_get_data_source_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_list_data_sources_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_list_data_sources_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_update_data_source_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_update_data_source_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_file_uploads_service_get_file_upload_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_file_uploads_service_get_file_upload_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.datasources.v1beta.json create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/scripts/fixup_merchant_datasources_v1beta_keywords.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/setup.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.13.txt create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/tests/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/tests/unit/gapic/merchant_datasources_v1beta/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/tests/unit/gapic/merchant_datasources_v1beta/test_data_sources_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/tests/unit/gapic/merchant_datasources_v1beta/test_file_uploads_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/.coveragerc create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/.flake8 create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/MANIFEST.in create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/_static/custom.css create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/conf.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/index.rst create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/local_inventory_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/regional_inventory_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/services_.rst create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/types_.rst create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/gapic_version.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/py.typed create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/gapic_metadata.json create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/gapic_version.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/py.typed create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/pagers.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/pagers.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/localinventory.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/regionalinventory.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/mypy.ini create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/noxfile.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.inventories.v1beta.json create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/scripts/fixup_merchant_inventories_v1beta_keywords.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/setup.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.13.txt create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/test_local_inventory_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/test_regional_inventory_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/.coveragerc create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/.flake8 create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/MANIFEST.in create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/_static/custom.css create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/conf.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/index.rst create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/merchant_lfp_v1beta/lfp_inventory_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/merchant_lfp_v1beta/lfp_sale_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/merchant_lfp_v1beta/lfp_store_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/merchant_lfp_v1beta/services_.rst create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/merchant_lfp_v1beta/types_.rst create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp/gapic_version.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp/py.typed create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/gapic_metadata.json create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/gapic_version.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/py.typed create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/pagers.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/types/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/types/lfpinventory.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/types/lfpsale.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/types/lfpstore.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/mypy.ini create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/noxfile.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_inventory_service_insert_lfp_inventory_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_inventory_service_insert_lfp_inventory_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_sale_service_insert_lfp_sale_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_sale_service_insert_lfp_sale_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_delete_lfp_store_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_delete_lfp_store_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_get_lfp_store_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_get_lfp_store_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_insert_lfp_store_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_insert_lfp_store_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_list_lfp_stores_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_list_lfp_stores_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.lfp.v1beta.json create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/scripts/fixup_merchant_lfp_v1beta_keywords.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/setup.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/testing/constraints-3.13.txt create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/tests/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/tests/unit/gapic/merchant_lfp_v1beta/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/tests/unit/gapic/merchant_lfp_v1beta/test_lfp_inventory_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/tests/unit/gapic/merchant_lfp_v1beta/test_lfp_sale_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/tests/unit/gapic/merchant_lfp_v1beta/test_lfp_store_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/.coveragerc create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/.flake8 create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/MANIFEST.in create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/_static/custom.css create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/conf.py create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/index.rst create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/merchant_notifications_v1beta/notifications_api_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/merchant_notifications_v1beta/services_.rst create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/merchant_notifications_v1beta/types_.rst create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications/gapic_version.py create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications/py.typed create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/gapic_metadata.json create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/gapic_version.py create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/py.typed create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/pagers.py create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/types/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/types/notificationsapi.py create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/mypy.ini create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/noxfile.py create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_create_notification_subscription_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_create_notification_subscription_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_delete_notification_subscription_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_delete_notification_subscription_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_get_notification_subscription_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_get_notification_subscription_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_list_notification_subscriptions_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_list_notification_subscriptions_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_update_notification_subscription_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_update_notification_subscription_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.notifications.v1beta.json create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/scripts/fixup_merchant_notifications_v1beta_keywords.py create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/setup.py create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/testing/constraints-3.13.txt create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/tests/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/tests/unit/gapic/merchant_notifications_v1beta/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/tests/unit/gapic/merchant_notifications_v1beta/test_notifications_api_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/.coveragerc create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/.flake8 create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/MANIFEST.in create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/_static/custom.css create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/conf.py create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/index.rst create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/merchant_promotions_v1beta/promotions_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/merchant_promotions_v1beta/services_.rst create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/merchant_promotions_v1beta/types_.rst create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions/gapic_version.py create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions/py.typed create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/gapic_metadata.json create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/gapic_version.py create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/py.typed create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/pagers.py create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/types/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/types/promotions.py create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/types/promotions_common.py create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/mypy.ini create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/noxfile.py create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_get_promotion_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_get_promotion_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_insert_promotion_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_insert_promotion_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_list_promotions_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_list_promotions_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.promotions.v1beta.json create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/scripts/fixup_merchant_promotions_v1beta_keywords.py create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/setup.py create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/testing/constraints-3.13.txt create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/tests/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/tests/unit/gapic/merchant_promotions_v1beta/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/tests/unit/gapic/merchant_promotions_v1beta/test_promotions_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/.coveragerc create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/.flake8 create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/MANIFEST.in create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/_static/custom.css create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/conf.py create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/index.rst create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/merchant_quota_v1beta/quota_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/merchant_quota_v1beta/services_.rst create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/merchant_quota_v1beta/types_.rst create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota/gapic_version.py create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota/py.typed create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/gapic_metadata.json create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/gapic_version.py create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/py.typed create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/pagers.py create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/types/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/types/quota.py create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/mypy.ini create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/noxfile.py create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/samples/generated_samples/merchantapi_v1beta_generated_quota_service_list_quota_groups_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/samples/generated_samples/merchantapi_v1beta_generated_quota_service_list_quota_groups_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.quota.v1beta.json create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/scripts/fixup_merchant_quota_v1beta_keywords.py create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/setup.py create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.13.txt create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/tests/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/tests/unit/gapic/merchant_quota_v1beta/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/tests/unit/gapic/merchant_quota_v1beta/test_quota_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/.coveragerc create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/.flake8 create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/MANIFEST.in create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/_static/custom.css create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/conf.py create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/index.rst create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/merchant_reports_v1beta/report_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/merchant_reports_v1beta/services_.rst create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/merchant_reports_v1beta/types_.rst create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports/gapic_version.py create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports/py.typed create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/gapic_metadata.json create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/gapic_version.py create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/py.typed create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/pagers.py create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/types/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/types/reports.py create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/mypy.ini create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/noxfile.py create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/samples/generated_samples/merchantapi_v1beta_generated_report_service_search_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/samples/generated_samples/merchantapi_v1beta_generated_report_service_search_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.reports.v1beta.json create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/scripts/fixup_merchant_reports_v1beta_keywords.py create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/setup.py create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/testing/constraints-3.13.txt create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/tests/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/tests/unit/gapic/merchant_reports_v1beta/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/tests/unit/gapic/merchant_reports_v1beta/test_report_service.py create mode 100644 owl-bot-staging/grafeas/v1/.coveragerc create mode 100644 owl-bot-staging/grafeas/v1/.flake8 create mode 100644 owl-bot-staging/grafeas/v1/MANIFEST.in create mode 100644 owl-bot-staging/grafeas/v1/README.rst create mode 100644 owl-bot-staging/grafeas/v1/docs/_static/custom.css create mode 100644 owl-bot-staging/grafeas/v1/docs/conf.py create mode 100644 owl-bot-staging/grafeas/v1/docs/grafeas_v1/grafeas.rst create mode 100644 owl-bot-staging/grafeas/v1/docs/grafeas_v1/services_.rst create mode 100644 owl-bot-staging/grafeas/v1/docs/grafeas_v1/types_.rst create mode 100644 owl-bot-staging/grafeas/v1/docs/index.rst create mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas/__init__.py create mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas/gapic_version.py create mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas/py.typed create mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/__init__.py create mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/gapic_metadata.json create mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/gapic_version.py create mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/py.typed create mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/__init__.py create mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/__init__.py create mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/async_client.py create mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/client.py create mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/pagers.py create mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/README.rst create mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/__init__.py create mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/base.py create mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/grpc.py create mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/rest.py create mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/rest_base.py create mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/__init__.py create mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/attestation.py create mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/build.py create mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/common.py create mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/compliance.py create mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/cvss.py create mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/deployment.py create mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/discovery.py create mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/dsse_attestation.py create mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/grafeas.py create mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/image.py create mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/intoto_provenance.py create mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/intoto_statement.py create mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/package.py create mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/provenance.py create mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/sbom.py create mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/severity.py create mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/slsa_provenance.py create mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/slsa_provenance_zero_two.py create mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/upgrade.py create mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/vex.py create mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/vulnerability.py create mode 100644 owl-bot-staging/grafeas/v1/mypy.ini create mode 100644 owl-bot-staging/grafeas/v1/noxfile.py create mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_notes_async.py create mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_notes_sync.py create mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_occurrences_async.py create mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_occurrences_sync.py create mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_note_async.py create mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_note_sync.py create mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_occurrence_async.py create mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_occurrence_sync.py create mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_note_async.py create mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_note_sync.py create mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_occurrence_async.py create mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_occurrence_sync.py create mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_note_async.py create mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_note_sync.py create mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_async.py create mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_note_async.py create mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_note_sync.py create mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_sync.py create mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_note_occurrences_async.py create mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_note_occurrences_sync.py create mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_notes_async.py create mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_notes_sync.py create mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_occurrences_async.py create mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_occurrences_sync.py create mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_note_async.py create mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_note_sync.py create mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_occurrence_async.py create mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_occurrence_sync.py create mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/snippet_metadata_grafeas.v1.json create mode 100644 owl-bot-staging/grafeas/v1/scripts/fixup_grafeas_v1_keywords.py create mode 100644 owl-bot-staging/grafeas/v1/setup.py create mode 100644 owl-bot-staging/grafeas/v1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/grafeas/v1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/grafeas/v1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/grafeas/v1/testing/constraints-3.13.txt create mode 100644 owl-bot-staging/grafeas/v1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/grafeas/v1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/grafeas/v1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/grafeas/v1/tests/__init__.py create mode 100644 owl-bot-staging/grafeas/v1/tests/unit/__init__.py create mode 100644 owl-bot-staging/grafeas/v1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/grafeas/v1/tests/unit/gapic/grafeas_v1/__init__.py create mode 100644 owl-bot-staging/grafeas/v1/tests/unit/gapic/grafeas_v1/test_grafeas.py diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/.coveragerc b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/.coveragerc new file mode 100644 index 000000000000..9f3dc18dceda --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/maps/mapsplatformdatasets/__init__.py + google/maps/mapsplatformdatasets/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-maps-mapsplatformdatasets/v1/.flake8 b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/MANIFEST.in b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/MANIFEST.in new file mode 100644 index 000000000000..d1e798fda05b --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/maps/mapsplatformdatasets *.py +recursive-include google/maps/mapsplatformdatasets_v1 *.py diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/README.rst b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/README.rst new file mode 100644 index 000000000000..4c46f2d1337e --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Maps Mapsplatformdatasets 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 Maps Mapsplatformdatasets 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 diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/_static/custom.css b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/conf.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/conf.py new file mode 100644 index 000000000000..e64db530d444 --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-maps-mapsplatformdatasets 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("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# 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.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +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-maps-mapsplatformdatasets" +copyright = u"2023, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# 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 = 'en' + +# 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"] + +# 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 Maps Client Libraries for Python", + "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-maps-mapsplatformdatasets-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-maps-mapsplatformdatasets.tex", + u"google-maps-mapsplatformdatasets 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-maps-mapsplatformdatasets", + u"Google Maps Mapsplatformdatasets 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-maps-mapsplatformdatasets", + u"google-maps-mapsplatformdatasets Documentation", + author, + "google-maps-mapsplatformdatasets", + "GAPIC library for Google Maps Mapsplatformdatasets API", + "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": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", 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-maps-mapsplatformdatasets/v1/docs/index.rst b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/index.rst new file mode 100644 index 000000000000..81b0ab58750e --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + mapsplatformdatasets_v1/services_ + mapsplatformdatasets_v1/types_ diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/mapsplatformdatasets_v1/maps_platform_datasets.rst b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/mapsplatformdatasets_v1/maps_platform_datasets.rst new file mode 100644 index 000000000000..d9eff02a3f2b --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/mapsplatformdatasets_v1/maps_platform_datasets.rst @@ -0,0 +1,10 @@ +MapsPlatformDatasets +-------------------------------------- + +.. automodule:: google.maps.mapsplatformdatasets_v1.services.maps_platform_datasets + :members: + :inherited-members: + +.. automodule:: google.maps.mapsplatformdatasets_v1.services.maps_platform_datasets.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/mapsplatformdatasets_v1/services_.rst b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/mapsplatformdatasets_v1/services_.rst new file mode 100644 index 000000000000..f2d8920fc6af --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/mapsplatformdatasets_v1/services_.rst @@ -0,0 +1,6 @@ +Services for Google Maps Mapsplatformdatasets v1 API +==================================================== +.. toctree:: + :maxdepth: 2 + + maps_platform_datasets diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/mapsplatformdatasets_v1/types_.rst b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/mapsplatformdatasets_v1/types_.rst new file mode 100644 index 000000000000..f4d2f2d7e793 --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/mapsplatformdatasets_v1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Maps Mapsplatformdatasets v1 API +================================================= + +.. automodule:: google.maps.mapsplatformdatasets_v1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets/__init__.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets/__init__.py new file mode 100644 index 000000000000..d87a63978fdc --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets/__init__.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.mapsplatformdatasets import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.maps.mapsplatformdatasets_v1.services.maps_platform_datasets.client import MapsPlatformDatasetsClient +from google.maps.mapsplatformdatasets_v1.services.maps_platform_datasets.async_client import MapsPlatformDatasetsAsyncClient + +from google.maps.mapsplatformdatasets_v1.types.data_source import GcsSource +from google.maps.mapsplatformdatasets_v1.types.data_source import LocalFileSource +from google.maps.mapsplatformdatasets_v1.types.data_source import FileFormat +from google.maps.mapsplatformdatasets_v1.types.dataset import Dataset +from google.maps.mapsplatformdatasets_v1.types.dataset import Status +from google.maps.mapsplatformdatasets_v1.types.dataset import Usage +from google.maps.mapsplatformdatasets_v1.types.maps_platform_datasets import CreateDatasetRequest +from google.maps.mapsplatformdatasets_v1.types.maps_platform_datasets import DeleteDatasetRequest +from google.maps.mapsplatformdatasets_v1.types.maps_platform_datasets import FetchDatasetErrorsRequest +from google.maps.mapsplatformdatasets_v1.types.maps_platform_datasets import FetchDatasetErrorsResponse +from google.maps.mapsplatformdatasets_v1.types.maps_platform_datasets import GetDatasetRequest +from google.maps.mapsplatformdatasets_v1.types.maps_platform_datasets import ListDatasetsRequest +from google.maps.mapsplatformdatasets_v1.types.maps_platform_datasets import ListDatasetsResponse +from google.maps.mapsplatformdatasets_v1.types.maps_platform_datasets import UpdateDatasetMetadataRequest + +__all__ = ('MapsPlatformDatasetsClient', + 'MapsPlatformDatasetsAsyncClient', + 'GcsSource', + 'LocalFileSource', + 'FileFormat', + 'Dataset', + 'Status', + 'Usage', + 'CreateDatasetRequest', + 'DeleteDatasetRequest', + 'FetchDatasetErrorsRequest', + 'FetchDatasetErrorsResponse', + 'GetDatasetRequest', + 'ListDatasetsRequest', + 'ListDatasetsResponse', + 'UpdateDatasetMetadataRequest', +) diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets/gapic_version.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets/py.typed b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets/py.typed new file mode 100644 index 000000000000..b186faa8f14d --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-maps-mapsplatformdatasets package uses inline types. diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/__init__.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/__init__.py new file mode 100644 index 000000000000..8d547fc08511 --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/__init__.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.mapsplatformdatasets_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.maps_platform_datasets import MapsPlatformDatasetsClient +from .services.maps_platform_datasets import MapsPlatformDatasetsAsyncClient + +from .types.data_source import GcsSource +from .types.data_source import LocalFileSource +from .types.data_source import FileFormat +from .types.dataset import Dataset +from .types.dataset import Status +from .types.dataset import Usage +from .types.maps_platform_datasets import CreateDatasetRequest +from .types.maps_platform_datasets import DeleteDatasetRequest +from .types.maps_platform_datasets import FetchDatasetErrorsRequest +from .types.maps_platform_datasets import FetchDatasetErrorsResponse +from .types.maps_platform_datasets import GetDatasetRequest +from .types.maps_platform_datasets import ListDatasetsRequest +from .types.maps_platform_datasets import ListDatasetsResponse +from .types.maps_platform_datasets import UpdateDatasetMetadataRequest + +__all__ = ( + 'MapsPlatformDatasetsAsyncClient', +'CreateDatasetRequest', +'Dataset', +'DeleteDatasetRequest', +'FetchDatasetErrorsRequest', +'FetchDatasetErrorsResponse', +'FileFormat', +'GcsSource', +'GetDatasetRequest', +'ListDatasetsRequest', +'ListDatasetsResponse', +'LocalFileSource', +'MapsPlatformDatasetsClient', +'Status', +'UpdateDatasetMetadataRequest', +'Usage', +) diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/gapic_metadata.json b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/gapic_metadata.json new file mode 100644 index 000000000000..fe6bcbfe38b3 --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/gapic_metadata.json @@ -0,0 +1,118 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.maps.mapsplatformdatasets_v1", + "protoPackage": "google.maps.mapsplatformdatasets.v1", + "schema": "1.0", + "services": { + "MapsPlatformDatasets": { + "clients": { + "grpc": { + "libraryClient": "MapsPlatformDatasetsClient", + "rpcs": { + "CreateDataset": { + "methods": [ + "create_dataset" + ] + }, + "DeleteDataset": { + "methods": [ + "delete_dataset" + ] + }, + "FetchDatasetErrors": { + "methods": [ + "fetch_dataset_errors" + ] + }, + "GetDataset": { + "methods": [ + "get_dataset" + ] + }, + "ListDatasets": { + "methods": [ + "list_datasets" + ] + }, + "UpdateDatasetMetadata": { + "methods": [ + "update_dataset_metadata" + ] + } + } + }, + "grpc-async": { + "libraryClient": "MapsPlatformDatasetsAsyncClient", + "rpcs": { + "CreateDataset": { + "methods": [ + "create_dataset" + ] + }, + "DeleteDataset": { + "methods": [ + "delete_dataset" + ] + }, + "FetchDatasetErrors": { + "methods": [ + "fetch_dataset_errors" + ] + }, + "GetDataset": { + "methods": [ + "get_dataset" + ] + }, + "ListDatasets": { + "methods": [ + "list_datasets" + ] + }, + "UpdateDatasetMetadata": { + "methods": [ + "update_dataset_metadata" + ] + } + } + }, + "rest": { + "libraryClient": "MapsPlatformDatasetsClient", + "rpcs": { + "CreateDataset": { + "methods": [ + "create_dataset" + ] + }, + "DeleteDataset": { + "methods": [ + "delete_dataset" + ] + }, + "FetchDatasetErrors": { + "methods": [ + "fetch_dataset_errors" + ] + }, + "GetDataset": { + "methods": [ + "get_dataset" + ] + }, + "ListDatasets": { + "methods": [ + "list_datasets" + ] + }, + "UpdateDatasetMetadata": { + "methods": [ + "update_dataset_metadata" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/gapic_version.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/py.typed b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/py.typed new file mode 100644 index 000000000000..b186faa8f14d --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-maps-mapsplatformdatasets package uses inline types. diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/__init__.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/__init__.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/__init__.py new file mode 100644 index 000000000000..a8cb67724686 --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 MapsPlatformDatasetsClient +from .async_client import MapsPlatformDatasetsAsyncClient + +__all__ = ( + 'MapsPlatformDatasetsClient', + 'MapsPlatformDatasetsAsyncClient', +) diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/async_client.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/async_client.py new file mode 100644 index 000000000000..5b3c279b040e --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/async_client.py @@ -0,0 +1,941 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.mapsplatformdatasets_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 + + +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.maps.mapsplatformdatasets_v1.services.maps_platform_datasets import pagers +from google.maps.mapsplatformdatasets_v1.types import data_source +from google.maps.mapsplatformdatasets_v1.types import dataset +from google.maps.mapsplatformdatasets_v1.types import dataset as gmm_dataset +from google.maps.mapsplatformdatasets_v1.types import maps_platform_datasets +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from .transports.base import MapsPlatformDatasetsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import MapsPlatformDatasetsGrpcAsyncIOTransport +from .client import MapsPlatformDatasetsClient + +try: + from google.api_core import client_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 MapsPlatformDatasetsAsyncClient: + """Service definition for the Maps Platform Datasets API.""" + + _client: MapsPlatformDatasetsClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = MapsPlatformDatasetsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = MapsPlatformDatasetsClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = MapsPlatformDatasetsClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = MapsPlatformDatasetsClient._DEFAULT_UNIVERSE + + dataset_path = staticmethod(MapsPlatformDatasetsClient.dataset_path) + parse_dataset_path = staticmethod(MapsPlatformDatasetsClient.parse_dataset_path) + common_billing_account_path = staticmethod(MapsPlatformDatasetsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(MapsPlatformDatasetsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(MapsPlatformDatasetsClient.common_folder_path) + parse_common_folder_path = staticmethod(MapsPlatformDatasetsClient.parse_common_folder_path) + common_organization_path = staticmethod(MapsPlatformDatasetsClient.common_organization_path) + parse_common_organization_path = staticmethod(MapsPlatformDatasetsClient.parse_common_organization_path) + common_project_path = staticmethod(MapsPlatformDatasetsClient.common_project_path) + parse_common_project_path = staticmethod(MapsPlatformDatasetsClient.parse_common_project_path) + common_location_path = staticmethod(MapsPlatformDatasetsClient.common_location_path) + parse_common_location_path = staticmethod(MapsPlatformDatasetsClient.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: + MapsPlatformDatasetsAsyncClient: The constructed client. + """ + return MapsPlatformDatasetsClient.from_service_account_info.__func__(MapsPlatformDatasetsAsyncClient, 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: + MapsPlatformDatasetsAsyncClient: The constructed client. + """ + return MapsPlatformDatasetsClient.from_service_account_file.__func__(MapsPlatformDatasetsAsyncClient, 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 MapsPlatformDatasetsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> MapsPlatformDatasetsTransport: + """Returns the transport used by the client instance. + + Returns: + MapsPlatformDatasetsTransport: 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 = MapsPlatformDatasetsClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, MapsPlatformDatasetsTransport, Callable[..., MapsPlatformDatasetsTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the maps platform datasets 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,MapsPlatformDatasetsTransport,Callable[..., MapsPlatformDatasetsTransport]]]): + 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 MapsPlatformDatasetsTransport 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 = MapsPlatformDatasetsClient( + 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.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient`.", + extra = { + "serviceName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "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.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "credentialsType": None, + } + ) + + async def create_dataset(self, + request: Optional[Union[maps_platform_datasets.CreateDatasetRequest, dict]] = None, + *, + parent: Optional[str] = None, + dataset: Optional[gmm_dataset.Dataset] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gmm_dataset.Dataset: + r"""Creates a new dataset for the specified project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import mapsplatformdatasets_v1 + + async def sample_create_dataset(): + # Create a client + client = mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient() + + # Initialize request argument(s) + request = mapsplatformdatasets_v1.CreateDatasetRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_dataset(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.mapsplatformdatasets_v1.types.CreateDatasetRequest, dict]]): + The request object. Request to create a maps dataset. + parent (:class:`str`): + Required. Parent project that will + own the dataset. Format: + projects/{project} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + dataset (:class:`google.maps.mapsplatformdatasets_v1.types.Dataset`): + Required. The dataset version to + create. + + This corresponds to the ``dataset`` 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.maps.mapsplatformdatasets_v1.types.Dataset: + A representation of a dataset + 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. + has_flattened_params = any([parent, dataset]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, maps_platform_datasets.CreateDatasetRequest): + request = maps_platform_datasets.CreateDatasetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if dataset is not None: + request.dataset = dataset + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_dataset] + + # Certain 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_dataset_metadata(self, + request: Optional[Union[maps_platform_datasets.UpdateDatasetMetadataRequest, dict]] = None, + *, + dataset: Optional[gmm_dataset.Dataset] = 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]]] = (), + ) -> gmm_dataset.Dataset: + r"""Updates the metadata for the dataset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import mapsplatformdatasets_v1 + + async def sample_update_dataset_metadata(): + # Create a client + client = mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient() + + # Initialize request argument(s) + request = mapsplatformdatasets_v1.UpdateDatasetMetadataRequest( + ) + + # Make the request + response = await client.update_dataset_metadata(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.mapsplatformdatasets_v1.types.UpdateDatasetMetadataRequest, dict]]): + The request object. Request to update the metadata fields + of the dataset. + dataset (:class:`google.maps.mapsplatformdatasets_v1.types.Dataset`): + Required. Resource name of the dataset to update. + Format: projects/{project}/datasets/{dataset_id} + + This corresponds to the ``dataset`` 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. + + The value "*" is used for full replacement (default). + + 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.maps.mapsplatformdatasets_v1.types.Dataset: + A representation of a dataset + 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. + has_flattened_params = any([dataset, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, maps_platform_datasets.UpdateDatasetMetadataRequest): + request = maps_platform_datasets.UpdateDatasetMetadataRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if dataset is not None: + request.dataset = dataset + 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_dataset_metadata] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("dataset.name", request.dataset.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_dataset(self, + request: Optional[Union[maps_platform_datasets.GetDatasetRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> dataset.Dataset: + r"""Gets the dataset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import mapsplatformdatasets_v1 + + async def sample_get_dataset(): + # Create a client + client = mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient() + + # Initialize request argument(s) + request = mapsplatformdatasets_v1.GetDatasetRequest( + name="name_value", + ) + + # Make the request + response = await client.get_dataset(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.mapsplatformdatasets_v1.types.GetDatasetRequest, dict]]): + The request object. Request to get the specified dataset. + name (:class:`str`): + Required. Resource name. Format: + projects/{project}/datasets/{dataset_id} + + Can also fetch some special versions by appending "@" + and a tag. Format: + projects/{project}/datasets/{dataset_id}@{tag} + + Tag "active": The info of the latest completed version + will be included, and NOT_FOUND if the dataset does not + have one. + + 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.maps.mapsplatformdatasets_v1.types.Dataset: + A representation of a dataset + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, maps_platform_datasets.GetDatasetRequest): + request = maps_platform_datasets.GetDatasetRequest(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_dataset] + + # Certain 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 fetch_dataset_errors(self, + request: Optional[Union[maps_platform_datasets.FetchDatasetErrorsRequest, dict]] = None, + *, + dataset: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.FetchDatasetErrorsAsyncPager: + r"""Gets all the errors of a dataset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import mapsplatformdatasets_v1 + + async def sample_fetch_dataset_errors(): + # Create a client + client = mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient() + + # Initialize request argument(s) + request = mapsplatformdatasets_v1.FetchDatasetErrorsRequest( + dataset="dataset_value", + ) + + # Make the request + page_result = client.fetch_dataset_errors(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.maps.mapsplatformdatasets_v1.types.FetchDatasetErrorsRequest, dict]]): + The request object. Request to list detailed errors + belonging to a dataset. + dataset (:class:`str`): + Required. The name of the dataset to list all the errors + for. Format: projects/{project}/datasets/{dataset_id} + + This corresponds to the ``dataset`` 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.maps.mapsplatformdatasets_v1.services.maps_platform_datasets.pagers.FetchDatasetErrorsAsyncPager: + Response object of + FetchDatasetErrors. + 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. + has_flattened_params = any([dataset]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, maps_platform_datasets.FetchDatasetErrorsRequest): + request = maps_platform_datasets.FetchDatasetErrorsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if dataset is not None: + request.dataset = dataset + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.fetch_dataset_errors] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("dataset", request.dataset), + )), + ) + + # 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.FetchDatasetErrorsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_datasets(self, + request: Optional[Union[maps_platform_datasets.ListDatasetsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListDatasetsAsyncPager: + r"""Lists all the datasets for the specified project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import mapsplatformdatasets_v1 + + async def sample_list_datasets(): + # Create a client + client = mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient() + + # Initialize request argument(s) + request = mapsplatformdatasets_v1.ListDatasetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_datasets(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.maps.mapsplatformdatasets_v1.types.ListDatasetsRequest, dict]]): + The request object. Request to list datasets for the + project. + parent (:class:`str`): + Required. The name of the project to + list all the datasets for. Format: + projects/{project} + + 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.maps.mapsplatformdatasets_v1.services.maps_platform_datasets.pagers.ListDatasetsAsyncPager: + Response object of ListDatasets. + + 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, maps_platform_datasets.ListDatasetsRequest): + request = maps_platform_datasets.ListDatasetsRequest(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_datasets] + + # Certain 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.ListDatasetsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_dataset(self, + request: Optional[Union[maps_platform_datasets.DeleteDatasetRequest, dict]] = None, + *, + name: Optional[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 dataset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import mapsplatformdatasets_v1 + + async def sample_delete_dataset(): + # Create a client + client = mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient() + + # Initialize request argument(s) + request = mapsplatformdatasets_v1.DeleteDatasetRequest( + name="name_value", + ) + + # Make the request + await client.delete_dataset(request=request) + + Args: + request (Optional[Union[google.maps.mapsplatformdatasets_v1.types.DeleteDatasetRequest, dict]]): + The request object. Request to delete a dataset. + name (:class:`str`): + Required. The name of the dataset to delete. Format: + projects/{project}/datasets/{dataset_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`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, maps_platform_datasets.DeleteDatasetRequest): + request = maps_platform_datasets.DeleteDatasetRequest(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_dataset] + + # Certain 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) -> "MapsPlatformDatasetsAsyncClient": + 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__) + + +__all__ = ( + "MapsPlatformDatasetsAsyncClient", +) diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/client.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/client.py new file mode 100644 index 000000000000..b26bc719eb07 --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/client.py @@ -0,0 +1,1271 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +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.maps.mapsplatformdatasets_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 + +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.maps.mapsplatformdatasets_v1.services.maps_platform_datasets import pagers +from google.maps.mapsplatformdatasets_v1.types import data_source +from google.maps.mapsplatformdatasets_v1.types import dataset +from google.maps.mapsplatformdatasets_v1.types import dataset as gmm_dataset +from google.maps.mapsplatformdatasets_v1.types import maps_platform_datasets +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from .transports.base import MapsPlatformDatasetsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import MapsPlatformDatasetsGrpcTransport +from .transports.grpc_asyncio import MapsPlatformDatasetsGrpcAsyncIOTransport +from .transports.rest import MapsPlatformDatasetsRestTransport + + +class MapsPlatformDatasetsClientMeta(type): + """Metaclass for the MapsPlatformDatasets 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[MapsPlatformDatasetsTransport]] + _transport_registry["grpc"] = MapsPlatformDatasetsGrpcTransport + _transport_registry["grpc_asyncio"] = MapsPlatformDatasetsGrpcAsyncIOTransport + _transport_registry["rest"] = MapsPlatformDatasetsRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[MapsPlatformDatasetsTransport]: + """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 MapsPlatformDatasetsClient(metaclass=MapsPlatformDatasetsClientMeta): + """Service definition for the Maps Platform Datasets 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 = "mapsplatformdatasets.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "mapsplatformdatasets.{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: + MapsPlatformDatasetsClient: 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: + MapsPlatformDatasetsClient: 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) -> MapsPlatformDatasetsTransport: + """Returns the transport used by the client instance. + + Returns: + MapsPlatformDatasetsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def dataset_path(project: str,dataset: str,) -> str: + """Returns a fully-qualified dataset string.""" + return "projects/{project}/datasets/{dataset}".format(project=project, dataset=dataset, ) + + @staticmethod + def parse_dataset_path(path: str) -> Dict[str,str]: + """Parses a dataset path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/datasets/(?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 = MapsPlatformDatasetsClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = MapsPlatformDatasetsClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = MapsPlatformDatasetsClient._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 = MapsPlatformDatasetsClient._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 + + @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, MapsPlatformDatasetsTransport, Callable[..., MapsPlatformDatasetsTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the maps platform datasets 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,MapsPlatformDatasetsTransport,Callable[..., MapsPlatformDatasetsTransport]]]): + 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 MapsPlatformDatasetsTransport 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 = MapsPlatformDatasetsClient._read_environment_variables() + self._client_cert_source = MapsPlatformDatasetsClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = MapsPlatformDatasetsClient._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, MapsPlatformDatasetsTransport) + if transport_provided: + # transport is a MapsPlatformDatasetsTransport 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(MapsPlatformDatasetsTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + MapsPlatformDatasetsClient._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[MapsPlatformDatasetsTransport], Callable[..., MapsPlatformDatasetsTransport]] = ( + MapsPlatformDatasetsClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., MapsPlatformDatasetsTransport], 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.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient`.", + extra = { + "serviceName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "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.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "credentialsType": None, + } + ) + + def create_dataset(self, + request: Optional[Union[maps_platform_datasets.CreateDatasetRequest, dict]] = None, + *, + parent: Optional[str] = None, + dataset: Optional[gmm_dataset.Dataset] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gmm_dataset.Dataset: + r"""Creates a new dataset for the specified project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import mapsplatformdatasets_v1 + + def sample_create_dataset(): + # Create a client + client = mapsplatformdatasets_v1.MapsPlatformDatasetsClient() + + # Initialize request argument(s) + request = mapsplatformdatasets_v1.CreateDatasetRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_dataset(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.mapsplatformdatasets_v1.types.CreateDatasetRequest, dict]): + The request object. Request to create a maps dataset. + parent (str): + Required. Parent project that will + own the dataset. Format: + projects/{project} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + dataset (google.maps.mapsplatformdatasets_v1.types.Dataset): + Required. The dataset version to + create. + + This corresponds to the ``dataset`` 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.maps.mapsplatformdatasets_v1.types.Dataset: + A representation of a dataset + 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. + has_flattened_params = any([parent, dataset]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, maps_platform_datasets.CreateDatasetRequest): + request = maps_platform_datasets.CreateDatasetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if dataset is not None: + request.dataset = dataset + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_dataset] + + # Certain 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_dataset_metadata(self, + request: Optional[Union[maps_platform_datasets.UpdateDatasetMetadataRequest, dict]] = None, + *, + dataset: Optional[gmm_dataset.Dataset] = 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]]] = (), + ) -> gmm_dataset.Dataset: + r"""Updates the metadata for the dataset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import mapsplatformdatasets_v1 + + def sample_update_dataset_metadata(): + # Create a client + client = mapsplatformdatasets_v1.MapsPlatformDatasetsClient() + + # Initialize request argument(s) + request = mapsplatformdatasets_v1.UpdateDatasetMetadataRequest( + ) + + # Make the request + response = client.update_dataset_metadata(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.mapsplatformdatasets_v1.types.UpdateDatasetMetadataRequest, dict]): + The request object. Request to update the metadata fields + of the dataset. + dataset (google.maps.mapsplatformdatasets_v1.types.Dataset): + Required. Resource name of the dataset to update. + Format: projects/{project}/datasets/{dataset_id} + + This corresponds to the ``dataset`` 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. + + The value "*" is used for full replacement (default). + + 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.maps.mapsplatformdatasets_v1.types.Dataset: + A representation of a dataset + 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. + has_flattened_params = any([dataset, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, maps_platform_datasets.UpdateDatasetMetadataRequest): + request = maps_platform_datasets.UpdateDatasetMetadataRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if dataset is not None: + request.dataset = dataset + 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_dataset_metadata] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("dataset.name", request.dataset.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_dataset(self, + request: Optional[Union[maps_platform_datasets.GetDatasetRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> dataset.Dataset: + r"""Gets the dataset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import mapsplatformdatasets_v1 + + def sample_get_dataset(): + # Create a client + client = mapsplatformdatasets_v1.MapsPlatformDatasetsClient() + + # Initialize request argument(s) + request = mapsplatformdatasets_v1.GetDatasetRequest( + name="name_value", + ) + + # Make the request + response = client.get_dataset(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.mapsplatformdatasets_v1.types.GetDatasetRequest, dict]): + The request object. Request to get the specified dataset. + name (str): + Required. Resource name. Format: + projects/{project}/datasets/{dataset_id} + + Can also fetch some special versions by appending "@" + and a tag. Format: + projects/{project}/datasets/{dataset_id}@{tag} + + Tag "active": The info of the latest completed version + will be included, and NOT_FOUND if the dataset does not + have one. + + 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.maps.mapsplatformdatasets_v1.types.Dataset: + A representation of a dataset + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, maps_platform_datasets.GetDatasetRequest): + request = maps_platform_datasets.GetDatasetRequest(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_dataset] + + # Certain 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 fetch_dataset_errors(self, + request: Optional[Union[maps_platform_datasets.FetchDatasetErrorsRequest, dict]] = None, + *, + dataset: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.FetchDatasetErrorsPager: + r"""Gets all the errors of a dataset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import mapsplatformdatasets_v1 + + def sample_fetch_dataset_errors(): + # Create a client + client = mapsplatformdatasets_v1.MapsPlatformDatasetsClient() + + # Initialize request argument(s) + request = mapsplatformdatasets_v1.FetchDatasetErrorsRequest( + dataset="dataset_value", + ) + + # Make the request + page_result = client.fetch_dataset_errors(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.maps.mapsplatformdatasets_v1.types.FetchDatasetErrorsRequest, dict]): + The request object. Request to list detailed errors + belonging to a dataset. + dataset (str): + Required. The name of the dataset to list all the errors + for. Format: projects/{project}/datasets/{dataset_id} + + This corresponds to the ``dataset`` 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.maps.mapsplatformdatasets_v1.services.maps_platform_datasets.pagers.FetchDatasetErrorsPager: + Response object of + FetchDatasetErrors. + 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. + has_flattened_params = any([dataset]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, maps_platform_datasets.FetchDatasetErrorsRequest): + request = maps_platform_datasets.FetchDatasetErrorsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if dataset is not None: + request.dataset = dataset + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.fetch_dataset_errors] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("dataset", request.dataset), + )), + ) + + # 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.FetchDatasetErrorsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_datasets(self, + request: Optional[Union[maps_platform_datasets.ListDatasetsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListDatasetsPager: + r"""Lists all the datasets for the specified project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import mapsplatformdatasets_v1 + + def sample_list_datasets(): + # Create a client + client = mapsplatformdatasets_v1.MapsPlatformDatasetsClient() + + # Initialize request argument(s) + request = mapsplatformdatasets_v1.ListDatasetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_datasets(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.maps.mapsplatformdatasets_v1.types.ListDatasetsRequest, dict]): + The request object. Request to list datasets for the + project. + parent (str): + Required. The name of the project to + list all the datasets for. Format: + projects/{project} + + 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.maps.mapsplatformdatasets_v1.services.maps_platform_datasets.pagers.ListDatasetsPager: + Response object of ListDatasets. + + 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, maps_platform_datasets.ListDatasetsRequest): + request = maps_platform_datasets.ListDatasetsRequest(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_datasets] + + # Certain 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.ListDatasetsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_dataset(self, + request: Optional[Union[maps_platform_datasets.DeleteDatasetRequest, dict]] = None, + *, + name: Optional[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 dataset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import mapsplatformdatasets_v1 + + def sample_delete_dataset(): + # Create a client + client = mapsplatformdatasets_v1.MapsPlatformDatasetsClient() + + # Initialize request argument(s) + request = mapsplatformdatasets_v1.DeleteDatasetRequest( + name="name_value", + ) + + # Make the request + client.delete_dataset(request=request) + + Args: + request (Union[google.maps.mapsplatformdatasets_v1.types.DeleteDatasetRequest, dict]): + The request object. Request to delete a dataset. + name (str): + Required. The name of the dataset to delete. Format: + projects/{project}/datasets/{dataset_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`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, maps_platform_datasets.DeleteDatasetRequest): + request = maps_platform_datasets.DeleteDatasetRequest(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_dataset] + + # Certain 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) -> "MapsPlatformDatasetsClient": + 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__) + + +__all__ = ( + "MapsPlatformDatasetsClient", +) diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/pagers.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/pagers.py new file mode 100644 index 000000000000..0d42c1f7844c --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/pagers.py @@ -0,0 +1,307 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.mapsplatformdatasets_v1.types import dataset +from google.maps.mapsplatformdatasets_v1.types import maps_platform_datasets +from google.rpc import status_pb2 # type: ignore + + +class FetchDatasetErrorsPager: + """A pager for iterating through ``fetch_dataset_errors`` requests. + + This class thinly wraps an initial + :class:`google.maps.mapsplatformdatasets_v1.types.FetchDatasetErrorsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``errors`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``FetchDatasetErrors`` requests and continue to iterate + through the ``errors`` field on the + corresponding responses. + + All the usual :class:`google.maps.mapsplatformdatasets_v1.types.FetchDatasetErrorsResponse` + 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[..., maps_platform_datasets.FetchDatasetErrorsResponse], + request: maps_platform_datasets.FetchDatasetErrorsRequest, + response: maps_platform_datasets.FetchDatasetErrorsResponse, + *, + 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.maps.mapsplatformdatasets_v1.types.FetchDatasetErrorsRequest): + The initial request object. + response (google.maps.mapsplatformdatasets_v1.types.FetchDatasetErrorsResponse): + 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 = maps_platform_datasets.FetchDatasetErrorsRequest(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[maps_platform_datasets.FetchDatasetErrorsResponse]: + 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[status_pb2.Status]: + for page in self.pages: + yield from page.errors + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class FetchDatasetErrorsAsyncPager: + """A pager for iterating through ``fetch_dataset_errors`` requests. + + This class thinly wraps an initial + :class:`google.maps.mapsplatformdatasets_v1.types.FetchDatasetErrorsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``errors`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``FetchDatasetErrors`` requests and continue to iterate + through the ``errors`` field on the + corresponding responses. + + All the usual :class:`google.maps.mapsplatformdatasets_v1.types.FetchDatasetErrorsResponse` + 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[maps_platform_datasets.FetchDatasetErrorsResponse]], + request: maps_platform_datasets.FetchDatasetErrorsRequest, + response: maps_platform_datasets.FetchDatasetErrorsResponse, + *, + 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.maps.mapsplatformdatasets_v1.types.FetchDatasetErrorsRequest): + The initial request object. + response (google.maps.mapsplatformdatasets_v1.types.FetchDatasetErrorsResponse): + 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 = maps_platform_datasets.FetchDatasetErrorsRequest(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[maps_platform_datasets.FetchDatasetErrorsResponse]: + 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[status_pb2.Status]: + async def async_generator(): + async for page in self.pages: + for response in page.errors: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDatasetsPager: + """A pager for iterating through ``list_datasets`` requests. + + This class thinly wraps an initial + :class:`google.maps.mapsplatformdatasets_v1.types.ListDatasetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``datasets`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListDatasets`` requests and continue to iterate + through the ``datasets`` field on the + corresponding responses. + + All the usual :class:`google.maps.mapsplatformdatasets_v1.types.ListDatasetsResponse` + 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[..., maps_platform_datasets.ListDatasetsResponse], + request: maps_platform_datasets.ListDatasetsRequest, + response: maps_platform_datasets.ListDatasetsResponse, + *, + 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.maps.mapsplatformdatasets_v1.types.ListDatasetsRequest): + The initial request object. + response (google.maps.mapsplatformdatasets_v1.types.ListDatasetsResponse): + 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 = maps_platform_datasets.ListDatasetsRequest(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[maps_platform_datasets.ListDatasetsResponse]: + 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[dataset.Dataset]: + for page in self.pages: + yield from page.datasets + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDatasetsAsyncPager: + """A pager for iterating through ``list_datasets`` requests. + + This class thinly wraps an initial + :class:`google.maps.mapsplatformdatasets_v1.types.ListDatasetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``datasets`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListDatasets`` requests and continue to iterate + through the ``datasets`` field on the + corresponding responses. + + All the usual :class:`google.maps.mapsplatformdatasets_v1.types.ListDatasetsResponse` + 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[maps_platform_datasets.ListDatasetsResponse]], + request: maps_platform_datasets.ListDatasetsRequest, + response: maps_platform_datasets.ListDatasetsResponse, + *, + 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.maps.mapsplatformdatasets_v1.types.ListDatasetsRequest): + The initial request object. + response (google.maps.mapsplatformdatasets_v1.types.ListDatasetsResponse): + 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 = maps_platform_datasets.ListDatasetsRequest(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[maps_platform_datasets.ListDatasetsResponse]: + 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[dataset.Dataset]: + async def async_generator(): + async for page in self.pages: + for response in page.datasets: + 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-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/README.rst b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/README.rst new file mode 100644 index 000000000000..cb6fbe0110ae --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`MapsPlatformDatasetsTransport` is the ABC for all transports. +- public child `MapsPlatformDatasetsGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `MapsPlatformDatasetsGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseMapsPlatformDatasetsRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `MapsPlatformDatasetsRestTransport` 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-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/__init__.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/__init__.py new file mode 100644 index 000000000000..e3a3c8c168b4 --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 MapsPlatformDatasetsTransport +from .grpc import MapsPlatformDatasetsGrpcTransport +from .grpc_asyncio import MapsPlatformDatasetsGrpcAsyncIOTransport +from .rest import MapsPlatformDatasetsRestTransport +from .rest import MapsPlatformDatasetsRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[MapsPlatformDatasetsTransport]] +_transport_registry['grpc'] = MapsPlatformDatasetsGrpcTransport +_transport_registry['grpc_asyncio'] = MapsPlatformDatasetsGrpcAsyncIOTransport +_transport_registry['rest'] = MapsPlatformDatasetsRestTransport + +__all__ = ( + 'MapsPlatformDatasetsTransport', + 'MapsPlatformDatasetsGrpcTransport', + 'MapsPlatformDatasetsGrpcAsyncIOTransport', + 'MapsPlatformDatasetsRestTransport', + 'MapsPlatformDatasetsRestInterceptor', +) diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/base.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/base.py new file mode 100644 index 000000000000..1133740e976a --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/base.py @@ -0,0 +1,254 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.mapsplatformdatasets_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 + +from google.maps.mapsplatformdatasets_v1.types import dataset +from google.maps.mapsplatformdatasets_v1.types import dataset as gmm_dataset +from google.maps.mapsplatformdatasets_v1.types import maps_platform_datasets +from google.protobuf import empty_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class MapsPlatformDatasetsTransport(abc.ABC): + """Abstract transport class for MapsPlatformDatasets.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'mapsplatformdatasets.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: 'mapsplatformdatasets.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to 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.create_dataset: gapic_v1.method.wrap_method( + self.create_dataset, + default_timeout=60.0, + client_info=client_info, + ), + self.update_dataset_metadata: gapic_v1.method.wrap_method( + self.update_dataset_metadata, + default_timeout=60.0, + client_info=client_info, + ), + self.get_dataset: gapic_v1.method.wrap_method( + self.get_dataset, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.fetch_dataset_errors: gapic_v1.method.wrap_method( + self.fetch_dataset_errors, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_datasets: gapic_v1.method.wrap_method( + self.list_datasets, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_dataset: gapic_v1.method.wrap_method( + self.delete_dataset, + default_timeout=60.0, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def create_dataset(self) -> Callable[ + [maps_platform_datasets.CreateDatasetRequest], + Union[ + gmm_dataset.Dataset, + Awaitable[gmm_dataset.Dataset] + ]]: + raise NotImplementedError() + + @property + def update_dataset_metadata(self) -> Callable[ + [maps_platform_datasets.UpdateDatasetMetadataRequest], + Union[ + gmm_dataset.Dataset, + Awaitable[gmm_dataset.Dataset] + ]]: + raise NotImplementedError() + + @property + def get_dataset(self) -> Callable[ + [maps_platform_datasets.GetDatasetRequest], + Union[ + dataset.Dataset, + Awaitable[dataset.Dataset] + ]]: + raise NotImplementedError() + + @property + def fetch_dataset_errors(self) -> Callable[ + [maps_platform_datasets.FetchDatasetErrorsRequest], + Union[ + maps_platform_datasets.FetchDatasetErrorsResponse, + Awaitable[maps_platform_datasets.FetchDatasetErrorsResponse] + ]]: + raise NotImplementedError() + + @property + def list_datasets(self) -> Callable[ + [maps_platform_datasets.ListDatasetsRequest], + Union[ + maps_platform_datasets.ListDatasetsResponse, + Awaitable[maps_platform_datasets.ListDatasetsResponse] + ]]: + raise NotImplementedError() + + @property + def delete_dataset(self) -> Callable[ + [maps_platform_datasets.DeleteDatasetRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'MapsPlatformDatasetsTransport', +) diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/grpc.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/grpc.py new file mode 100644 index 000000000000..81d8194aef59 --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/grpc.py @@ -0,0 +1,480 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.mapsplatformdatasets_v1.types import dataset +from google.maps.mapsplatformdatasets_v1.types import dataset as gmm_dataset +from google.maps.mapsplatformdatasets_v1.types import maps_platform_datasets +from google.protobuf import empty_pb2 # type: ignore +from .base import MapsPlatformDatasetsTransport, 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.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "rpcName": 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.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class MapsPlatformDatasetsGrpcTransport(MapsPlatformDatasetsTransport): + """gRPC backend transport for MapsPlatformDatasets. + + Service definition for the Maps Platform Datasets 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 = 'mapsplatformdatasets.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: 'mapsplatformdatasets.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to 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 = 'mapsplatformdatasets.googleapis.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 create_dataset(self) -> Callable[ + [maps_platform_datasets.CreateDatasetRequest], + gmm_dataset.Dataset]: + r"""Return a callable for the create dataset method over gRPC. + + Creates a new dataset for the specified project. + + Returns: + Callable[[~.CreateDatasetRequest], + ~.Dataset]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_dataset' not in self._stubs: + self._stubs['create_dataset'] = self._logged_channel.unary_unary( + '/google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets/CreateDataset', + request_serializer=maps_platform_datasets.CreateDatasetRequest.serialize, + response_deserializer=gmm_dataset.Dataset.deserialize, + ) + return self._stubs['create_dataset'] + + @property + def update_dataset_metadata(self) -> Callable[ + [maps_platform_datasets.UpdateDatasetMetadataRequest], + gmm_dataset.Dataset]: + r"""Return a callable for the update dataset metadata method over gRPC. + + Updates the metadata for the dataset. + + Returns: + Callable[[~.UpdateDatasetMetadataRequest], + ~.Dataset]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_dataset_metadata' not in self._stubs: + self._stubs['update_dataset_metadata'] = self._logged_channel.unary_unary( + '/google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets/UpdateDatasetMetadata', + request_serializer=maps_platform_datasets.UpdateDatasetMetadataRequest.serialize, + response_deserializer=gmm_dataset.Dataset.deserialize, + ) + return self._stubs['update_dataset_metadata'] + + @property + def get_dataset(self) -> Callable[ + [maps_platform_datasets.GetDatasetRequest], + dataset.Dataset]: + r"""Return a callable for the get dataset method over gRPC. + + Gets the dataset. + + Returns: + Callable[[~.GetDatasetRequest], + ~.Dataset]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_dataset' not in self._stubs: + self._stubs['get_dataset'] = self._logged_channel.unary_unary( + '/google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets/GetDataset', + request_serializer=maps_platform_datasets.GetDatasetRequest.serialize, + response_deserializer=dataset.Dataset.deserialize, + ) + return self._stubs['get_dataset'] + + @property + def fetch_dataset_errors(self) -> Callable[ + [maps_platform_datasets.FetchDatasetErrorsRequest], + maps_platform_datasets.FetchDatasetErrorsResponse]: + r"""Return a callable for the fetch dataset errors method over gRPC. + + Gets all the errors of a dataset. + + Returns: + Callable[[~.FetchDatasetErrorsRequest], + ~.FetchDatasetErrorsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'fetch_dataset_errors' not in self._stubs: + self._stubs['fetch_dataset_errors'] = self._logged_channel.unary_unary( + '/google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets/FetchDatasetErrors', + request_serializer=maps_platform_datasets.FetchDatasetErrorsRequest.serialize, + response_deserializer=maps_platform_datasets.FetchDatasetErrorsResponse.deserialize, + ) + return self._stubs['fetch_dataset_errors'] + + @property + def list_datasets(self) -> Callable[ + [maps_platform_datasets.ListDatasetsRequest], + maps_platform_datasets.ListDatasetsResponse]: + r"""Return a callable for the list datasets method over gRPC. + + Lists all the datasets for the specified project. + + Returns: + Callable[[~.ListDatasetsRequest], + ~.ListDatasetsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_datasets' not in self._stubs: + self._stubs['list_datasets'] = self._logged_channel.unary_unary( + '/google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets/ListDatasets', + request_serializer=maps_platform_datasets.ListDatasetsRequest.serialize, + response_deserializer=maps_platform_datasets.ListDatasetsResponse.deserialize, + ) + return self._stubs['list_datasets'] + + @property + def delete_dataset(self) -> Callable[ + [maps_platform_datasets.DeleteDatasetRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete dataset method over gRPC. + + Deletes the specified dataset. + + Returns: + Callable[[~.DeleteDatasetRequest], + ~.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_dataset' not in self._stubs: + self._stubs['delete_dataset'] = self._logged_channel.unary_unary( + '/google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets/DeleteDataset', + request_serializer=maps_platform_datasets.DeleteDatasetRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_dataset'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'MapsPlatformDatasetsGrpcTransport', +) diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/grpc_asyncio.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/grpc_asyncio.py new file mode 100644 index 000000000000..b8703b9c746d --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/grpc_asyncio.py @@ -0,0 +1,552 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.mapsplatformdatasets_v1.types import dataset +from google.maps.mapsplatformdatasets_v1.types import dataset as gmm_dataset +from google.maps.mapsplatformdatasets_v1.types import maps_platform_datasets +from google.protobuf import empty_pb2 # type: ignore +from .base import MapsPlatformDatasetsTransport, DEFAULT_CLIENT_INFO +from .grpc import MapsPlatformDatasetsGrpcTransport + +try: + from google.api_core import client_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.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "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.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class MapsPlatformDatasetsGrpcAsyncIOTransport(MapsPlatformDatasetsTransport): + """gRPC AsyncIO backend transport for MapsPlatformDatasets. + + Service definition for the Maps Platform Datasets 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 = 'mapsplatformdatasets.googleapis.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 = 'mapsplatformdatasets.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: 'mapsplatformdatasets.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to 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 create_dataset(self) -> Callable[ + [maps_platform_datasets.CreateDatasetRequest], + Awaitable[gmm_dataset.Dataset]]: + r"""Return a callable for the create dataset method over gRPC. + + Creates a new dataset for the specified project. + + Returns: + Callable[[~.CreateDatasetRequest], + Awaitable[~.Dataset]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_dataset' not in self._stubs: + self._stubs['create_dataset'] = self._logged_channel.unary_unary( + '/google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets/CreateDataset', + request_serializer=maps_platform_datasets.CreateDatasetRequest.serialize, + response_deserializer=gmm_dataset.Dataset.deserialize, + ) + return self._stubs['create_dataset'] + + @property + def update_dataset_metadata(self) -> Callable[ + [maps_platform_datasets.UpdateDatasetMetadataRequest], + Awaitable[gmm_dataset.Dataset]]: + r"""Return a callable for the update dataset metadata method over gRPC. + + Updates the metadata for the dataset. + + Returns: + Callable[[~.UpdateDatasetMetadataRequest], + Awaitable[~.Dataset]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_dataset_metadata' not in self._stubs: + self._stubs['update_dataset_metadata'] = self._logged_channel.unary_unary( + '/google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets/UpdateDatasetMetadata', + request_serializer=maps_platform_datasets.UpdateDatasetMetadataRequest.serialize, + response_deserializer=gmm_dataset.Dataset.deserialize, + ) + return self._stubs['update_dataset_metadata'] + + @property + def get_dataset(self) -> Callable[ + [maps_platform_datasets.GetDatasetRequest], + Awaitable[dataset.Dataset]]: + r"""Return a callable for the get dataset method over gRPC. + + Gets the dataset. + + Returns: + Callable[[~.GetDatasetRequest], + Awaitable[~.Dataset]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_dataset' not in self._stubs: + self._stubs['get_dataset'] = self._logged_channel.unary_unary( + '/google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets/GetDataset', + request_serializer=maps_platform_datasets.GetDatasetRequest.serialize, + response_deserializer=dataset.Dataset.deserialize, + ) + return self._stubs['get_dataset'] + + @property + def fetch_dataset_errors(self) -> Callable[ + [maps_platform_datasets.FetchDatasetErrorsRequest], + Awaitable[maps_platform_datasets.FetchDatasetErrorsResponse]]: + r"""Return a callable for the fetch dataset errors method over gRPC. + + Gets all the errors of a dataset. + + Returns: + Callable[[~.FetchDatasetErrorsRequest], + Awaitable[~.FetchDatasetErrorsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'fetch_dataset_errors' not in self._stubs: + self._stubs['fetch_dataset_errors'] = self._logged_channel.unary_unary( + '/google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets/FetchDatasetErrors', + request_serializer=maps_platform_datasets.FetchDatasetErrorsRequest.serialize, + response_deserializer=maps_platform_datasets.FetchDatasetErrorsResponse.deserialize, + ) + return self._stubs['fetch_dataset_errors'] + + @property + def list_datasets(self) -> Callable[ + [maps_platform_datasets.ListDatasetsRequest], + Awaitable[maps_platform_datasets.ListDatasetsResponse]]: + r"""Return a callable for the list datasets method over gRPC. + + Lists all the datasets for the specified project. + + Returns: + Callable[[~.ListDatasetsRequest], + Awaitable[~.ListDatasetsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_datasets' not in self._stubs: + self._stubs['list_datasets'] = self._logged_channel.unary_unary( + '/google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets/ListDatasets', + request_serializer=maps_platform_datasets.ListDatasetsRequest.serialize, + response_deserializer=maps_platform_datasets.ListDatasetsResponse.deserialize, + ) + return self._stubs['list_datasets'] + + @property + def delete_dataset(self) -> Callable[ + [maps_platform_datasets.DeleteDatasetRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete dataset method over gRPC. + + Deletes the specified dataset. + + Returns: + Callable[[~.DeleteDatasetRequest], + 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_dataset' not in self._stubs: + self._stubs['delete_dataset'] = self._logged_channel.unary_unary( + '/google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets/DeleteDataset', + request_serializer=maps_platform_datasets.DeleteDatasetRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_dataset'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.create_dataset: self._wrap_method( + self.create_dataset, + default_timeout=60.0, + client_info=client_info, + ), + self.update_dataset_metadata: self._wrap_method( + self.update_dataset_metadata, + default_timeout=60.0, + client_info=client_info, + ), + self.get_dataset: self._wrap_method( + self.get_dataset, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.fetch_dataset_errors: self._wrap_method( + self.fetch_dataset_errors, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_datasets: self._wrap_method( + self.list_datasets, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_dataset: self._wrap_method( + self.delete_dataset, + default_timeout=60.0, + 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__ = ( + 'MapsPlatformDatasetsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/rest.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/rest.py new file mode 100644 index 000000000000..0a4d5499984d --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/rest.py @@ -0,0 +1,1051 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +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.maps.mapsplatformdatasets_v1.types import dataset +from google.maps.mapsplatformdatasets_v1.types import dataset as gmm_dataset +from google.maps.mapsplatformdatasets_v1.types import maps_platform_datasets +from google.protobuf import empty_pb2 # type: ignore + + +from .rest_base import _BaseMapsPlatformDatasetsRestTransport +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}", +) + + +class MapsPlatformDatasetsRestInterceptor: + """Interceptor for MapsPlatformDatasets. + + 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 MapsPlatformDatasetsRestTransport. + + .. code-block:: python + class MyCustomMapsPlatformDatasetsInterceptor(MapsPlatformDatasetsRestInterceptor): + def pre_create_dataset(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_dataset(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_dataset(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_fetch_dataset_errors(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_fetch_dataset_errors(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_dataset(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_dataset(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_datasets(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_datasets(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_dataset_metadata(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_dataset_metadata(self, response): + logging.log(f"Received response: {response}") + return response + + transport = MapsPlatformDatasetsRestTransport(interceptor=MyCustomMapsPlatformDatasetsInterceptor()) + client = MapsPlatformDatasetsClient(transport=transport) + + + """ + def pre_create_dataset(self, request: maps_platform_datasets.CreateDatasetRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[maps_platform_datasets.CreateDatasetRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_dataset + + Override in a subclass to manipulate the request or metadata + before they are sent to the MapsPlatformDatasets server. + """ + return request, metadata + + def post_create_dataset(self, response: gmm_dataset.Dataset) -> gmm_dataset.Dataset: + """Post-rpc interceptor for create_dataset + + Override in a subclass to manipulate the response + after it is returned by the MapsPlatformDatasets server but before + it is returned to user code. + """ + return response + + def pre_delete_dataset(self, request: maps_platform_datasets.DeleteDatasetRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[maps_platform_datasets.DeleteDatasetRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_dataset + + Override in a subclass to manipulate the request or metadata + before they are sent to the MapsPlatformDatasets server. + """ + return request, metadata + + def pre_fetch_dataset_errors(self, request: maps_platform_datasets.FetchDatasetErrorsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[maps_platform_datasets.FetchDatasetErrorsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for fetch_dataset_errors + + Override in a subclass to manipulate the request or metadata + before they are sent to the MapsPlatformDatasets server. + """ + return request, metadata + + def post_fetch_dataset_errors(self, response: maps_platform_datasets.FetchDatasetErrorsResponse) -> maps_platform_datasets.FetchDatasetErrorsResponse: + """Post-rpc interceptor for fetch_dataset_errors + + Override in a subclass to manipulate the response + after it is returned by the MapsPlatformDatasets server but before + it is returned to user code. + """ + return response + + def pre_get_dataset(self, request: maps_platform_datasets.GetDatasetRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[maps_platform_datasets.GetDatasetRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_dataset + + Override in a subclass to manipulate the request or metadata + before they are sent to the MapsPlatformDatasets server. + """ + return request, metadata + + def post_get_dataset(self, response: dataset.Dataset) -> dataset.Dataset: + """Post-rpc interceptor for get_dataset + + Override in a subclass to manipulate the response + after it is returned by the MapsPlatformDatasets server but before + it is returned to user code. + """ + return response + + def pre_list_datasets(self, request: maps_platform_datasets.ListDatasetsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[maps_platform_datasets.ListDatasetsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_datasets + + Override in a subclass to manipulate the request or metadata + before they are sent to the MapsPlatformDatasets server. + """ + return request, metadata + + def post_list_datasets(self, response: maps_platform_datasets.ListDatasetsResponse) -> maps_platform_datasets.ListDatasetsResponse: + """Post-rpc interceptor for list_datasets + + Override in a subclass to manipulate the response + after it is returned by the MapsPlatformDatasets server but before + it is returned to user code. + """ + return response + + def pre_update_dataset_metadata(self, request: maps_platform_datasets.UpdateDatasetMetadataRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[maps_platform_datasets.UpdateDatasetMetadataRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_dataset_metadata + + Override in a subclass to manipulate the request or metadata + before they are sent to the MapsPlatformDatasets server. + """ + return request, metadata + + def post_update_dataset_metadata(self, response: gmm_dataset.Dataset) -> gmm_dataset.Dataset: + """Post-rpc interceptor for update_dataset_metadata + + Override in a subclass to manipulate the response + after it is returned by the MapsPlatformDatasets server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class MapsPlatformDatasetsRestStub: + _session: AuthorizedSession + _host: str + _interceptor: MapsPlatformDatasetsRestInterceptor + + +class MapsPlatformDatasetsRestTransport(_BaseMapsPlatformDatasetsRestTransport): + """REST backend synchronous transport for MapsPlatformDatasets. + + Service definition for the Maps Platform Datasets 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 = 'mapsplatformdatasets.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[MapsPlatformDatasetsRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'mapsplatformdatasets.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to 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 MapsPlatformDatasetsRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateDataset(_BaseMapsPlatformDatasetsRestTransport._BaseCreateDataset, MapsPlatformDatasetsRestStub): + def __hash__(self): + return hash("MapsPlatformDatasetsRestTransport.CreateDataset") + + @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: maps_platform_datasets.CreateDatasetRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> gmm_dataset.Dataset: + r"""Call the create dataset method over HTTP. + + Args: + request (~.maps_platform_datasets.CreateDatasetRequest): + The request object. Request to create a maps dataset. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gmm_dataset.Dataset: + A representation of a dataset + resource. + + """ + + http_options = _BaseMapsPlatformDatasetsRestTransport._BaseCreateDataset._get_http_options() + + request, metadata = self._interceptor.pre_create_dataset(request, metadata) + transcoded_request = _BaseMapsPlatformDatasetsRestTransport._BaseCreateDataset._get_transcoded_request(http_options, request) + + body = _BaseMapsPlatformDatasetsRestTransport._BaseCreateDataset._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseMapsPlatformDatasetsRestTransport._BaseCreateDataset._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient.CreateDataset", + extra = { + "serviceName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "rpcName": "CreateDataset", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MapsPlatformDatasetsRestTransport._CreateDataset._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 = gmm_dataset.Dataset() + pb_resp = gmm_dataset.Dataset.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_dataset(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = gmm_dataset.Dataset.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.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient.create_dataset", + extra = { + "serviceName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "rpcName": "CreateDataset", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteDataset(_BaseMapsPlatformDatasetsRestTransport._BaseDeleteDataset, MapsPlatformDatasetsRestStub): + def __hash__(self): + return hash("MapsPlatformDatasetsRestTransport.DeleteDataset") + + @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: maps_platform_datasets.DeleteDatasetRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): + r"""Call the delete dataset method over HTTP. + + Args: + request (~.maps_platform_datasets.DeleteDatasetRequest): + The request object. Request to delete a dataset. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 = _BaseMapsPlatformDatasetsRestTransport._BaseDeleteDataset._get_http_options() + + request, metadata = self._interceptor.pre_delete_dataset(request, metadata) + transcoded_request = _BaseMapsPlatformDatasetsRestTransport._BaseDeleteDataset._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseMapsPlatformDatasetsRestTransport._BaseDeleteDataset._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(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.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient.DeleteDataset", + extra = { + "serviceName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "rpcName": "DeleteDataset", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MapsPlatformDatasetsRestTransport._DeleteDataset._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 _FetchDatasetErrors(_BaseMapsPlatformDatasetsRestTransport._BaseFetchDatasetErrors, MapsPlatformDatasetsRestStub): + def __hash__(self): + return hash("MapsPlatformDatasetsRestTransport.FetchDatasetErrors") + + @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: maps_platform_datasets.FetchDatasetErrorsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> maps_platform_datasets.FetchDatasetErrorsResponse: + r"""Call the fetch dataset errors method over HTTP. + + Args: + request (~.maps_platform_datasets.FetchDatasetErrorsRequest): + The request object. Request to list detailed errors + belonging to a dataset. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.maps_platform_datasets.FetchDatasetErrorsResponse: + Response object of + FetchDatasetErrors. + + """ + + http_options = _BaseMapsPlatformDatasetsRestTransport._BaseFetchDatasetErrors._get_http_options() + + request, metadata = self._interceptor.pre_fetch_dataset_errors(request, metadata) + transcoded_request = _BaseMapsPlatformDatasetsRestTransport._BaseFetchDatasetErrors._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseMapsPlatformDatasetsRestTransport._BaseFetchDatasetErrors._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient.FetchDatasetErrors", + extra = { + "serviceName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "rpcName": "FetchDatasetErrors", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MapsPlatformDatasetsRestTransport._FetchDatasetErrors._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 = maps_platform_datasets.FetchDatasetErrorsResponse() + pb_resp = maps_platform_datasets.FetchDatasetErrorsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_fetch_dataset_errors(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = maps_platform_datasets.FetchDatasetErrorsResponse.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.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient.fetch_dataset_errors", + extra = { + "serviceName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "rpcName": "FetchDatasetErrors", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetDataset(_BaseMapsPlatformDatasetsRestTransport._BaseGetDataset, MapsPlatformDatasetsRestStub): + def __hash__(self): + return hash("MapsPlatformDatasetsRestTransport.GetDataset") + + @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: maps_platform_datasets.GetDatasetRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> dataset.Dataset: + r"""Call the get dataset method over HTTP. + + Args: + request (~.maps_platform_datasets.GetDatasetRequest): + The request object. Request to get the specified dataset. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.dataset.Dataset: + A representation of a dataset + resource. + + """ + + http_options = _BaseMapsPlatformDatasetsRestTransport._BaseGetDataset._get_http_options() + + request, metadata = self._interceptor.pre_get_dataset(request, metadata) + transcoded_request = _BaseMapsPlatformDatasetsRestTransport._BaseGetDataset._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseMapsPlatformDatasetsRestTransport._BaseGetDataset._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient.GetDataset", + extra = { + "serviceName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "rpcName": "GetDataset", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MapsPlatformDatasetsRestTransport._GetDataset._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 = dataset.Dataset() + pb_resp = dataset.Dataset.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_dataset(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = dataset.Dataset.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.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient.get_dataset", + extra = { + "serviceName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "rpcName": "GetDataset", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListDatasets(_BaseMapsPlatformDatasetsRestTransport._BaseListDatasets, MapsPlatformDatasetsRestStub): + def __hash__(self): + return hash("MapsPlatformDatasetsRestTransport.ListDatasets") + + @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: maps_platform_datasets.ListDatasetsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> maps_platform_datasets.ListDatasetsResponse: + r"""Call the list datasets method over HTTP. + + Args: + request (~.maps_platform_datasets.ListDatasetsRequest): + The request object. Request to list datasets for the + project. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.maps_platform_datasets.ListDatasetsResponse: + Response object of ListDatasets. + """ + + http_options = _BaseMapsPlatformDatasetsRestTransport._BaseListDatasets._get_http_options() + + request, metadata = self._interceptor.pre_list_datasets(request, metadata) + transcoded_request = _BaseMapsPlatformDatasetsRestTransport._BaseListDatasets._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseMapsPlatformDatasetsRestTransport._BaseListDatasets._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient.ListDatasets", + extra = { + "serviceName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "rpcName": "ListDatasets", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MapsPlatformDatasetsRestTransport._ListDatasets._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 = maps_platform_datasets.ListDatasetsResponse() + pb_resp = maps_platform_datasets.ListDatasetsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_datasets(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = maps_platform_datasets.ListDatasetsResponse.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.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient.list_datasets", + extra = { + "serviceName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "rpcName": "ListDatasets", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateDatasetMetadata(_BaseMapsPlatformDatasetsRestTransport._BaseUpdateDatasetMetadata, MapsPlatformDatasetsRestStub): + def __hash__(self): + return hash("MapsPlatformDatasetsRestTransport.UpdateDatasetMetadata") + + @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: maps_platform_datasets.UpdateDatasetMetadataRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> gmm_dataset.Dataset: + r"""Call the update dataset metadata method over HTTP. + + Args: + request (~.maps_platform_datasets.UpdateDatasetMetadataRequest): + The request object. Request to update the metadata fields + of the dataset. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gmm_dataset.Dataset: + A representation of a dataset + resource. + + """ + + http_options = _BaseMapsPlatformDatasetsRestTransport._BaseUpdateDatasetMetadata._get_http_options() + + request, metadata = self._interceptor.pre_update_dataset_metadata(request, metadata) + transcoded_request = _BaseMapsPlatformDatasetsRestTransport._BaseUpdateDatasetMetadata._get_transcoded_request(http_options, request) + + body = _BaseMapsPlatformDatasetsRestTransport._BaseUpdateDatasetMetadata._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseMapsPlatformDatasetsRestTransport._BaseUpdateDatasetMetadata._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient.UpdateDatasetMetadata", + extra = { + "serviceName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "rpcName": "UpdateDatasetMetadata", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MapsPlatformDatasetsRestTransport._UpdateDatasetMetadata._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 = gmm_dataset.Dataset() + pb_resp = gmm_dataset.Dataset.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_dataset_metadata(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = gmm_dataset.Dataset.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.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient.update_dataset_metadata", + extra = { + "serviceName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "rpcName": "UpdateDatasetMetadata", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_dataset(self) -> Callable[ + [maps_platform_datasets.CreateDatasetRequest], + gmm_dataset.Dataset]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateDataset(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_dataset(self) -> Callable[ + [maps_platform_datasets.DeleteDatasetRequest], + 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._DeleteDataset(self._session, self._host, self._interceptor) # type: ignore + + @property + def fetch_dataset_errors(self) -> Callable[ + [maps_platform_datasets.FetchDatasetErrorsRequest], + maps_platform_datasets.FetchDatasetErrorsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._FetchDatasetErrors(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_dataset(self) -> Callable[ + [maps_platform_datasets.GetDatasetRequest], + dataset.Dataset]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetDataset(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_datasets(self) -> Callable[ + [maps_platform_datasets.ListDatasetsRequest], + maps_platform_datasets.ListDatasetsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListDatasets(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_dataset_metadata(self) -> Callable[ + [maps_platform_datasets.UpdateDatasetMetadataRequest], + gmm_dataset.Dataset]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateDatasetMetadata(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'MapsPlatformDatasetsRestTransport', +) diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/rest_base.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/rest_base.py new file mode 100644 index 000000000000..464ab2674fce --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/rest_base.py @@ -0,0 +1,336 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 MapsPlatformDatasetsTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.maps.mapsplatformdatasets_v1.types import dataset +from google.maps.mapsplatformdatasets_v1.types import dataset as gmm_dataset +from google.maps.mapsplatformdatasets_v1.types import maps_platform_datasets +from google.protobuf import empty_pb2 # type: ignore + + +class _BaseMapsPlatformDatasetsRestTransport(MapsPlatformDatasetsTransport): + """Base REST backend transport for MapsPlatformDatasets. + + 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 = 'mapsplatformdatasets.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: 'mapsplatformdatasets.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 _BaseCreateDataset: + 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': '/v1/{parent=projects/*}/datasets', + 'body': 'dataset', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = maps_platform_datasets.CreateDatasetRequest.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(_BaseMapsPlatformDatasetsRestTransport._BaseCreateDataset._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteDataset: + 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': '/v1/{name=projects/*/datasets/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = maps_platform_datasets.DeleteDatasetRequest.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(_BaseMapsPlatformDatasetsRestTransport._BaseDeleteDataset._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseFetchDatasetErrors: + 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': '/v1/{dataset=projects/*/datasets/*}:fetchDatasetErrors', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = maps_platform_datasets.FetchDatasetErrorsRequest.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(_BaseMapsPlatformDatasetsRestTransport._BaseFetchDatasetErrors._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetDataset: + 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': '/v1/{name=projects/*/datasets/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = maps_platform_datasets.GetDatasetRequest.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(_BaseMapsPlatformDatasetsRestTransport._BaseGetDataset._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListDatasets: + 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': '/v1/{parent=projects/*}/datasets', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = maps_platform_datasets.ListDatasetsRequest.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(_BaseMapsPlatformDatasetsRestTransport._BaseListDatasets._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateDatasetMetadata: + 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': '/v1/{dataset.name=projects/*/datasets/*}', + 'body': 'dataset', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = maps_platform_datasets.UpdateDatasetMetadataRequest.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(_BaseMapsPlatformDatasetsRestTransport._BaseUpdateDatasetMetadata._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseMapsPlatformDatasetsRestTransport', +) diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/types/__init__.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/types/__init__.py new file mode 100644 index 000000000000..64e0edf7cc91 --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/types/__init__.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .data_source import ( + GcsSource, + LocalFileSource, + FileFormat, +) +from .dataset import ( + Dataset, + Status, + Usage, +) +from .maps_platform_datasets import ( + CreateDatasetRequest, + DeleteDatasetRequest, + FetchDatasetErrorsRequest, + FetchDatasetErrorsResponse, + GetDatasetRequest, + ListDatasetsRequest, + ListDatasetsResponse, + UpdateDatasetMetadataRequest, +) + +__all__ = ( + 'GcsSource', + 'LocalFileSource', + 'FileFormat', + 'Dataset', + 'Status', + 'Usage', + 'CreateDatasetRequest', + 'DeleteDatasetRequest', + 'FetchDatasetErrorsRequest', + 'FetchDatasetErrorsResponse', + 'GetDatasetRequest', + 'ListDatasetsRequest', + 'ListDatasetsResponse', + 'UpdateDatasetMetadataRequest', +) diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/types/data_source.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/types/data_source.py new file mode 100644 index 000000000000..6957a23d1849 --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/types/data_source.py @@ -0,0 +1,97 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.mapsplatformdatasets.v1', + manifest={ + 'FileFormat', + 'LocalFileSource', + 'GcsSource', + }, +) + + +class FileFormat(proto.Enum): + r"""The format of the file being uploaded. + + Values: + FILE_FORMAT_UNSPECIFIED (0): + Unspecified file format. + FILE_FORMAT_GEOJSON (1): + GeoJson file. + FILE_FORMAT_KML (2): + KML file. + FILE_FORMAT_CSV (3): + CSV file. + """ + FILE_FORMAT_UNSPECIFIED = 0 + FILE_FORMAT_GEOJSON = 1 + FILE_FORMAT_KML = 2 + FILE_FORMAT_CSV = 3 + + +class LocalFileSource(proto.Message): + r"""The details about the data source when it is a local file. + + Attributes: + filename (str): + The file name of the uploaded file. + file_format (google.maps.mapsplatformdatasets_v1.types.FileFormat): + The format of the file that is being + uploaded. + """ + + filename: str = proto.Field( + proto.STRING, + number=1, + ) + file_format: 'FileFormat' = proto.Field( + proto.ENUM, + number=2, + enum='FileFormat', + ) + + +class GcsSource(proto.Message): + r"""The details about the data source when it is in Google Cloud + Storage. + + Attributes: + input_uri (str): + Source data URI. For example, ``gs://my_bucket/my_object``. + file_format (google.maps.mapsplatformdatasets_v1.types.FileFormat): + The file format of the Google Cloud Storage + object. This is used mainly for validation. + """ + + input_uri: str = proto.Field( + proto.STRING, + number=1, + ) + file_format: 'FileFormat' = proto.Field( + proto.ENUM, + number=2, + enum='FileFormat', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/types/dataset.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/types/dataset.py new file mode 100644 index 000000000000..712ba7ac6361 --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/types/dataset.py @@ -0,0 +1,236 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.mapsplatformdatasets_v1.types import data_source +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.mapsplatformdatasets.v1', + manifest={ + 'Usage', + 'Dataset', + 'Status', + }, +) + + +class Usage(proto.Enum): + r"""Usage specifies where the data is intended to be used to + inform how to process the data. + + Values: + USAGE_UNSPECIFIED (0): + The usage of this dataset is not set. + USAGE_DATA_DRIVEN_STYLING (1): + This dataset will be used for data driven + styling. + """ + USAGE_UNSPECIFIED = 0 + USAGE_DATA_DRIVEN_STYLING = 1 + + +class Dataset(proto.Message): + r"""A representation of a dataset resource. + + 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: + name (str): + Resource name. Format: + projects/{project}/datasets/{dataset_id} + display_name (str): + Human readable name, shown in the console UI. + + Must be unique within a project. + description (str): + A description of this dataset. + version_id (str): + The version ID of the dataset. + usage (MutableSequence[google.maps.mapsplatformdatasets_v1.types.Usage]): + Specified use case for this dataset. + local_file_source (google.maps.mapsplatformdatasets_v1.types.LocalFileSource): + A local file source for the dataset for a + single upload. + + This field is a member of `oneof`_ ``data_source``. + gcs_source (google.maps.mapsplatformdatasets_v1.types.GcsSource): + A Google Cloud Storage file source for the + dataset for a single upload. + + This field is a member of `oneof`_ ``data_source``. + status (google.maps.mapsplatformdatasets_v1.types.Status): + Output only. The status of this dataset + version. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when the dataset was first + created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when the dataset metadata + was last updated. + version_create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this version was + created. + version_description (str): + Output only. The description for this version + of dataset. It is provided when importing data + to the dataset. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + version_id: str = proto.Field( + proto.STRING, + number=4, + ) + usage: MutableSequence['Usage'] = proto.RepeatedField( + proto.ENUM, + number=5, + enum='Usage', + ) + local_file_source: data_source.LocalFileSource = proto.Field( + proto.MESSAGE, + number=6, + oneof='data_source', + message=data_source.LocalFileSource, + ) + gcs_source: data_source.GcsSource = proto.Field( + proto.MESSAGE, + number=7, + oneof='data_source', + message=data_source.GcsSource, + ) + status: 'Status' = proto.Field( + proto.MESSAGE, + number=12, + message='Status', + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + version_create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + version_description: str = proto.Field( + proto.STRING, + number=11, + ) + + +class Status(proto.Message): + r"""Status of the dataset. + + Attributes: + state (google.maps.mapsplatformdatasets_v1.types.Status.State): + State enum for status. + error_message (str): + Error message indicating reason of failure. + It is empty if the datasets is not in a failed + state. + """ + class State(proto.Enum): + r"""A list of states for the dataset. + + Values: + STATE_UNSPECIFIED (0): + The state of this dataset is not set. + STATE_IMPORTING (1): + Data is being imported to a dataset. + STATE_IMPORT_SUCCEEDED (2): + Importing data to a dataset succeeded. + STATE_IMPORT_FAILED (3): + Importing data to a dataset failed. + STATE_DELETING (4): + The dataset is in the process of getting + deleted. + STATE_DELETION_FAILED (5): + The deletion failed state. This state + represents that dataset deletion has failed. + Deletion may be retried. + STATE_PROCESSING (6): + Data is being processed. + STATE_PROCESSING_FAILED (7): + The processing failed state. This state + represents that processing has failed and may + report errors. + STATE_NEEDS_REVIEW (8): + This state is currently not used. + STATE_PUBLISHING (9): + The publishing state. This state represents + the publishing is in progress. + STATE_PUBLISHING_FAILED (10): + The publishing failed states. This state + represents that the publishing failed. + Publishing may be retried. + STATE_COMPLETED (11): + The completed state. This state represents + the dataset being available for its specific + usage. + """ + STATE_UNSPECIFIED = 0 + STATE_IMPORTING = 1 + STATE_IMPORT_SUCCEEDED = 2 + STATE_IMPORT_FAILED = 3 + STATE_DELETING = 4 + STATE_DELETION_FAILED = 5 + STATE_PROCESSING = 6 + STATE_PROCESSING_FAILED = 7 + STATE_NEEDS_REVIEW = 8 + STATE_PUBLISHING = 9 + STATE_PUBLISHING_FAILED = 10 + STATE_COMPLETED = 11 + + state: State = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + error_message: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/types/maps_platform_datasets.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/types/maps_platform_datasets.py new file mode 100644 index 000000000000..df36e87d1582 --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/types/maps_platform_datasets.py @@ -0,0 +1,265 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.mapsplatformdatasets_v1.types import dataset as gmm_dataset +from google.protobuf import field_mask_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.mapsplatformdatasets.v1', + manifest={ + 'CreateDatasetRequest', + 'UpdateDatasetMetadataRequest', + 'GetDatasetRequest', + 'ListDatasetsRequest', + 'ListDatasetsResponse', + 'FetchDatasetErrorsRequest', + 'FetchDatasetErrorsResponse', + 'DeleteDatasetRequest', + }, +) + + +class CreateDatasetRequest(proto.Message): + r"""Request to create a maps dataset. + + Attributes: + parent (str): + Required. Parent project that will own the + dataset. Format: projects/{project} + dataset (google.maps.mapsplatformdatasets_v1.types.Dataset): + Required. The dataset version to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + dataset: gmm_dataset.Dataset = proto.Field( + proto.MESSAGE, + number=2, + message=gmm_dataset.Dataset, + ) + + +class UpdateDatasetMetadataRequest(proto.Message): + r"""Request to update the metadata fields of the dataset. + + Attributes: + dataset (google.maps.mapsplatformdatasets_v1.types.Dataset): + Required. Resource name of the dataset to update. Format: + projects/{project}/datasets/{dataset_id} + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. + + The value "*" is used for full replacement (default). + """ + + dataset: gmm_dataset.Dataset = proto.Field( + proto.MESSAGE, + number=1, + message=gmm_dataset.Dataset, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class GetDatasetRequest(proto.Message): + r"""Request to get the specified dataset. + + Attributes: + name (str): + Required. Resource name. Format: + projects/{project}/datasets/{dataset_id} + + Can also fetch some special versions by appending "@" and a + tag. Format: projects/{project}/datasets/{dataset_id}@{tag} + + Tag "active": The info of the latest completed version will + be included, and NOT_FOUND if the dataset does not have one. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListDatasetsRequest(proto.Message): + r"""Request to list datasets for the project. + + Attributes: + parent (str): + Required. The name of the project to list all + the datasets for. Format: projects/{project} + page_size (int): + The maximum number of datasets to return per + page. + If unspecified (or zero), all datasets will be + returned. + page_token (str): + The page token, received from a previous + ListDatasets call. Provide this to retrieve the + subsequent page. + tag (str): + The tag that specifies the desired version + for each dataset. + Note that when pagination is also specified, + some filtering can happen after pagination, + which may cause the response to contain fewer + datasets than the page size, even if it's not + the last page. + + Tag "active": Each dataset in the response will + include the info of its latest completed + version, and the dataset will be skipped if it + does not have one. + """ + + 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, + ) + tag: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListDatasetsResponse(proto.Message): + r"""Response object of ListDatasets. + + Attributes: + datasets (MutableSequence[google.maps.mapsplatformdatasets_v1.types.Dataset]): + All the datasets for the project. + 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 + + datasets: MutableSequence[gmm_dataset.Dataset] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gmm_dataset.Dataset, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class FetchDatasetErrorsRequest(proto.Message): + r"""Request to list detailed errors belonging to a dataset. + + Attributes: + dataset (str): + Required. The name of the dataset to list all the errors + for. Format: projects/{project}/datasets/{dataset_id} + page_size (int): + The maximum number of errors to return per + page. + The maximum value is 500; values above 500 will + be capped to 500. + + If unspecified, at most 50 errors will be + returned. + page_token (str): + The page token, received from a previous + ListDatasetErrors call. Provide this to retrieve + the subsequent page. + """ + + dataset: 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 FetchDatasetErrorsResponse(proto.Message): + r"""Response object of FetchDatasetErrors. + + Attributes: + 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. + errors (MutableSequence[google.rpc.status_pb2.Status]): + The errors associated with a dataset. + """ + + @property + def raw_page(self): + return self + + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + errors: MutableSequence[status_pb2.Status] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=status_pb2.Status, + ) + + +class DeleteDatasetRequest(proto.Message): + r"""Request to delete a dataset. + + Attributes: + name (str): + Required. The name of the dataset to delete. Format: + projects/{project}/datasets/{dataset_id} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/types/maps_platform_datasets_service.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/types/maps_platform_datasets_service.py new file mode 100644 index 000000000000..4224501e4543 --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/types/maps_platform_datasets_service.py @@ -0,0 +1,26 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.mapsplatformdatasets.v1', + manifest={ + }, +) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/mypy.ini b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/noxfile.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/noxfile.py new file mode 100644 index 000000000000..3d09ce6c0f5a --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/noxfile.py @@ -0,0 +1,280 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = 'google-maps-mapsplatformdatasets' + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.13" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "prerelease_deps", +] + +@nox.session(python=ALL_PYTHON) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def unit(session, protobuf_implementation): + """Run the unit test suite.""" + + 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+") + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") + + # 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") + + session.run( + 'py.test', + '--quiet', + '--cov=google/maps/mapsplatformdatasets_v1/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)), + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + +@nox.session(python=ALL_PYTHON[-1]) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def prerelease_deps(session, protobuf_implementation): + """Run the unit test suite against pre-release versions of dependencies.""" + + 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 test environment dependencies + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + + # Install the package without dependencies + session.install('-e', '.', '--no-deps') + + # We test the minimum dependency versions using the minimum Python + # version so the lowest python runtime that we test has a corresponding constraints + # file, located at `testing/constraints--.txt`, which contains all of the + # 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 + ) + ] + + session.install(*constraints_deps) + + prerel_deps = [ + "googleapis-common-protos", + "google-api-core", + "google-auth", + # Exclude grpcio!=1.67.0rc1 which does not support python 3.13 + "grpcio!=1.67.0rc1", + "grpcio-status", + "protobuf", + "proto-plus", + ] + + for dep in prerel_deps: + session.install("--pre", "--no-deps", "--upgrade", dep) + + # Remaining dependencies + other_deps = [ + "requests", + ] + session.install(*other_deps) + + # Print out prerelease package versions + + session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") + session.run("python", "-c", "import google.auth; print(google.auth.__version__)") + session.run("python", "-c", "import grpc; print(grpc.__version__)") + session.run( + "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" + ) + session.run( + "python", "-c", "import proto; print(proto.__version__)" + ) + + session.run( + 'py.test', + '--quiet', + '--cov=google/maps/mapsplatformdatasets_v1/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)), + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + + +@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=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 docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==7.0.1", "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=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", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_create_dataset_async.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_create_dataset_async.py new file mode 100644 index 000000000000..5b50f1a1217e --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_create_dataset_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateDataset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-mapsplatformdatasets + + +# [START mapsplatformdatasets_v1_generated_MapsPlatformDatasets_CreateDataset_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.maps import mapsplatformdatasets_v1 + + +async def sample_create_dataset(): + # Create a client + client = mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient() + + # Initialize request argument(s) + request = mapsplatformdatasets_v1.CreateDatasetRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_dataset(request=request) + + # Handle the response + print(response) + +# [END mapsplatformdatasets_v1_generated_MapsPlatformDatasets_CreateDataset_async] diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_create_dataset_sync.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_create_dataset_sync.py new file mode 100644 index 000000000000..2df3d5dbcf12 --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_create_dataset_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateDataset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-mapsplatformdatasets + + +# [START mapsplatformdatasets_v1_generated_MapsPlatformDatasets_CreateDataset_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.maps import mapsplatformdatasets_v1 + + +def sample_create_dataset(): + # Create a client + client = mapsplatformdatasets_v1.MapsPlatformDatasetsClient() + + # Initialize request argument(s) + request = mapsplatformdatasets_v1.CreateDatasetRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_dataset(request=request) + + # Handle the response + print(response) + +# [END mapsplatformdatasets_v1_generated_MapsPlatformDatasets_CreateDataset_sync] diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_delete_dataset_async.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_delete_dataset_async.py new file mode 100644 index 000000000000..b290ae5be047 --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_delete_dataset_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteDataset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-mapsplatformdatasets + + +# [START mapsplatformdatasets_v1_generated_MapsPlatformDatasets_DeleteDataset_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.maps import mapsplatformdatasets_v1 + + +async def sample_delete_dataset(): + # Create a client + client = mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient() + + # Initialize request argument(s) + request = mapsplatformdatasets_v1.DeleteDatasetRequest( + name="name_value", + ) + + # Make the request + await client.delete_dataset(request=request) + + +# [END mapsplatformdatasets_v1_generated_MapsPlatformDatasets_DeleteDataset_async] diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_delete_dataset_sync.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_delete_dataset_sync.py new file mode 100644 index 000000000000..c7179f4147ac --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_delete_dataset_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteDataset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-mapsplatformdatasets + + +# [START mapsplatformdatasets_v1_generated_MapsPlatformDatasets_DeleteDataset_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.maps import mapsplatformdatasets_v1 + + +def sample_delete_dataset(): + # Create a client + client = mapsplatformdatasets_v1.MapsPlatformDatasetsClient() + + # Initialize request argument(s) + request = mapsplatformdatasets_v1.DeleteDatasetRequest( + name="name_value", + ) + + # Make the request + client.delete_dataset(request=request) + + +# [END mapsplatformdatasets_v1_generated_MapsPlatformDatasets_DeleteDataset_sync] diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_fetch_dataset_errors_async.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_fetch_dataset_errors_async.py new file mode 100644 index 000000000000..993b9aa8fe4e --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_fetch_dataset_errors_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for FetchDatasetErrors +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-mapsplatformdatasets + + +# [START mapsplatformdatasets_v1_generated_MapsPlatformDatasets_FetchDatasetErrors_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.maps import mapsplatformdatasets_v1 + + +async def sample_fetch_dataset_errors(): + # Create a client + client = mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient() + + # Initialize request argument(s) + request = mapsplatformdatasets_v1.FetchDatasetErrorsRequest( + dataset="dataset_value", + ) + + # Make the request + page_result = client.fetch_dataset_errors(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END mapsplatformdatasets_v1_generated_MapsPlatformDatasets_FetchDatasetErrors_async] diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_fetch_dataset_errors_sync.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_fetch_dataset_errors_sync.py new file mode 100644 index 000000000000..644e0a562566 --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_fetch_dataset_errors_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for FetchDatasetErrors +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-mapsplatformdatasets + + +# [START mapsplatformdatasets_v1_generated_MapsPlatformDatasets_FetchDatasetErrors_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.maps import mapsplatformdatasets_v1 + + +def sample_fetch_dataset_errors(): + # Create a client + client = mapsplatformdatasets_v1.MapsPlatformDatasetsClient() + + # Initialize request argument(s) + request = mapsplatformdatasets_v1.FetchDatasetErrorsRequest( + dataset="dataset_value", + ) + + # Make the request + page_result = client.fetch_dataset_errors(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END mapsplatformdatasets_v1_generated_MapsPlatformDatasets_FetchDatasetErrors_sync] diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_get_dataset_async.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_get_dataset_async.py new file mode 100644 index 000000000000..312e767bd626 --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_get_dataset_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDataset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-mapsplatformdatasets + + +# [START mapsplatformdatasets_v1_generated_MapsPlatformDatasets_GetDataset_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.maps import mapsplatformdatasets_v1 + + +async def sample_get_dataset(): + # Create a client + client = mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient() + + # Initialize request argument(s) + request = mapsplatformdatasets_v1.GetDatasetRequest( + name="name_value", + ) + + # Make the request + response = await client.get_dataset(request=request) + + # Handle the response + print(response) + +# [END mapsplatformdatasets_v1_generated_MapsPlatformDatasets_GetDataset_async] diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_get_dataset_sync.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_get_dataset_sync.py new file mode 100644 index 000000000000..0acc34dfa04a --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_get_dataset_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDataset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-mapsplatformdatasets + + +# [START mapsplatformdatasets_v1_generated_MapsPlatformDatasets_GetDataset_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.maps import mapsplatformdatasets_v1 + + +def sample_get_dataset(): + # Create a client + client = mapsplatformdatasets_v1.MapsPlatformDatasetsClient() + + # Initialize request argument(s) + request = mapsplatformdatasets_v1.GetDatasetRequest( + name="name_value", + ) + + # Make the request + response = client.get_dataset(request=request) + + # Handle the response + print(response) + +# [END mapsplatformdatasets_v1_generated_MapsPlatformDatasets_GetDataset_sync] diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_list_datasets_async.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_list_datasets_async.py new file mode 100644 index 000000000000..8d05703b3263 --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_list_datasets_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListDatasets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-mapsplatformdatasets + + +# [START mapsplatformdatasets_v1_generated_MapsPlatformDatasets_ListDatasets_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.maps import mapsplatformdatasets_v1 + + +async def sample_list_datasets(): + # Create a client + client = mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient() + + # Initialize request argument(s) + request = mapsplatformdatasets_v1.ListDatasetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_datasets(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END mapsplatformdatasets_v1_generated_MapsPlatformDatasets_ListDatasets_async] diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_list_datasets_sync.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_list_datasets_sync.py new file mode 100644 index 000000000000..648a02bc6842 --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_list_datasets_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListDatasets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-mapsplatformdatasets + + +# [START mapsplatformdatasets_v1_generated_MapsPlatformDatasets_ListDatasets_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.maps import mapsplatformdatasets_v1 + + +def sample_list_datasets(): + # Create a client + client = mapsplatformdatasets_v1.MapsPlatformDatasetsClient() + + # Initialize request argument(s) + request = mapsplatformdatasets_v1.ListDatasetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_datasets(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END mapsplatformdatasets_v1_generated_MapsPlatformDatasets_ListDatasets_sync] diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_update_dataset_metadata_async.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_update_dataset_metadata_async.py new file mode 100644 index 000000000000..ef0886fafc21 --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_update_dataset_metadata_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateDatasetMetadata +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-mapsplatformdatasets + + +# [START mapsplatformdatasets_v1_generated_MapsPlatformDatasets_UpdateDatasetMetadata_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.maps import mapsplatformdatasets_v1 + + +async def sample_update_dataset_metadata(): + # Create a client + client = mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient() + + # Initialize request argument(s) + request = mapsplatformdatasets_v1.UpdateDatasetMetadataRequest( + ) + + # Make the request + response = await client.update_dataset_metadata(request=request) + + # Handle the response + print(response) + +# [END mapsplatformdatasets_v1_generated_MapsPlatformDatasets_UpdateDatasetMetadata_async] diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_update_dataset_metadata_sync.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_update_dataset_metadata_sync.py new file mode 100644 index 000000000000..da429a9ff436 --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_update_dataset_metadata_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateDatasetMetadata +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-mapsplatformdatasets + + +# [START mapsplatformdatasets_v1_generated_MapsPlatformDatasets_UpdateDatasetMetadata_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.maps import mapsplatformdatasets_v1 + + +def sample_update_dataset_metadata(): + # Create a client + client = mapsplatformdatasets_v1.MapsPlatformDatasetsClient() + + # Initialize request argument(s) + request = mapsplatformdatasets_v1.UpdateDatasetMetadataRequest( + ) + + # Make the request + response = client.update_dataset_metadata(request=request) + + # Handle the response + print(response) + +# [END mapsplatformdatasets_v1_generated_MapsPlatformDatasets_UpdateDatasetMetadata_sync] diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/snippet_metadata_google.maps.mapsplatformdatasets.v1.json b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/snippet_metadata_google.maps.mapsplatformdatasets.v1.json new file mode 100644 index 000000000000..efd05ec97721 --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/snippet_metadata_google.maps.mapsplatformdatasets.v1.json @@ -0,0 +1,991 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.maps.mapsplatformdatasets.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-maps-mapsplatformdatasets", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient", + "shortName": "MapsPlatformDatasetsAsyncClient" + }, + "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient.create_dataset", + "method": { + "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets.CreateDataset", + "service": { + "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "shortName": "MapsPlatformDatasets" + }, + "shortName": "CreateDataset" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.mapsplatformdatasets_v1.types.CreateDatasetRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "dataset", + "type": "google.maps.mapsplatformdatasets_v1.types.Dataset" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.maps.mapsplatformdatasets_v1.types.Dataset", + "shortName": "create_dataset" + }, + "description": "Sample for CreateDataset", + "file": "mapsplatformdatasets_v1_generated_maps_platform_datasets_create_dataset_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "mapsplatformdatasets_v1_generated_MapsPlatformDatasets_CreateDataset_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": "mapsplatformdatasets_v1_generated_maps_platform_datasets_create_dataset_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient", + "shortName": "MapsPlatformDatasetsClient" + }, + "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient.create_dataset", + "method": { + "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets.CreateDataset", + "service": { + "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "shortName": "MapsPlatformDatasets" + }, + "shortName": "CreateDataset" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.mapsplatformdatasets_v1.types.CreateDatasetRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "dataset", + "type": "google.maps.mapsplatformdatasets_v1.types.Dataset" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.maps.mapsplatformdatasets_v1.types.Dataset", + "shortName": "create_dataset" + }, + "description": "Sample for CreateDataset", + "file": "mapsplatformdatasets_v1_generated_maps_platform_datasets_create_dataset_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "mapsplatformdatasets_v1_generated_MapsPlatformDatasets_CreateDataset_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": "mapsplatformdatasets_v1_generated_maps_platform_datasets_create_dataset_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient", + "shortName": "MapsPlatformDatasetsAsyncClient" + }, + "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient.delete_dataset", + "method": { + "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets.DeleteDataset", + "service": { + "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "shortName": "MapsPlatformDatasets" + }, + "shortName": "DeleteDataset" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.mapsplatformdatasets_v1.types.DeleteDatasetRequest" + }, + { + "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_dataset" + }, + "description": "Sample for DeleteDataset", + "file": "mapsplatformdatasets_v1_generated_maps_platform_datasets_delete_dataset_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "mapsplatformdatasets_v1_generated_MapsPlatformDatasets_DeleteDataset_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": "mapsplatformdatasets_v1_generated_maps_platform_datasets_delete_dataset_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient", + "shortName": "MapsPlatformDatasetsClient" + }, + "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient.delete_dataset", + "method": { + "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets.DeleteDataset", + "service": { + "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "shortName": "MapsPlatformDatasets" + }, + "shortName": "DeleteDataset" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.mapsplatformdatasets_v1.types.DeleteDatasetRequest" + }, + { + "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_dataset" + }, + "description": "Sample for DeleteDataset", + "file": "mapsplatformdatasets_v1_generated_maps_platform_datasets_delete_dataset_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "mapsplatformdatasets_v1_generated_MapsPlatformDatasets_DeleteDataset_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": "mapsplatformdatasets_v1_generated_maps_platform_datasets_delete_dataset_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient", + "shortName": "MapsPlatformDatasetsAsyncClient" + }, + "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient.fetch_dataset_errors", + "method": { + "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets.FetchDatasetErrors", + "service": { + "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "shortName": "MapsPlatformDatasets" + }, + "shortName": "FetchDatasetErrors" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.mapsplatformdatasets_v1.types.FetchDatasetErrorsRequest" + }, + { + "name": "dataset", + "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.maps.mapsplatformdatasets_v1.services.maps_platform_datasets.pagers.FetchDatasetErrorsAsyncPager", + "shortName": "fetch_dataset_errors" + }, + "description": "Sample for FetchDatasetErrors", + "file": "mapsplatformdatasets_v1_generated_maps_platform_datasets_fetch_dataset_errors_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "mapsplatformdatasets_v1_generated_MapsPlatformDatasets_FetchDatasetErrors_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": "mapsplatformdatasets_v1_generated_maps_platform_datasets_fetch_dataset_errors_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient", + "shortName": "MapsPlatformDatasetsClient" + }, + "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient.fetch_dataset_errors", + "method": { + "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets.FetchDatasetErrors", + "service": { + "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "shortName": "MapsPlatformDatasets" + }, + "shortName": "FetchDatasetErrors" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.mapsplatformdatasets_v1.types.FetchDatasetErrorsRequest" + }, + { + "name": "dataset", + "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.maps.mapsplatformdatasets_v1.services.maps_platform_datasets.pagers.FetchDatasetErrorsPager", + "shortName": "fetch_dataset_errors" + }, + "description": "Sample for FetchDatasetErrors", + "file": "mapsplatformdatasets_v1_generated_maps_platform_datasets_fetch_dataset_errors_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "mapsplatformdatasets_v1_generated_MapsPlatformDatasets_FetchDatasetErrors_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": "mapsplatformdatasets_v1_generated_maps_platform_datasets_fetch_dataset_errors_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient", + "shortName": "MapsPlatformDatasetsAsyncClient" + }, + "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient.get_dataset", + "method": { + "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets.GetDataset", + "service": { + "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "shortName": "MapsPlatformDatasets" + }, + "shortName": "GetDataset" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.mapsplatformdatasets_v1.types.GetDatasetRequest" + }, + { + "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.maps.mapsplatformdatasets_v1.types.Dataset", + "shortName": "get_dataset" + }, + "description": "Sample for GetDataset", + "file": "mapsplatformdatasets_v1_generated_maps_platform_datasets_get_dataset_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "mapsplatformdatasets_v1_generated_MapsPlatformDatasets_GetDataset_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": "mapsplatformdatasets_v1_generated_maps_platform_datasets_get_dataset_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient", + "shortName": "MapsPlatformDatasetsClient" + }, + "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient.get_dataset", + "method": { + "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets.GetDataset", + "service": { + "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "shortName": "MapsPlatformDatasets" + }, + "shortName": "GetDataset" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.mapsplatformdatasets_v1.types.GetDatasetRequest" + }, + { + "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.maps.mapsplatformdatasets_v1.types.Dataset", + "shortName": "get_dataset" + }, + "description": "Sample for GetDataset", + "file": "mapsplatformdatasets_v1_generated_maps_platform_datasets_get_dataset_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "mapsplatformdatasets_v1_generated_MapsPlatformDatasets_GetDataset_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": "mapsplatformdatasets_v1_generated_maps_platform_datasets_get_dataset_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient", + "shortName": "MapsPlatformDatasetsAsyncClient" + }, + "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient.list_datasets", + "method": { + "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets.ListDatasets", + "service": { + "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "shortName": "MapsPlatformDatasets" + }, + "shortName": "ListDatasets" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.mapsplatformdatasets_v1.types.ListDatasetsRequest" + }, + { + "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.maps.mapsplatformdatasets_v1.services.maps_platform_datasets.pagers.ListDatasetsAsyncPager", + "shortName": "list_datasets" + }, + "description": "Sample for ListDatasets", + "file": "mapsplatformdatasets_v1_generated_maps_platform_datasets_list_datasets_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "mapsplatformdatasets_v1_generated_MapsPlatformDatasets_ListDatasets_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": "mapsplatformdatasets_v1_generated_maps_platform_datasets_list_datasets_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient", + "shortName": "MapsPlatformDatasetsClient" + }, + "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient.list_datasets", + "method": { + "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets.ListDatasets", + "service": { + "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "shortName": "MapsPlatformDatasets" + }, + "shortName": "ListDatasets" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.mapsplatformdatasets_v1.types.ListDatasetsRequest" + }, + { + "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.maps.mapsplatformdatasets_v1.services.maps_platform_datasets.pagers.ListDatasetsPager", + "shortName": "list_datasets" + }, + "description": "Sample for ListDatasets", + "file": "mapsplatformdatasets_v1_generated_maps_platform_datasets_list_datasets_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "mapsplatformdatasets_v1_generated_MapsPlatformDatasets_ListDatasets_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": "mapsplatformdatasets_v1_generated_maps_platform_datasets_list_datasets_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient", + "shortName": "MapsPlatformDatasetsAsyncClient" + }, + "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient.update_dataset_metadata", + "method": { + "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets.UpdateDatasetMetadata", + "service": { + "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "shortName": "MapsPlatformDatasets" + }, + "shortName": "UpdateDatasetMetadata" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.mapsplatformdatasets_v1.types.UpdateDatasetMetadataRequest" + }, + { + "name": "dataset", + "type": "google.maps.mapsplatformdatasets_v1.types.Dataset" + }, + { + "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.maps.mapsplatformdatasets_v1.types.Dataset", + "shortName": "update_dataset_metadata" + }, + "description": "Sample for UpdateDatasetMetadata", + "file": "mapsplatformdatasets_v1_generated_maps_platform_datasets_update_dataset_metadata_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "mapsplatformdatasets_v1_generated_MapsPlatformDatasets_UpdateDatasetMetadata_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": "mapsplatformdatasets_v1_generated_maps_platform_datasets_update_dataset_metadata_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient", + "shortName": "MapsPlatformDatasetsClient" + }, + "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient.update_dataset_metadata", + "method": { + "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets.UpdateDatasetMetadata", + "service": { + "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "shortName": "MapsPlatformDatasets" + }, + "shortName": "UpdateDatasetMetadata" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.mapsplatformdatasets_v1.types.UpdateDatasetMetadataRequest" + }, + { + "name": "dataset", + "type": "google.maps.mapsplatformdatasets_v1.types.Dataset" + }, + { + "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.maps.mapsplatformdatasets_v1.types.Dataset", + "shortName": "update_dataset_metadata" + }, + "description": "Sample for UpdateDatasetMetadata", + "file": "mapsplatformdatasets_v1_generated_maps_platform_datasets_update_dataset_metadata_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "mapsplatformdatasets_v1_generated_MapsPlatformDatasets_UpdateDatasetMetadata_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": "mapsplatformdatasets_v1_generated_maps_platform_datasets_update_dataset_metadata_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/scripts/fixup_mapsplatformdatasets_v1_keywords.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/scripts/fixup_mapsplatformdatasets_v1_keywords.py new file mode 100644 index 000000000000..ff0000bc3ad6 --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/scripts/fixup_mapsplatformdatasets_v1_keywords.py @@ -0,0 +1,181 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 mapsplatformdatasetsCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_dataset': ('parent', 'dataset', ), + 'delete_dataset': ('name', ), + 'fetch_dataset_errors': ('dataset', 'page_size', 'page_token', ), + 'get_dataset': ('name', ), + 'list_datasets': ('parent', 'page_size', 'page_token', 'tag', ), + 'update_dataset_metadata': ('dataset', '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=mapsplatformdatasetsCallTransformer(), +): + """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 mapsplatformdatasets 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-maps-mapsplatformdatasets/v1/setup.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/setup.py new file mode 100644 index 000000000000..b2f22f2d7c10 --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/setup.py @@ -0,0 +1,98 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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-maps-mapsplatformdatasets' + + +description = "Google Maps Mapsplatformdatasets API client library" + +version = None + +with open(os.path.join(package_root, 'google/maps/mapsplatformdatasets/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.0dev,!=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.0dev,!=2.24.0,!=2.25.0", + "proto-plus >= 1.22.3, <2.0.0dev", + "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'", + "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", +] +extras = { +} +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-mapsplatformdatasets" + +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-maps-mapsplatformdatasets/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.10.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.11.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.12.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.13.txt b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.13.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.13.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.7.txt new file mode 100644 index 000000000000..fc812592b0ee --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.7.txt @@ -0,0 +1,10 @@ +# 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.0dev", +# 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 diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.8.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.9.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/tests/__init__.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-maps-mapsplatformdatasets/v1/tests/unit/__init__.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-maps-mapsplatformdatasets/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-maps-mapsplatformdatasets/v1/tests/unit/gapic/mapsplatformdatasets_v1/__init__.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/tests/unit/gapic/mapsplatformdatasets_v1/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/tests/unit/gapic/mapsplatformdatasets_v1/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-maps-mapsplatformdatasets/v1/tests/unit/gapic/mapsplatformdatasets_v1/test_maps_platform_datasets.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/tests/unit/gapic/mapsplatformdatasets_v1/test_maps_platform_datasets.py new file mode 100644 index 000000000000..d8d1b199a178 --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/tests/unit/gapic/mapsplatformdatasets_v1/test_maps_platform_datasets.py @@ -0,0 +1,6115 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.mapsplatformdatasets_v1.services.maps_platform_datasets import MapsPlatformDatasetsAsyncClient +from google.maps.mapsplatformdatasets_v1.services.maps_platform_datasets import MapsPlatformDatasetsClient +from google.maps.mapsplatformdatasets_v1.services.maps_platform_datasets import pagers +from google.maps.mapsplatformdatasets_v1.services.maps_platform_datasets import transports +from google.maps.mapsplatformdatasets_v1.types import data_source +from google.maps.mapsplatformdatasets_v1.types import dataset +from google.maps.mapsplatformdatasets_v1.types import dataset as gmm_dataset +from google.maps.mapsplatformdatasets_v1.types import maps_platform_datasets +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.rpc import status_pb2 # type: ignore +import google.auth + + +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 MapsPlatformDatasetsClient._get_default_mtls_endpoint(None) is None + assert MapsPlatformDatasetsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert MapsPlatformDatasetsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert MapsPlatformDatasetsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert MapsPlatformDatasetsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert MapsPlatformDatasetsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert MapsPlatformDatasetsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert MapsPlatformDatasetsClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert MapsPlatformDatasetsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + MapsPlatformDatasetsClient._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 MapsPlatformDatasetsClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert MapsPlatformDatasetsClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert MapsPlatformDatasetsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + MapsPlatformDatasetsClient._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 MapsPlatformDatasetsClient._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 MapsPlatformDatasetsClient._get_client_cert_source(None, False) is None + assert MapsPlatformDatasetsClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert MapsPlatformDatasetsClient._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 MapsPlatformDatasetsClient._get_client_cert_source(None, True) is mock_default_cert_source + assert MapsPlatformDatasetsClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(MapsPlatformDatasetsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(MapsPlatformDatasetsClient)) +@mock.patch.object(MapsPlatformDatasetsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(MapsPlatformDatasetsAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = MapsPlatformDatasetsClient._DEFAULT_UNIVERSE + default_endpoint = MapsPlatformDatasetsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = MapsPlatformDatasetsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert MapsPlatformDatasetsClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert MapsPlatformDatasetsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == MapsPlatformDatasetsClient.DEFAULT_MTLS_ENDPOINT + assert MapsPlatformDatasetsClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert MapsPlatformDatasetsClient._get_api_endpoint(None, None, default_universe, "always") == MapsPlatformDatasetsClient.DEFAULT_MTLS_ENDPOINT + assert MapsPlatformDatasetsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == MapsPlatformDatasetsClient.DEFAULT_MTLS_ENDPOINT + assert MapsPlatformDatasetsClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert MapsPlatformDatasetsClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + MapsPlatformDatasetsClient._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 MapsPlatformDatasetsClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert MapsPlatformDatasetsClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert MapsPlatformDatasetsClient._get_universe_domain(None, None) == MapsPlatformDatasetsClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + MapsPlatformDatasetsClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize("client_class,transport_name", [ + (MapsPlatformDatasetsClient, "grpc"), + (MapsPlatformDatasetsAsyncClient, "grpc_asyncio"), + (MapsPlatformDatasetsClient, "rest"), +]) +def test_maps_platform_datasets_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 == ( + 'mapsplatformdatasets.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://mapsplatformdatasets.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.MapsPlatformDatasetsGrpcTransport, "grpc"), + (transports.MapsPlatformDatasetsGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.MapsPlatformDatasetsRestTransport, "rest"), +]) +def test_maps_platform_datasets_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", [ + (MapsPlatformDatasetsClient, "grpc"), + (MapsPlatformDatasetsAsyncClient, "grpc_asyncio"), + (MapsPlatformDatasetsClient, "rest"), +]) +def test_maps_platform_datasets_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 == ( + 'mapsplatformdatasets.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://mapsplatformdatasets.googleapis.com' + ) + + +def test_maps_platform_datasets_client_get_transport_class(): + transport = MapsPlatformDatasetsClient.get_transport_class() + available_transports = [ + transports.MapsPlatformDatasetsGrpcTransport, + transports.MapsPlatformDatasetsRestTransport, + ] + assert transport in available_transports + + transport = MapsPlatformDatasetsClient.get_transport_class("grpc") + assert transport == transports.MapsPlatformDatasetsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (MapsPlatformDatasetsClient, transports.MapsPlatformDatasetsGrpcTransport, "grpc"), + (MapsPlatformDatasetsAsyncClient, transports.MapsPlatformDatasetsGrpcAsyncIOTransport, "grpc_asyncio"), + (MapsPlatformDatasetsClient, transports.MapsPlatformDatasetsRestTransport, "rest"), +]) +@mock.patch.object(MapsPlatformDatasetsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(MapsPlatformDatasetsClient)) +@mock.patch.object(MapsPlatformDatasetsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(MapsPlatformDatasetsAsyncClient)) +def test_maps_platform_datasets_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(MapsPlatformDatasetsClient, '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(MapsPlatformDatasetsClient, '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", [ + (MapsPlatformDatasetsClient, transports.MapsPlatformDatasetsGrpcTransport, "grpc", "true"), + (MapsPlatformDatasetsAsyncClient, transports.MapsPlatformDatasetsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (MapsPlatformDatasetsClient, transports.MapsPlatformDatasetsGrpcTransport, "grpc", "false"), + (MapsPlatformDatasetsAsyncClient, transports.MapsPlatformDatasetsGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (MapsPlatformDatasetsClient, transports.MapsPlatformDatasetsRestTransport, "rest", "true"), + (MapsPlatformDatasetsClient, transports.MapsPlatformDatasetsRestTransport, "rest", "false"), +]) +@mock.patch.object(MapsPlatformDatasetsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(MapsPlatformDatasetsClient)) +@mock.patch.object(MapsPlatformDatasetsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(MapsPlatformDatasetsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_maps_platform_datasets_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", [ + MapsPlatformDatasetsClient, MapsPlatformDatasetsAsyncClient +]) +@mock.patch.object(MapsPlatformDatasetsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(MapsPlatformDatasetsClient)) +@mock.patch.object(MapsPlatformDatasetsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(MapsPlatformDatasetsAsyncClient)) +def test_maps_platform_datasets_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", [ + MapsPlatformDatasetsClient, MapsPlatformDatasetsAsyncClient +]) +@mock.patch.object(MapsPlatformDatasetsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(MapsPlatformDatasetsClient)) +@mock.patch.object(MapsPlatformDatasetsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(MapsPlatformDatasetsAsyncClient)) +def test_maps_platform_datasets_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = MapsPlatformDatasetsClient._DEFAULT_UNIVERSE + default_endpoint = MapsPlatformDatasetsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = MapsPlatformDatasetsClient._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", [ + (MapsPlatformDatasetsClient, transports.MapsPlatformDatasetsGrpcTransport, "grpc"), + (MapsPlatformDatasetsAsyncClient, transports.MapsPlatformDatasetsGrpcAsyncIOTransport, "grpc_asyncio"), + (MapsPlatformDatasetsClient, transports.MapsPlatformDatasetsRestTransport, "rest"), +]) +def test_maps_platform_datasets_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", [ + (MapsPlatformDatasetsClient, transports.MapsPlatformDatasetsGrpcTransport, "grpc", grpc_helpers), + (MapsPlatformDatasetsAsyncClient, transports.MapsPlatformDatasetsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (MapsPlatformDatasetsClient, transports.MapsPlatformDatasetsRestTransport, "rest", None), +]) +def test_maps_platform_datasets_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_maps_platform_datasets_client_client_options_from_dict(): + with mock.patch('google.maps.mapsplatformdatasets_v1.services.maps_platform_datasets.transports.MapsPlatformDatasetsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = MapsPlatformDatasetsClient( + 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", [ + (MapsPlatformDatasetsClient, transports.MapsPlatformDatasetsGrpcTransport, "grpc", grpc_helpers), + (MapsPlatformDatasetsAsyncClient, transports.MapsPlatformDatasetsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_maps_platform_datasets_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( + "mapsplatformdatasets.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=None, + default_host="mapsplatformdatasets.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + maps_platform_datasets.CreateDatasetRequest, + dict, +]) +def test_create_dataset(request_type, transport: str = 'grpc'): + client = MapsPlatformDatasetsClient( + 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_dataset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gmm_dataset.Dataset( + name='name_value', + display_name='display_name_value', + description='description_value', + version_id='version_id_value', + usage=[gmm_dataset.Usage.USAGE_DATA_DRIVEN_STYLING], + version_description='version_description_value', + ) + response = client.create_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = maps_platform_datasets.CreateDatasetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gmm_dataset.Dataset) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.version_id == 'version_id_value' + assert response.usage == [gmm_dataset.Usage.USAGE_DATA_DRIVEN_STYLING] + assert response.version_description == 'version_description_value' + + +def test_create_dataset_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 = MapsPlatformDatasetsClient( + 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 = maps_platform_datasets.CreateDatasetRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_dataset), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_dataset(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == maps_platform_datasets.CreateDatasetRequest( + parent='parent_value', + ) + +def test_create_dataset_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MapsPlatformDatasetsClient( + 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_dataset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_dataset] = mock_rpc + request = {} + client.create_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_dataset(request) + + # Establish that a new wrapper 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_dataset_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = MapsPlatformDatasetsAsyncClient( + 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_dataset in client._client._transport._wrapped_methods + + # 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_dataset] = mock_rpc + + request = {} + await client.create_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_dataset(request) + + # Establish that a new wrapper 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_dataset_async(transport: str = 'grpc_asyncio', request_type=maps_platform_datasets.CreateDatasetRequest): + client = MapsPlatformDatasetsAsyncClient( + 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_dataset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gmm_dataset.Dataset( + name='name_value', + display_name='display_name_value', + description='description_value', + version_id='version_id_value', + usage=[gmm_dataset.Usage.USAGE_DATA_DRIVEN_STYLING], + version_description='version_description_value', + )) + response = await client.create_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = maps_platform_datasets.CreateDatasetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gmm_dataset.Dataset) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.version_id == 'version_id_value' + assert response.usage == [gmm_dataset.Usage.USAGE_DATA_DRIVEN_STYLING] + assert response.version_description == 'version_description_value' + + +@pytest.mark.asyncio +async def test_create_dataset_async_from_dict(): + await test_create_dataset_async(request_type=dict) + +def test_create_dataset_field_headers(): + client = MapsPlatformDatasetsClient( + 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 = maps_platform_datasets.CreateDatasetRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_dataset), + '__call__') as call: + call.return_value = gmm_dataset.Dataset() + client.create_dataset(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_dataset_field_headers_async(): + client = MapsPlatformDatasetsAsyncClient( + 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 = maps_platform_datasets.CreateDatasetRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_dataset), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gmm_dataset.Dataset()) + await client.create_dataset(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_dataset_flattened(): + client = MapsPlatformDatasetsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_dataset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gmm_dataset.Dataset() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_dataset( + parent='parent_value', + dataset=gmm_dataset.Dataset(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].dataset + mock_val = gmm_dataset.Dataset(name='name_value') + assert arg == mock_val + + +def test_create_dataset_flattened_error(): + client = MapsPlatformDatasetsClient( + 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_dataset( + maps_platform_datasets.CreateDatasetRequest(), + parent='parent_value', + dataset=gmm_dataset.Dataset(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_dataset_flattened_async(): + client = MapsPlatformDatasetsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_dataset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gmm_dataset.Dataset() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gmm_dataset.Dataset()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_dataset( + parent='parent_value', + dataset=gmm_dataset.Dataset(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].dataset + mock_val = gmm_dataset.Dataset(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_dataset_flattened_error_async(): + client = MapsPlatformDatasetsAsyncClient( + 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_dataset( + maps_platform_datasets.CreateDatasetRequest(), + parent='parent_value', + dataset=gmm_dataset.Dataset(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + maps_platform_datasets.UpdateDatasetMetadataRequest, + dict, +]) +def test_update_dataset_metadata(request_type, transport: str = 'grpc'): + client = MapsPlatformDatasetsClient( + 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_dataset_metadata), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gmm_dataset.Dataset( + name='name_value', + display_name='display_name_value', + description='description_value', + version_id='version_id_value', + usage=[gmm_dataset.Usage.USAGE_DATA_DRIVEN_STYLING], + version_description='version_description_value', + ) + response = client.update_dataset_metadata(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = maps_platform_datasets.UpdateDatasetMetadataRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gmm_dataset.Dataset) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.version_id == 'version_id_value' + assert response.usage == [gmm_dataset.Usage.USAGE_DATA_DRIVEN_STYLING] + assert response.version_description == 'version_description_value' + + +def test_update_dataset_metadata_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 = MapsPlatformDatasetsClient( + 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 = maps_platform_datasets.UpdateDatasetMetadataRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_dataset_metadata), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_dataset_metadata(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == maps_platform_datasets.UpdateDatasetMetadataRequest( + ) + +def test_update_dataset_metadata_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MapsPlatformDatasetsClient( + 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_dataset_metadata in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_dataset_metadata] = mock_rpc + request = {} + client.update_dataset_metadata(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_dataset_metadata(request) + + # Establish that a new wrapper 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_dataset_metadata_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = MapsPlatformDatasetsAsyncClient( + 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_dataset_metadata in client._client._transport._wrapped_methods + + # 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_dataset_metadata] = mock_rpc + + request = {} + await client.update_dataset_metadata(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_dataset_metadata(request) + + # Establish that a new wrapper 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_dataset_metadata_async(transport: str = 'grpc_asyncio', request_type=maps_platform_datasets.UpdateDatasetMetadataRequest): + client = MapsPlatformDatasetsAsyncClient( + 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_dataset_metadata), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gmm_dataset.Dataset( + name='name_value', + display_name='display_name_value', + description='description_value', + version_id='version_id_value', + usage=[gmm_dataset.Usage.USAGE_DATA_DRIVEN_STYLING], + version_description='version_description_value', + )) + response = await client.update_dataset_metadata(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = maps_platform_datasets.UpdateDatasetMetadataRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gmm_dataset.Dataset) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.version_id == 'version_id_value' + assert response.usage == [gmm_dataset.Usage.USAGE_DATA_DRIVEN_STYLING] + assert response.version_description == 'version_description_value' + + +@pytest.mark.asyncio +async def test_update_dataset_metadata_async_from_dict(): + await test_update_dataset_metadata_async(request_type=dict) + +def test_update_dataset_metadata_field_headers(): + client = MapsPlatformDatasetsClient( + 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 = maps_platform_datasets.UpdateDatasetMetadataRequest() + + request.dataset.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_dataset_metadata), + '__call__') as call: + call.return_value = gmm_dataset.Dataset() + client.update_dataset_metadata(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', + 'dataset.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_dataset_metadata_field_headers_async(): + client = MapsPlatformDatasetsAsyncClient( + 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 = maps_platform_datasets.UpdateDatasetMetadataRequest() + + request.dataset.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_dataset_metadata), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gmm_dataset.Dataset()) + await client.update_dataset_metadata(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', + 'dataset.name=name_value', + ) in kw['metadata'] + + +def test_update_dataset_metadata_flattened(): + client = MapsPlatformDatasetsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_dataset_metadata), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gmm_dataset.Dataset() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_dataset_metadata( + dataset=gmm_dataset.Dataset(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].dataset + mock_val = gmm_dataset.Dataset(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_dataset_metadata_flattened_error(): + client = MapsPlatformDatasetsClient( + 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_dataset_metadata( + maps_platform_datasets.UpdateDatasetMetadataRequest(), + dataset=gmm_dataset.Dataset(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_dataset_metadata_flattened_async(): + client = MapsPlatformDatasetsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_dataset_metadata), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gmm_dataset.Dataset() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gmm_dataset.Dataset()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_dataset_metadata( + dataset=gmm_dataset.Dataset(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].dataset + mock_val = gmm_dataset.Dataset(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_dataset_metadata_flattened_error_async(): + client = MapsPlatformDatasetsAsyncClient( + 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_dataset_metadata( + maps_platform_datasets.UpdateDatasetMetadataRequest(), + dataset=gmm_dataset.Dataset(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + maps_platform_datasets.GetDatasetRequest, + dict, +]) +def test_get_dataset(request_type, transport: str = 'grpc'): + client = MapsPlatformDatasetsClient( + 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_dataset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = dataset.Dataset( + name='name_value', + display_name='display_name_value', + description='description_value', + version_id='version_id_value', + usage=[dataset.Usage.USAGE_DATA_DRIVEN_STYLING], + version_description='version_description_value', + ) + response = client.get_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = maps_platform_datasets.GetDatasetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, dataset.Dataset) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.version_id == 'version_id_value' + assert response.usage == [dataset.Usage.USAGE_DATA_DRIVEN_STYLING] + assert response.version_description == 'version_description_value' + + +def test_get_dataset_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 = MapsPlatformDatasetsClient( + 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 = maps_platform_datasets.GetDatasetRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_dataset), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_dataset(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == maps_platform_datasets.GetDatasetRequest( + name='name_value', + ) + +def test_get_dataset_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MapsPlatformDatasetsClient( + 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_dataset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_dataset] = mock_rpc + request = {} + client.get_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_dataset(request) + + # Establish that a new wrapper 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_dataset_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = MapsPlatformDatasetsAsyncClient( + 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_dataset in client._client._transport._wrapped_methods + + # 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_dataset] = mock_rpc + + request = {} + await client.get_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_dataset(request) + + # Establish that a new wrapper 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_dataset_async(transport: str = 'grpc_asyncio', request_type=maps_platform_datasets.GetDatasetRequest): + client = MapsPlatformDatasetsAsyncClient( + 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_dataset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(dataset.Dataset( + name='name_value', + display_name='display_name_value', + description='description_value', + version_id='version_id_value', + usage=[dataset.Usage.USAGE_DATA_DRIVEN_STYLING], + version_description='version_description_value', + )) + response = await client.get_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = maps_platform_datasets.GetDatasetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, dataset.Dataset) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.version_id == 'version_id_value' + assert response.usage == [dataset.Usage.USAGE_DATA_DRIVEN_STYLING] + assert response.version_description == 'version_description_value' + + +@pytest.mark.asyncio +async def test_get_dataset_async_from_dict(): + await test_get_dataset_async(request_type=dict) + +def test_get_dataset_field_headers(): + client = MapsPlatformDatasetsClient( + 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 = maps_platform_datasets.GetDatasetRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_dataset), + '__call__') as call: + call.return_value = dataset.Dataset() + client.get_dataset(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_dataset_field_headers_async(): + client = MapsPlatformDatasetsAsyncClient( + 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 = maps_platform_datasets.GetDatasetRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_dataset), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dataset.Dataset()) + await client.get_dataset(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_dataset_flattened(): + client = MapsPlatformDatasetsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_dataset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = dataset.Dataset() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_dataset( + 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_dataset_flattened_error(): + client = MapsPlatformDatasetsClient( + 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_dataset( + maps_platform_datasets.GetDatasetRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_dataset_flattened_async(): + client = MapsPlatformDatasetsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_dataset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = dataset.Dataset() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dataset.Dataset()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_dataset( + 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_dataset_flattened_error_async(): + client = MapsPlatformDatasetsAsyncClient( + 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_dataset( + maps_platform_datasets.GetDatasetRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + maps_platform_datasets.FetchDatasetErrorsRequest, + dict, +]) +def test_fetch_dataset_errors(request_type, transport: str = 'grpc'): + client = MapsPlatformDatasetsClient( + 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.fetch_dataset_errors), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = maps_platform_datasets.FetchDatasetErrorsResponse( + next_page_token='next_page_token_value', + ) + response = client.fetch_dataset_errors(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = maps_platform_datasets.FetchDatasetErrorsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.FetchDatasetErrorsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_fetch_dataset_errors_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 = MapsPlatformDatasetsClient( + 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 = maps_platform_datasets.FetchDatasetErrorsRequest( + dataset='dataset_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.fetch_dataset_errors), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.fetch_dataset_errors(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == maps_platform_datasets.FetchDatasetErrorsRequest( + dataset='dataset_value', + page_token='page_token_value', + ) + +def test_fetch_dataset_errors_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MapsPlatformDatasetsClient( + 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.fetch_dataset_errors in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.fetch_dataset_errors] = mock_rpc + request = {} + client.fetch_dataset_errors(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.fetch_dataset_errors(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_fetch_dataset_errors_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = MapsPlatformDatasetsAsyncClient( + 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.fetch_dataset_errors in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.fetch_dataset_errors] = mock_rpc + + request = {} + await client.fetch_dataset_errors(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.fetch_dataset_errors(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_fetch_dataset_errors_async(transport: str = 'grpc_asyncio', request_type=maps_platform_datasets.FetchDatasetErrorsRequest): + client = MapsPlatformDatasetsAsyncClient( + 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.fetch_dataset_errors), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(maps_platform_datasets.FetchDatasetErrorsResponse( + next_page_token='next_page_token_value', + )) + response = await client.fetch_dataset_errors(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = maps_platform_datasets.FetchDatasetErrorsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.FetchDatasetErrorsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_fetch_dataset_errors_async_from_dict(): + await test_fetch_dataset_errors_async(request_type=dict) + +def test_fetch_dataset_errors_field_headers(): + client = MapsPlatformDatasetsClient( + 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 = maps_platform_datasets.FetchDatasetErrorsRequest() + + request.dataset = 'dataset_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_dataset_errors), + '__call__') as call: + call.return_value = maps_platform_datasets.FetchDatasetErrorsResponse() + client.fetch_dataset_errors(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', + 'dataset=dataset_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_fetch_dataset_errors_field_headers_async(): + client = MapsPlatformDatasetsAsyncClient( + 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 = maps_platform_datasets.FetchDatasetErrorsRequest() + + request.dataset = 'dataset_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_dataset_errors), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(maps_platform_datasets.FetchDatasetErrorsResponse()) + await client.fetch_dataset_errors(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', + 'dataset=dataset_value', + ) in kw['metadata'] + + +def test_fetch_dataset_errors_flattened(): + client = MapsPlatformDatasetsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_dataset_errors), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = maps_platform_datasets.FetchDatasetErrorsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.fetch_dataset_errors( + dataset='dataset_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].dataset + mock_val = 'dataset_value' + assert arg == mock_val + + +def test_fetch_dataset_errors_flattened_error(): + client = MapsPlatformDatasetsClient( + 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.fetch_dataset_errors( + maps_platform_datasets.FetchDatasetErrorsRequest(), + dataset='dataset_value', + ) + +@pytest.mark.asyncio +async def test_fetch_dataset_errors_flattened_async(): + client = MapsPlatformDatasetsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_dataset_errors), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = maps_platform_datasets.FetchDatasetErrorsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(maps_platform_datasets.FetchDatasetErrorsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.fetch_dataset_errors( + dataset='dataset_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].dataset + mock_val = 'dataset_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_fetch_dataset_errors_flattened_error_async(): + client = MapsPlatformDatasetsAsyncClient( + 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.fetch_dataset_errors( + maps_platform_datasets.FetchDatasetErrorsRequest(), + dataset='dataset_value', + ) + + +def test_fetch_dataset_errors_pager(transport_name: str = "grpc"): + client = MapsPlatformDatasetsClient( + 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.fetch_dataset_errors), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + maps_platform_datasets.FetchDatasetErrorsResponse( + errors=[ + status_pb2.Status(), + status_pb2.Status(), + status_pb2.Status(), + ], + next_page_token='abc', + ), + maps_platform_datasets.FetchDatasetErrorsResponse( + errors=[], + next_page_token='def', + ), + maps_platform_datasets.FetchDatasetErrorsResponse( + errors=[ + status_pb2.Status(), + ], + next_page_token='ghi', + ), + maps_platform_datasets.FetchDatasetErrorsResponse( + errors=[ + status_pb2.Status(), + status_pb2.Status(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('dataset', ''), + )), + ) + pager = client.fetch_dataset_errors(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, status_pb2.Status) + for i in results) +def test_fetch_dataset_errors_pages(transport_name: str = "grpc"): + client = MapsPlatformDatasetsClient( + 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.fetch_dataset_errors), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + maps_platform_datasets.FetchDatasetErrorsResponse( + errors=[ + status_pb2.Status(), + status_pb2.Status(), + status_pb2.Status(), + ], + next_page_token='abc', + ), + maps_platform_datasets.FetchDatasetErrorsResponse( + errors=[], + next_page_token='def', + ), + maps_platform_datasets.FetchDatasetErrorsResponse( + errors=[ + status_pb2.Status(), + ], + next_page_token='ghi', + ), + maps_platform_datasets.FetchDatasetErrorsResponse( + errors=[ + status_pb2.Status(), + status_pb2.Status(), + ], + ), + RuntimeError, + ) + pages = list(client.fetch_dataset_errors(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_fetch_dataset_errors_async_pager(): + client = MapsPlatformDatasetsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_dataset_errors), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + maps_platform_datasets.FetchDatasetErrorsResponse( + errors=[ + status_pb2.Status(), + status_pb2.Status(), + status_pb2.Status(), + ], + next_page_token='abc', + ), + maps_platform_datasets.FetchDatasetErrorsResponse( + errors=[], + next_page_token='def', + ), + maps_platform_datasets.FetchDatasetErrorsResponse( + errors=[ + status_pb2.Status(), + ], + next_page_token='ghi', + ), + maps_platform_datasets.FetchDatasetErrorsResponse( + errors=[ + status_pb2.Status(), + status_pb2.Status(), + ], + ), + RuntimeError, + ) + async_pager = await client.fetch_dataset_errors(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, status_pb2.Status) + for i in responses) + + +@pytest.mark.asyncio +async def test_fetch_dataset_errors_async_pages(): + client = MapsPlatformDatasetsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_dataset_errors), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + maps_platform_datasets.FetchDatasetErrorsResponse( + errors=[ + status_pb2.Status(), + status_pb2.Status(), + status_pb2.Status(), + ], + next_page_token='abc', + ), + maps_platform_datasets.FetchDatasetErrorsResponse( + errors=[], + next_page_token='def', + ), + maps_platform_datasets.FetchDatasetErrorsResponse( + errors=[ + status_pb2.Status(), + ], + next_page_token='ghi', + ), + maps_platform_datasets.FetchDatasetErrorsResponse( + errors=[ + status_pb2.Status(), + status_pb2.Status(), + ], + ), + 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.fetch_dataset_errors(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", [ + maps_platform_datasets.ListDatasetsRequest, + dict, +]) +def test_list_datasets(request_type, transport: str = 'grpc'): + client = MapsPlatformDatasetsClient( + 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_datasets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = maps_platform_datasets.ListDatasetsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_datasets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = maps_platform_datasets.ListDatasetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDatasetsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_datasets_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 = MapsPlatformDatasetsClient( + 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 = maps_platform_datasets.ListDatasetsRequest( + parent='parent_value', + page_token='page_token_value', + tag='tag_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_datasets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_datasets(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == maps_platform_datasets.ListDatasetsRequest( + parent='parent_value', + page_token='page_token_value', + tag='tag_value', + ) + +def test_list_datasets_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MapsPlatformDatasetsClient( + 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_datasets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_datasets] = mock_rpc + request = {} + client.list_datasets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_datasets(request) + + # Establish that a new wrapper 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_datasets_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = MapsPlatformDatasetsAsyncClient( + 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_datasets in client._client._transport._wrapped_methods + + # 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_datasets] = mock_rpc + + request = {} + await client.list_datasets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_datasets(request) + + # Establish that a new wrapper 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_datasets_async(transport: str = 'grpc_asyncio', request_type=maps_platform_datasets.ListDatasetsRequest): + client = MapsPlatformDatasetsAsyncClient( + 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_datasets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(maps_platform_datasets.ListDatasetsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_datasets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = maps_platform_datasets.ListDatasetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDatasetsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_datasets_async_from_dict(): + await test_list_datasets_async(request_type=dict) + +def test_list_datasets_field_headers(): + client = MapsPlatformDatasetsClient( + 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 = maps_platform_datasets.ListDatasetsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_datasets), + '__call__') as call: + call.return_value = maps_platform_datasets.ListDatasetsResponse() + client.list_datasets(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_datasets_field_headers_async(): + client = MapsPlatformDatasetsAsyncClient( + 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 = maps_platform_datasets.ListDatasetsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_datasets), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(maps_platform_datasets.ListDatasetsResponse()) + await client.list_datasets(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_datasets_flattened(): + client = MapsPlatformDatasetsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_datasets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = maps_platform_datasets.ListDatasetsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_datasets( + 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_datasets_flattened_error(): + client = MapsPlatformDatasetsClient( + 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_datasets( + maps_platform_datasets.ListDatasetsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_datasets_flattened_async(): + client = MapsPlatformDatasetsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_datasets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = maps_platform_datasets.ListDatasetsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(maps_platform_datasets.ListDatasetsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_datasets( + 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_datasets_flattened_error_async(): + client = MapsPlatformDatasetsAsyncClient( + 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_datasets( + maps_platform_datasets.ListDatasetsRequest(), + parent='parent_value', + ) + + +def test_list_datasets_pager(transport_name: str = "grpc"): + client = MapsPlatformDatasetsClient( + 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_datasets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + maps_platform_datasets.ListDatasetsResponse( + datasets=[ + dataset.Dataset(), + dataset.Dataset(), + dataset.Dataset(), + ], + next_page_token='abc', + ), + maps_platform_datasets.ListDatasetsResponse( + datasets=[], + next_page_token='def', + ), + maps_platform_datasets.ListDatasetsResponse( + datasets=[ + dataset.Dataset(), + ], + next_page_token='ghi', + ), + maps_platform_datasets.ListDatasetsResponse( + datasets=[ + dataset.Dataset(), + dataset.Dataset(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_datasets(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, dataset.Dataset) + for i in results) +def test_list_datasets_pages(transport_name: str = "grpc"): + client = MapsPlatformDatasetsClient( + 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_datasets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + maps_platform_datasets.ListDatasetsResponse( + datasets=[ + dataset.Dataset(), + dataset.Dataset(), + dataset.Dataset(), + ], + next_page_token='abc', + ), + maps_platform_datasets.ListDatasetsResponse( + datasets=[], + next_page_token='def', + ), + maps_platform_datasets.ListDatasetsResponse( + datasets=[ + dataset.Dataset(), + ], + next_page_token='ghi', + ), + maps_platform_datasets.ListDatasetsResponse( + datasets=[ + dataset.Dataset(), + dataset.Dataset(), + ], + ), + RuntimeError, + ) + pages = list(client.list_datasets(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_datasets_async_pager(): + client = MapsPlatformDatasetsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_datasets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + maps_platform_datasets.ListDatasetsResponse( + datasets=[ + dataset.Dataset(), + dataset.Dataset(), + dataset.Dataset(), + ], + next_page_token='abc', + ), + maps_platform_datasets.ListDatasetsResponse( + datasets=[], + next_page_token='def', + ), + maps_platform_datasets.ListDatasetsResponse( + datasets=[ + dataset.Dataset(), + ], + next_page_token='ghi', + ), + maps_platform_datasets.ListDatasetsResponse( + datasets=[ + dataset.Dataset(), + dataset.Dataset(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_datasets(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, dataset.Dataset) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_datasets_async_pages(): + client = MapsPlatformDatasetsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_datasets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + maps_platform_datasets.ListDatasetsResponse( + datasets=[ + dataset.Dataset(), + dataset.Dataset(), + dataset.Dataset(), + ], + next_page_token='abc', + ), + maps_platform_datasets.ListDatasetsResponse( + datasets=[], + next_page_token='def', + ), + maps_platform_datasets.ListDatasetsResponse( + datasets=[ + dataset.Dataset(), + ], + next_page_token='ghi', + ), + maps_platform_datasets.ListDatasetsResponse( + datasets=[ + dataset.Dataset(), + dataset.Dataset(), + ], + ), + 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_datasets(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", [ + maps_platform_datasets.DeleteDatasetRequest, + dict, +]) +def test_delete_dataset(request_type, transport: str = 'grpc'): + client = MapsPlatformDatasetsClient( + 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_dataset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = maps_platform_datasets.DeleteDatasetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_dataset_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 = MapsPlatformDatasetsClient( + 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 = maps_platform_datasets.DeleteDatasetRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_dataset), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_dataset(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == maps_platform_datasets.DeleteDatasetRequest( + name='name_value', + ) + +def test_delete_dataset_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MapsPlatformDatasetsClient( + 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_dataset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_dataset] = mock_rpc + request = {} + client.delete_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_dataset(request) + + # Establish that a new wrapper 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_dataset_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = MapsPlatformDatasetsAsyncClient( + 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_dataset in client._client._transport._wrapped_methods + + # 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_dataset] = mock_rpc + + request = {} + await client.delete_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_dataset(request) + + # Establish that a new wrapper 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_dataset_async(transport: str = 'grpc_asyncio', request_type=maps_platform_datasets.DeleteDatasetRequest): + client = MapsPlatformDatasetsAsyncClient( + 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_dataset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = maps_platform_datasets.DeleteDatasetRequest() + 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_dataset_async_from_dict(): + await test_delete_dataset_async(request_type=dict) + +def test_delete_dataset_field_headers(): + client = MapsPlatformDatasetsClient( + 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 = maps_platform_datasets.DeleteDatasetRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_dataset), + '__call__') as call: + call.return_value = None + client.delete_dataset(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_dataset_field_headers_async(): + client = MapsPlatformDatasetsAsyncClient( + 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 = maps_platform_datasets.DeleteDatasetRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_dataset), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_dataset(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_dataset_flattened(): + client = MapsPlatformDatasetsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_dataset), + '__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_dataset( + 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_dataset_flattened_error(): + client = MapsPlatformDatasetsClient( + 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_dataset( + maps_platform_datasets.DeleteDatasetRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_dataset_flattened_async(): + client = MapsPlatformDatasetsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_dataset), + '__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_dataset( + 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_dataset_flattened_error_async(): + client = MapsPlatformDatasetsAsyncClient( + 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_dataset( + maps_platform_datasets.DeleteDatasetRequest(), + name='name_value', + ) + + +def test_create_dataset_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 = MapsPlatformDatasetsClient( + 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_dataset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_dataset] = mock_rpc + + request = {} + client.create_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_dataset(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_dataset_rest_required_fields(request_type=maps_platform_datasets.CreateDatasetRequest): + transport_class = transports.MapsPlatformDatasetsRestTransport + + 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_dataset._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_dataset._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 = MapsPlatformDatasetsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gmm_dataset.Dataset() + # 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 = gmm_dataset.Dataset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_dataset(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_dataset_rest_unset_required_fields(): + transport = transports.MapsPlatformDatasetsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_dataset._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "dataset", ))) + + +def test_create_dataset_rest_flattened(): + client = MapsPlatformDatasetsClient( + 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 = gmm_dataset.Dataset() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + dataset=gmm_dataset.Dataset(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 = gmm_dataset.Dataset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_dataset(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*}/datasets" % client.transport._host, args[1]) + + +def test_create_dataset_rest_flattened_error(transport: str = 'rest'): + client = MapsPlatformDatasetsClient( + 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_dataset( + maps_platform_datasets.CreateDatasetRequest(), + parent='parent_value', + dataset=gmm_dataset.Dataset(name='name_value'), + ) + + +def test_update_dataset_metadata_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 = MapsPlatformDatasetsClient( + 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_dataset_metadata in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_dataset_metadata] = mock_rpc + + request = {} + client.update_dataset_metadata(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_dataset_metadata(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_dataset_metadata_rest_required_fields(request_type=maps_platform_datasets.UpdateDatasetMetadataRequest): + transport_class = transports.MapsPlatformDatasetsRestTransport + + 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_dataset_metadata._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_dataset_metadata._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 = MapsPlatformDatasetsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gmm_dataset.Dataset() + # 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 = gmm_dataset.Dataset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_dataset_metadata(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_dataset_metadata_rest_unset_required_fields(): + transport = transports.MapsPlatformDatasetsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_dataset_metadata._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("dataset", ))) + + +def test_update_dataset_metadata_rest_flattened(): + client = MapsPlatformDatasetsClient( + 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 = gmm_dataset.Dataset() + + # get arguments that satisfy an http rule for this method + sample_request = {'dataset': {'name': 'projects/sample1/datasets/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + dataset=gmm_dataset.Dataset(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 = gmm_dataset.Dataset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_dataset_metadata(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{dataset.name=projects/*/datasets/*}" % client.transport._host, args[1]) + + +def test_update_dataset_metadata_rest_flattened_error(transport: str = 'rest'): + client = MapsPlatformDatasetsClient( + 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_dataset_metadata( + maps_platform_datasets.UpdateDatasetMetadataRequest(), + dataset=gmm_dataset.Dataset(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_get_dataset_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 = MapsPlatformDatasetsClient( + 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_dataset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_dataset] = mock_rpc + + request = {} + client.get_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_dataset(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_dataset_rest_required_fields(request_type=maps_platform_datasets.GetDatasetRequest): + transport_class = transports.MapsPlatformDatasetsRestTransport + + 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_dataset._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_dataset._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 = MapsPlatformDatasetsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = dataset.Dataset() + # 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 = dataset.Dataset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_dataset(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_dataset_rest_unset_required_fields(): + transport = transports.MapsPlatformDatasetsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_dataset._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_dataset_rest_flattened(): + client = MapsPlatformDatasetsClient( + 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 = dataset.Dataset() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/datasets/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 = dataset.Dataset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_dataset(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/datasets/*}" % client.transport._host, args[1]) + + +def test_get_dataset_rest_flattened_error(transport: str = 'rest'): + client = MapsPlatformDatasetsClient( + 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_dataset( + maps_platform_datasets.GetDatasetRequest(), + name='name_value', + ) + + +def test_fetch_dataset_errors_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 = MapsPlatformDatasetsClient( + 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.fetch_dataset_errors in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.fetch_dataset_errors] = mock_rpc + + request = {} + client.fetch_dataset_errors(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.fetch_dataset_errors(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_fetch_dataset_errors_rest_required_fields(request_type=maps_platform_datasets.FetchDatasetErrorsRequest): + transport_class = transports.MapsPlatformDatasetsRestTransport + + request_init = {} + request_init["dataset"] = "" + request = 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()).fetch_dataset_errors._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["dataset"] = 'dataset_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).fetch_dataset_errors._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 "dataset" in jsonified_request + assert jsonified_request["dataset"] == 'dataset_value' + + client = MapsPlatformDatasetsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = maps_platform_datasets.FetchDatasetErrorsResponse() + # 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 = maps_platform_datasets.FetchDatasetErrorsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.fetch_dataset_errors(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_fetch_dataset_errors_rest_unset_required_fields(): + transport = transports.MapsPlatformDatasetsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.fetch_dataset_errors._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("dataset", ))) + + +def test_fetch_dataset_errors_rest_flattened(): + client = MapsPlatformDatasetsClient( + 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 = maps_platform_datasets.FetchDatasetErrorsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'dataset': 'projects/sample1/datasets/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + dataset='dataset_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 = maps_platform_datasets.FetchDatasetErrorsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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.fetch_dataset_errors(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{dataset=projects/*/datasets/*}:fetchDatasetErrors" % client.transport._host, args[1]) + + +def test_fetch_dataset_errors_rest_flattened_error(transport: str = 'rest'): + client = MapsPlatformDatasetsClient( + 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.fetch_dataset_errors( + maps_platform_datasets.FetchDatasetErrorsRequest(), + dataset='dataset_value', + ) + + +def test_fetch_dataset_errors_rest_pager(transport: str = 'rest'): + client = MapsPlatformDatasetsClient( + 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 = ( + maps_platform_datasets.FetchDatasetErrorsResponse( + errors=[ + status_pb2.Status(), + status_pb2.Status(), + status_pb2.Status(), + ], + next_page_token='abc', + ), + maps_platform_datasets.FetchDatasetErrorsResponse( + errors=[], + next_page_token='def', + ), + maps_platform_datasets.FetchDatasetErrorsResponse( + errors=[ + status_pb2.Status(), + ], + next_page_token='ghi', + ), + maps_platform_datasets.FetchDatasetErrorsResponse( + errors=[ + status_pb2.Status(), + status_pb2.Status(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(maps_platform_datasets.FetchDatasetErrorsResponse.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 = {'dataset': 'projects/sample1/datasets/sample2'} + + pager = client.fetch_dataset_errors(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, status_pb2.Status) + for i in results) + + pages = list(client.fetch_dataset_errors(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_list_datasets_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 = MapsPlatformDatasetsClient( + 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_datasets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_datasets] = mock_rpc + + request = {} + client.list_datasets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_datasets(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_datasets_rest_required_fields(request_type=maps_platform_datasets.ListDatasetsRequest): + transport_class = transports.MapsPlatformDatasetsRestTransport + + 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_datasets._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_datasets._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", "tag", )) + 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 = MapsPlatformDatasetsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = maps_platform_datasets.ListDatasetsResponse() + # 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 = maps_platform_datasets.ListDatasetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_datasets(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_datasets_rest_unset_required_fields(): + transport = transports.MapsPlatformDatasetsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_datasets._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", "tag", )) & set(("parent", ))) + + +def test_list_datasets_rest_flattened(): + client = MapsPlatformDatasetsClient( + 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 = maps_platform_datasets.ListDatasetsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/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 = maps_platform_datasets.ListDatasetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_datasets(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*}/datasets" % client.transport._host, args[1]) + + +def test_list_datasets_rest_flattened_error(transport: str = 'rest'): + client = MapsPlatformDatasetsClient( + 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_datasets( + maps_platform_datasets.ListDatasetsRequest(), + parent='parent_value', + ) + + +def test_list_datasets_rest_pager(transport: str = 'rest'): + client = MapsPlatformDatasetsClient( + 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 = ( + maps_platform_datasets.ListDatasetsResponse( + datasets=[ + dataset.Dataset(), + dataset.Dataset(), + dataset.Dataset(), + ], + next_page_token='abc', + ), + maps_platform_datasets.ListDatasetsResponse( + datasets=[], + next_page_token='def', + ), + maps_platform_datasets.ListDatasetsResponse( + datasets=[ + dataset.Dataset(), + ], + next_page_token='ghi', + ), + maps_platform_datasets.ListDatasetsResponse( + datasets=[ + dataset.Dataset(), + dataset.Dataset(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(maps_platform_datasets.ListDatasetsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1'} + + pager = client.list_datasets(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, dataset.Dataset) + for i in results) + + pages = list(client.list_datasets(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_delete_dataset_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 = MapsPlatformDatasetsClient( + 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_dataset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_dataset] = mock_rpc + + request = {} + client.delete_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_dataset(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_dataset_rest_required_fields(request_type=maps_platform_datasets.DeleteDatasetRequest): + transport_class = transports.MapsPlatformDatasetsRestTransport + + 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_dataset._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_dataset._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 = MapsPlatformDatasetsClient( + 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_dataset(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_dataset_rest_unset_required_fields(): + transport = transports.MapsPlatformDatasetsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_dataset._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_delete_dataset_rest_flattened(): + client = MapsPlatformDatasetsClient( + 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': 'projects/sample1/datasets/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_dataset(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/datasets/*}" % client.transport._host, args[1]) + + +def test_delete_dataset_rest_flattened_error(transport: str = 'rest'): + client = MapsPlatformDatasetsClient( + 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_dataset( + maps_platform_datasets.DeleteDatasetRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.MapsPlatformDatasetsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = MapsPlatformDatasetsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.MapsPlatformDatasetsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = MapsPlatformDatasetsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.MapsPlatformDatasetsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = MapsPlatformDatasetsClient( + 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 = MapsPlatformDatasetsClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.MapsPlatformDatasetsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = MapsPlatformDatasetsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.MapsPlatformDatasetsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = MapsPlatformDatasetsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.MapsPlatformDatasetsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.MapsPlatformDatasetsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.MapsPlatformDatasetsGrpcTransport, + transports.MapsPlatformDatasetsGrpcAsyncIOTransport, + transports.MapsPlatformDatasetsRestTransport, +]) +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 = MapsPlatformDatasetsClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = MapsPlatformDatasetsClient( + 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_create_dataset_empty_call_grpc(): + client = MapsPlatformDatasetsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_dataset), + '__call__') as call: + call.return_value = gmm_dataset.Dataset() + client.create_dataset(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = maps_platform_datasets.CreateDatasetRequest() + + assert args[0] == request_msg + + +# This 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_dataset_metadata_empty_call_grpc(): + client = MapsPlatformDatasetsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_dataset_metadata), + '__call__') as call: + call.return_value = gmm_dataset.Dataset() + client.update_dataset_metadata(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = maps_platform_datasets.UpdateDatasetMetadataRequest() + + assert args[0] == request_msg + + +# This 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_dataset_empty_call_grpc(): + client = MapsPlatformDatasetsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_dataset), + '__call__') as call: + call.return_value = dataset.Dataset() + client.get_dataset(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = maps_platform_datasets.GetDatasetRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_fetch_dataset_errors_empty_call_grpc(): + client = MapsPlatformDatasetsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_dataset_errors), + '__call__') as call: + call.return_value = maps_platform_datasets.FetchDatasetErrorsResponse() + client.fetch_dataset_errors(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = maps_platform_datasets.FetchDatasetErrorsRequest() + + assert args[0] == request_msg + + +# This 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_datasets_empty_call_grpc(): + client = MapsPlatformDatasetsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_datasets), + '__call__') as call: + call.return_value = maps_platform_datasets.ListDatasetsResponse() + client.list_datasets(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = maps_platform_datasets.ListDatasetsRequest() + + assert args[0] == request_msg + + +# This 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_dataset_empty_call_grpc(): + client = MapsPlatformDatasetsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_dataset), + '__call__') as call: + call.return_value = None + client.delete_dataset(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = maps_platform_datasets.DeleteDatasetRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = MapsPlatformDatasetsAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = MapsPlatformDatasetsAsyncClient( + 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_create_dataset_empty_call_grpc_asyncio(): + client = MapsPlatformDatasetsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_dataset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gmm_dataset.Dataset( + name='name_value', + display_name='display_name_value', + description='description_value', + version_id='version_id_value', + usage=[gmm_dataset.Usage.USAGE_DATA_DRIVEN_STYLING], + version_description='version_description_value', + )) + await client.create_dataset(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = maps_platform_datasets.CreateDatasetRequest() + + assert args[0] == request_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_dataset_metadata_empty_call_grpc_asyncio(): + client = MapsPlatformDatasetsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_dataset_metadata), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gmm_dataset.Dataset( + name='name_value', + display_name='display_name_value', + description='description_value', + version_id='version_id_value', + usage=[gmm_dataset.Usage.USAGE_DATA_DRIVEN_STYLING], + version_description='version_description_value', + )) + await client.update_dataset_metadata(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = maps_platform_datasets.UpdateDatasetMetadataRequest() + + assert args[0] == request_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_dataset_empty_call_grpc_asyncio(): + client = MapsPlatformDatasetsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_dataset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dataset.Dataset( + name='name_value', + display_name='display_name_value', + description='description_value', + version_id='version_id_value', + usage=[dataset.Usage.USAGE_DATA_DRIVEN_STYLING], + version_description='version_description_value', + )) + await client.get_dataset(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = maps_platform_datasets.GetDatasetRequest() + + assert args[0] == request_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_fetch_dataset_errors_empty_call_grpc_asyncio(): + client = MapsPlatformDatasetsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_dataset_errors), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(maps_platform_datasets.FetchDatasetErrorsResponse( + next_page_token='next_page_token_value', + )) + await client.fetch_dataset_errors(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = maps_platform_datasets.FetchDatasetErrorsRequest() + + assert args[0] == request_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_datasets_empty_call_grpc_asyncio(): + client = MapsPlatformDatasetsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_datasets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(maps_platform_datasets.ListDatasetsResponse( + next_page_token='next_page_token_value', + )) + await client.list_datasets(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = maps_platform_datasets.ListDatasetsRequest() + + assert args[0] == request_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_dataset_empty_call_grpc_asyncio(): + client = MapsPlatformDatasetsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_dataset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_dataset(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = maps_platform_datasets.DeleteDatasetRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = MapsPlatformDatasetsClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_dataset_rest_bad_request(request_type=maps_platform_datasets.CreateDatasetRequest): + client = MapsPlatformDatasetsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/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_dataset(request) + + +@pytest.mark.parametrize("request_type", [ + maps_platform_datasets.CreateDatasetRequest, + dict, +]) +def test_create_dataset_rest_call_success(request_type): + client = MapsPlatformDatasetsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1'} + request_init["dataset"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'version_id': 'version_id_value', 'usage': [1], 'local_file_source': {'filename': 'filename_value', 'file_format': 1}, 'gcs_source': {'input_uri': 'input_uri_value', 'file_format': 1}, 'status': {'state': 1, 'error_message': 'error_message_value'}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'version_create_time': {}, 'version_description': 'version_description_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 = maps_platform_datasets.CreateDatasetRequest.meta.fields["dataset"] + + 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["dataset"].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["dataset"][field])): + del request_init["dataset"][field][i][subfield] + else: + del request_init["dataset"][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 = gmm_dataset.Dataset( + name='name_value', + display_name='display_name_value', + description='description_value', + version_id='version_id_value', + usage=[gmm_dataset.Usage.USAGE_DATA_DRIVEN_STYLING], + version_description='version_description_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 = gmm_dataset.Dataset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_dataset(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gmm_dataset.Dataset) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.version_id == 'version_id_value' + assert response.usage == [gmm_dataset.Usage.USAGE_DATA_DRIVEN_STYLING] + assert response.version_description == 'version_description_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_dataset_rest_interceptors(null_interceptor): + transport = transports.MapsPlatformDatasetsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.MapsPlatformDatasetsRestInterceptor(), + ) + client = MapsPlatformDatasetsClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.MapsPlatformDatasetsRestInterceptor, "post_create_dataset") as post, \ + mock.patch.object(transports.MapsPlatformDatasetsRestInterceptor, "pre_create_dataset") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = maps_platform_datasets.CreateDatasetRequest.pb(maps_platform_datasets.CreateDatasetRequest()) + 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 = gmm_dataset.Dataset.to_json(gmm_dataset.Dataset()) + req.return_value.content = return_value + + request = maps_platform_datasets.CreateDatasetRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gmm_dataset.Dataset() + + client.create_dataset(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_dataset_metadata_rest_bad_request(request_type=maps_platform_datasets.UpdateDatasetMetadataRequest): + client = MapsPlatformDatasetsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'dataset': {'name': 'projects/sample1/datasets/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_dataset_metadata(request) + + +@pytest.mark.parametrize("request_type", [ + maps_platform_datasets.UpdateDatasetMetadataRequest, + dict, +]) +def test_update_dataset_metadata_rest_call_success(request_type): + client = MapsPlatformDatasetsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'dataset': {'name': 'projects/sample1/datasets/sample2'}} + request_init["dataset"] = {'name': 'projects/sample1/datasets/sample2', 'display_name': 'display_name_value', 'description': 'description_value', 'version_id': 'version_id_value', 'usage': [1], 'local_file_source': {'filename': 'filename_value', 'file_format': 1}, 'gcs_source': {'input_uri': 'input_uri_value', 'file_format': 1}, 'status': {'state': 1, 'error_message': 'error_message_value'}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'version_create_time': {}, 'version_description': 'version_description_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 = maps_platform_datasets.UpdateDatasetMetadataRequest.meta.fields["dataset"] + + 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["dataset"].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["dataset"][field])): + del request_init["dataset"][field][i][subfield] + else: + del request_init["dataset"][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 = gmm_dataset.Dataset( + name='name_value', + display_name='display_name_value', + description='description_value', + version_id='version_id_value', + usage=[gmm_dataset.Usage.USAGE_DATA_DRIVEN_STYLING], + version_description='version_description_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 = gmm_dataset.Dataset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_dataset_metadata(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gmm_dataset.Dataset) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.version_id == 'version_id_value' + assert response.usage == [gmm_dataset.Usage.USAGE_DATA_DRIVEN_STYLING] + assert response.version_description == 'version_description_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_dataset_metadata_rest_interceptors(null_interceptor): + transport = transports.MapsPlatformDatasetsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.MapsPlatformDatasetsRestInterceptor(), + ) + client = MapsPlatformDatasetsClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.MapsPlatformDatasetsRestInterceptor, "post_update_dataset_metadata") as post, \ + mock.patch.object(transports.MapsPlatformDatasetsRestInterceptor, "pre_update_dataset_metadata") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = maps_platform_datasets.UpdateDatasetMetadataRequest.pb(maps_platform_datasets.UpdateDatasetMetadataRequest()) + 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 = gmm_dataset.Dataset.to_json(gmm_dataset.Dataset()) + req.return_value.content = return_value + + request = maps_platform_datasets.UpdateDatasetMetadataRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gmm_dataset.Dataset() + + client.update_dataset_metadata(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_dataset_rest_bad_request(request_type=maps_platform_datasets.GetDatasetRequest): + client = MapsPlatformDatasetsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/datasets/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_dataset(request) + + +@pytest.mark.parametrize("request_type", [ + maps_platform_datasets.GetDatasetRequest, + dict, +]) +def test_get_dataset_rest_call_success(request_type): + client = MapsPlatformDatasetsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/datasets/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 = dataset.Dataset( + name='name_value', + display_name='display_name_value', + description='description_value', + version_id='version_id_value', + usage=[dataset.Usage.USAGE_DATA_DRIVEN_STYLING], + version_description='version_description_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 = dataset.Dataset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_dataset(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, dataset.Dataset) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.version_id == 'version_id_value' + assert response.usage == [dataset.Usage.USAGE_DATA_DRIVEN_STYLING] + assert response.version_description == 'version_description_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_dataset_rest_interceptors(null_interceptor): + transport = transports.MapsPlatformDatasetsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.MapsPlatformDatasetsRestInterceptor(), + ) + client = MapsPlatformDatasetsClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.MapsPlatformDatasetsRestInterceptor, "post_get_dataset") as post, \ + mock.patch.object(transports.MapsPlatformDatasetsRestInterceptor, "pre_get_dataset") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = maps_platform_datasets.GetDatasetRequest.pb(maps_platform_datasets.GetDatasetRequest()) + 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 = dataset.Dataset.to_json(dataset.Dataset()) + req.return_value.content = return_value + + request = maps_platform_datasets.GetDatasetRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = dataset.Dataset() + + client.get_dataset(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_fetch_dataset_errors_rest_bad_request(request_type=maps_platform_datasets.FetchDatasetErrorsRequest): + client = MapsPlatformDatasetsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'dataset': 'projects/sample1/datasets/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.fetch_dataset_errors(request) + + +@pytest.mark.parametrize("request_type", [ + maps_platform_datasets.FetchDatasetErrorsRequest, + dict, +]) +def test_fetch_dataset_errors_rest_call_success(request_type): + client = MapsPlatformDatasetsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'dataset': 'projects/sample1/datasets/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 = maps_platform_datasets.FetchDatasetErrorsResponse( + 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 = maps_platform_datasets.FetchDatasetErrorsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.fetch_dataset_errors(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.FetchDatasetErrorsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_fetch_dataset_errors_rest_interceptors(null_interceptor): + transport = transports.MapsPlatformDatasetsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.MapsPlatformDatasetsRestInterceptor(), + ) + client = MapsPlatformDatasetsClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.MapsPlatformDatasetsRestInterceptor, "post_fetch_dataset_errors") as post, \ + mock.patch.object(transports.MapsPlatformDatasetsRestInterceptor, "pre_fetch_dataset_errors") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = maps_platform_datasets.FetchDatasetErrorsRequest.pb(maps_platform_datasets.FetchDatasetErrorsRequest()) + 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 = maps_platform_datasets.FetchDatasetErrorsResponse.to_json(maps_platform_datasets.FetchDatasetErrorsResponse()) + req.return_value.content = return_value + + request = maps_platform_datasets.FetchDatasetErrorsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = maps_platform_datasets.FetchDatasetErrorsResponse() + + client.fetch_dataset_errors(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_datasets_rest_bad_request(request_type=maps_platform_datasets.ListDatasetsRequest): + client = MapsPlatformDatasetsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/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_datasets(request) + + +@pytest.mark.parametrize("request_type", [ + maps_platform_datasets.ListDatasetsRequest, + dict, +]) +def test_list_datasets_rest_call_success(request_type): + client = MapsPlatformDatasetsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = maps_platform_datasets.ListDatasetsResponse( + 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 = maps_platform_datasets.ListDatasetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_datasets(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDatasetsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_datasets_rest_interceptors(null_interceptor): + transport = transports.MapsPlatformDatasetsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.MapsPlatformDatasetsRestInterceptor(), + ) + client = MapsPlatformDatasetsClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.MapsPlatformDatasetsRestInterceptor, "post_list_datasets") as post, \ + mock.patch.object(transports.MapsPlatformDatasetsRestInterceptor, "pre_list_datasets") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = maps_platform_datasets.ListDatasetsRequest.pb(maps_platform_datasets.ListDatasetsRequest()) + 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 = maps_platform_datasets.ListDatasetsResponse.to_json(maps_platform_datasets.ListDatasetsResponse()) + req.return_value.content = return_value + + request = maps_platform_datasets.ListDatasetsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = maps_platform_datasets.ListDatasetsResponse() + + client.list_datasets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_dataset_rest_bad_request(request_type=maps_platform_datasets.DeleteDatasetRequest): + client = MapsPlatformDatasetsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/datasets/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_dataset(request) + + +@pytest.mark.parametrize("request_type", [ + maps_platform_datasets.DeleteDatasetRequest, + dict, +]) +def test_delete_dataset_rest_call_success(request_type): + client = MapsPlatformDatasetsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/datasets/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_dataset(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_dataset_rest_interceptors(null_interceptor): + transport = transports.MapsPlatformDatasetsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.MapsPlatformDatasetsRestInterceptor(), + ) + client = MapsPlatformDatasetsClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.MapsPlatformDatasetsRestInterceptor, "pre_delete_dataset") as pre: + pre.assert_not_called() + pb_message = maps_platform_datasets.DeleteDatasetRequest.pb(maps_platform_datasets.DeleteDatasetRequest()) + 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 = maps_platform_datasets.DeleteDatasetRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_dataset(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + +def test_initialize_client_w_rest(): + client = MapsPlatformDatasetsClient( + 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_create_dataset_empty_call_rest(): + client = MapsPlatformDatasetsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_dataset), + '__call__') as call: + client.create_dataset(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = maps_platform_datasets.CreateDatasetRequest() + + assert args[0] == request_msg + + +# This 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_dataset_metadata_empty_call_rest(): + client = MapsPlatformDatasetsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_dataset_metadata), + '__call__') as call: + client.update_dataset_metadata(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = maps_platform_datasets.UpdateDatasetMetadataRequest() + + assert args[0] == request_msg + + +# This 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_dataset_empty_call_rest(): + client = MapsPlatformDatasetsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_dataset), + '__call__') as call: + client.get_dataset(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = maps_platform_datasets.GetDatasetRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_fetch_dataset_errors_empty_call_rest(): + client = MapsPlatformDatasetsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_dataset_errors), + '__call__') as call: + client.fetch_dataset_errors(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = maps_platform_datasets.FetchDatasetErrorsRequest() + + assert args[0] == request_msg + + +# This 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_datasets_empty_call_rest(): + client = MapsPlatformDatasetsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_datasets), + '__call__') as call: + client.list_datasets(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = maps_platform_datasets.ListDatasetsRequest() + + assert args[0] == request_msg + + +# This 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_dataset_empty_call_rest(): + client = MapsPlatformDatasetsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_dataset), + '__call__') as call: + client.delete_dataset(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = maps_platform_datasets.DeleteDatasetRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = MapsPlatformDatasetsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.MapsPlatformDatasetsGrpcTransport, + ) + +def test_maps_platform_datasets_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.MapsPlatformDatasetsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_maps_platform_datasets_base_transport(): + # Instantiate the base transport. + with mock.patch('google.maps.mapsplatformdatasets_v1.services.maps_platform_datasets.transports.MapsPlatformDatasetsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.MapsPlatformDatasetsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_dataset', + 'update_dataset_metadata', + 'get_dataset', + 'fetch_dataset_errors', + 'list_datasets', + 'delete_dataset', + ) + 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_maps_platform_datasets_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.maps.mapsplatformdatasets_v1.services.maps_platform_datasets.transports.MapsPlatformDatasetsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.MapsPlatformDatasetsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_maps_platform_datasets_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.maps.mapsplatformdatasets_v1.services.maps_platform_datasets.transports.MapsPlatformDatasetsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.MapsPlatformDatasetsTransport() + adc.assert_called_once() + + +def test_maps_platform_datasets_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) + MapsPlatformDatasetsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.MapsPlatformDatasetsGrpcTransport, + transports.MapsPlatformDatasetsGrpcAsyncIOTransport, + ], +) +def test_maps_platform_datasets_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.MapsPlatformDatasetsGrpcTransport, + transports.MapsPlatformDatasetsGrpcAsyncIOTransport, + transports.MapsPlatformDatasetsRestTransport, + ], +) +def test_maps_platform_datasets_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.MapsPlatformDatasetsGrpcTransport, grpc_helpers), + (transports.MapsPlatformDatasetsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_maps_platform_datasets_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( + "mapsplatformdatasets.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=["1", "2"], + default_host="mapsplatformdatasets.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.MapsPlatformDatasetsGrpcTransport, transports.MapsPlatformDatasetsGrpcAsyncIOTransport]) +def test_maps_platform_datasets_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_maps_platform_datasets_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.MapsPlatformDatasetsRestTransport ( + 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_maps_platform_datasets_host_no_port(transport_name): + client = MapsPlatformDatasetsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='mapsplatformdatasets.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'mapsplatformdatasets.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://mapsplatformdatasets.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_maps_platform_datasets_host_with_port(transport_name): + client = MapsPlatformDatasetsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='mapsplatformdatasets.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'mapsplatformdatasets.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://mapsplatformdatasets.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_maps_platform_datasets_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = MapsPlatformDatasetsClient( + credentials=creds1, + transport=transport_name, + ) + client2 = MapsPlatformDatasetsClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_dataset._session + session2 = client2.transport.create_dataset._session + assert session1 != session2 + session1 = client1.transport.update_dataset_metadata._session + session2 = client2.transport.update_dataset_metadata._session + assert session1 != session2 + session1 = client1.transport.get_dataset._session + session2 = client2.transport.get_dataset._session + assert session1 != session2 + session1 = client1.transport.fetch_dataset_errors._session + session2 = client2.transport.fetch_dataset_errors._session + assert session1 != session2 + session1 = client1.transport.list_datasets._session + session2 = client2.transport.list_datasets._session + assert session1 != session2 + session1 = client1.transport.delete_dataset._session + session2 = client2.transport.delete_dataset._session + assert session1 != session2 +def test_maps_platform_datasets_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.MapsPlatformDatasetsGrpcTransport( + 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_maps_platform_datasets_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.MapsPlatformDatasetsGrpcAsyncIOTransport( + 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.MapsPlatformDatasetsGrpcTransport, transports.MapsPlatformDatasetsGrpcAsyncIOTransport]) +def test_maps_platform_datasets_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.MapsPlatformDatasetsGrpcTransport, transports.MapsPlatformDatasetsGrpcAsyncIOTransport]) +def test_maps_platform_datasets_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_dataset_path(): + project = "squid" + dataset = "clam" + expected = "projects/{project}/datasets/{dataset}".format(project=project, dataset=dataset, ) + actual = MapsPlatformDatasetsClient.dataset_path(project, dataset) + assert expected == actual + + +def test_parse_dataset_path(): + expected = { + "project": "whelk", + "dataset": "octopus", + } + path = MapsPlatformDatasetsClient.dataset_path(**expected) + + # Check that the path construction is reversible. + actual = MapsPlatformDatasetsClient.parse_dataset_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = MapsPlatformDatasetsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = MapsPlatformDatasetsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = MapsPlatformDatasetsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = MapsPlatformDatasetsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = MapsPlatformDatasetsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = MapsPlatformDatasetsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = MapsPlatformDatasetsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = MapsPlatformDatasetsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = MapsPlatformDatasetsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = MapsPlatformDatasetsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = MapsPlatformDatasetsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = MapsPlatformDatasetsClient.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 = MapsPlatformDatasetsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = MapsPlatformDatasetsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = MapsPlatformDatasetsClient.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.MapsPlatformDatasetsTransport, '_prep_wrapped_messages') as prep: + client = MapsPlatformDatasetsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.MapsPlatformDatasetsTransport, '_prep_wrapped_messages') as prep: + transport_class = MapsPlatformDatasetsClient.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 = MapsPlatformDatasetsClient( + 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 = MapsPlatformDatasetsAsyncClient( + 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 = MapsPlatformDatasetsClient( + 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 = MapsPlatformDatasetsClient( + 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", [ + (MapsPlatformDatasetsClient, transports.MapsPlatformDatasetsGrpcTransport), + (MapsPlatformDatasetsAsyncClient, transports.MapsPlatformDatasetsGrpcAsyncIOTransport), +]) +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-maps-places/v1/.coveragerc b/owl-bot-staging/google-maps-places/v1/.coveragerc new file mode 100644 index 000000000000..85cb2db49afb --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/maps/places/__init__.py + google/maps/places/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-maps-places/v1/.flake8 b/owl-bot-staging/google-maps-places/v1/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/google-maps-places/v1/MANIFEST.in b/owl-bot-staging/google-maps-places/v1/MANIFEST.in new file mode 100644 index 000000000000..aca0ee5357fb --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/maps/places *.py +recursive-include google/maps/places_v1 *.py diff --git a/owl-bot-staging/google-maps-places/v1/README.rst b/owl-bot-staging/google-maps-places/v1/README.rst new file mode 100644 index 000000000000..a4719af79336 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Maps Places 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 Maps Places 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 diff --git a/owl-bot-staging/google-maps-places/v1/docs/_static/custom.css b/owl-bot-staging/google-maps-places/v1/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-maps-places/v1/docs/conf.py b/owl-bot-staging/google-maps-places/v1/docs/conf.py new file mode 100644 index 000000000000..db77e54d8b8d --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-maps-places 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("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# 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.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +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-maps-places" +copyright = u"2023, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# 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 = 'en' + +# 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"] + +# 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 Maps Client Libraries for Python", + "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-maps-places-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-maps-places.tex", + u"google-maps-places 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-maps-places", + u"Google Maps Places 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-maps-places", + u"google-maps-places Documentation", + author, + "google-maps-places", + "GAPIC library for Google Maps Places API", + "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": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", 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-maps-places/v1/docs/index.rst b/owl-bot-staging/google-maps-places/v1/docs/index.rst new file mode 100644 index 000000000000..bb4fadc1e6f8 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + places_v1/services_ + places_v1/types_ diff --git a/owl-bot-staging/google-maps-places/v1/docs/places_v1/places.rst b/owl-bot-staging/google-maps-places/v1/docs/places_v1/places.rst new file mode 100644 index 000000000000..cf160d2126f2 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/docs/places_v1/places.rst @@ -0,0 +1,6 @@ +Places +------------------------ + +.. automodule:: google.maps.places_v1.services.places + :members: + :inherited-members: diff --git a/owl-bot-staging/google-maps-places/v1/docs/places_v1/services_.rst b/owl-bot-staging/google-maps-places/v1/docs/places_v1/services_.rst new file mode 100644 index 000000000000..91337ff78a9a --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/docs/places_v1/services_.rst @@ -0,0 +1,6 @@ +Services for Google Maps Places v1 API +====================================== +.. toctree:: + :maxdepth: 2 + + places diff --git a/owl-bot-staging/google-maps-places/v1/docs/places_v1/types_.rst b/owl-bot-staging/google-maps-places/v1/docs/places_v1/types_.rst new file mode 100644 index 000000000000..d634d52d3f87 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/docs/places_v1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Maps Places v1 API +=================================== + +.. automodule:: google.maps.places_v1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places/__init__.py b/owl-bot-staging/google-maps-places/v1/google/maps/places/__init__.py new file mode 100644 index 000000000000..b6e255b38d0f --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places/__init__.py @@ -0,0 +1,83 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.places import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.maps.places_v1.services.places.client import PlacesClient +from google.maps.places_v1.services.places.async_client import PlacesAsyncClient + +from google.maps.places_v1.types.attribution import AuthorAttribution +from google.maps.places_v1.types.content_block import ContentBlock +from google.maps.places_v1.types.contextual_content import ContextualContent +from google.maps.places_v1.types.ev_charging import EVChargeOptions +from google.maps.places_v1.types.ev_charging import EVConnectorType +from google.maps.places_v1.types.fuel_options import FuelOptions +from google.maps.places_v1.types.geometry import Circle +from google.maps.places_v1.types.photo import Photo +from google.maps.places_v1.types.place import Place +from google.maps.places_v1.types.place import PriceLevel +from google.maps.places_v1.types.places_service import AutocompletePlacesRequest +from google.maps.places_v1.types.places_service import AutocompletePlacesResponse +from google.maps.places_v1.types.places_service import GetPhotoMediaRequest +from google.maps.places_v1.types.places_service import GetPlaceRequest +from google.maps.places_v1.types.places_service import PhotoMedia +from google.maps.places_v1.types.places_service import RoutingParameters +from google.maps.places_v1.types.places_service import SearchNearbyRequest +from google.maps.places_v1.types.places_service import SearchNearbyResponse +from google.maps.places_v1.types.places_service import SearchTextRequest +from google.maps.places_v1.types.places_service import SearchTextResponse +from google.maps.places_v1.types.polyline import Polyline +from google.maps.places_v1.types.price_range import PriceRange +from google.maps.places_v1.types.reference import References +from google.maps.places_v1.types.review import Review +from google.maps.places_v1.types.route_modifiers import RouteModifiers +from google.maps.places_v1.types.routing_preference import RoutingPreference +from google.maps.places_v1.types.routing_summary import RoutingSummary +from google.maps.places_v1.types.travel_mode import TravelMode + +__all__ = ('PlacesClient', + 'PlacesAsyncClient', + 'AuthorAttribution', + 'ContentBlock', + 'ContextualContent', + 'EVChargeOptions', + 'EVConnectorType', + 'FuelOptions', + 'Circle', + 'Photo', + 'Place', + 'PriceLevel', + 'AutocompletePlacesRequest', + 'AutocompletePlacesResponse', + 'GetPhotoMediaRequest', + 'GetPlaceRequest', + 'PhotoMedia', + 'RoutingParameters', + 'SearchNearbyRequest', + 'SearchNearbyResponse', + 'SearchTextRequest', + 'SearchTextResponse', + 'Polyline', + 'PriceRange', + 'References', + 'Review', + 'RouteModifiers', + 'RoutingPreference', + 'RoutingSummary', + 'TravelMode', +) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places/gapic_version.py b/owl-bot-staging/google-maps-places/v1/google/maps/places/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-maps-places/v1/google/maps/places/py.typed b/owl-bot-staging/google-maps-places/v1/google/maps/places/py.typed new file mode 100644 index 000000000000..ae821546ded2 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-maps-places package uses inline types. diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/__init__.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/__init__.py new file mode 100644 index 000000000000..42c0424e3800 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/__init__.py @@ -0,0 +1,84 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.places_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.places import PlacesClient +from .services.places import PlacesAsyncClient + +from .types.attribution import AuthorAttribution +from .types.content_block import ContentBlock +from .types.contextual_content import ContextualContent +from .types.ev_charging import EVChargeOptions +from .types.ev_charging import EVConnectorType +from .types.fuel_options import FuelOptions +from .types.geometry import Circle +from .types.photo import Photo +from .types.place import Place +from .types.place import PriceLevel +from .types.places_service import AutocompletePlacesRequest +from .types.places_service import AutocompletePlacesResponse +from .types.places_service import GetPhotoMediaRequest +from .types.places_service import GetPlaceRequest +from .types.places_service import PhotoMedia +from .types.places_service import RoutingParameters +from .types.places_service import SearchNearbyRequest +from .types.places_service import SearchNearbyResponse +from .types.places_service import SearchTextRequest +from .types.places_service import SearchTextResponse +from .types.polyline import Polyline +from .types.price_range import PriceRange +from .types.reference import References +from .types.review import Review +from .types.route_modifiers import RouteModifiers +from .types.routing_preference import RoutingPreference +from .types.routing_summary import RoutingSummary +from .types.travel_mode import TravelMode + +__all__ = ( + 'PlacesAsyncClient', +'AuthorAttribution', +'AutocompletePlacesRequest', +'AutocompletePlacesResponse', +'Circle', +'ContentBlock', +'ContextualContent', +'EVChargeOptions', +'EVConnectorType', +'FuelOptions', +'GetPhotoMediaRequest', +'GetPlaceRequest', +'Photo', +'PhotoMedia', +'Place', +'PlacesClient', +'Polyline', +'PriceLevel', +'PriceRange', +'References', +'Review', +'RouteModifiers', +'RoutingParameters', +'RoutingPreference', +'RoutingSummary', +'SearchNearbyRequest', +'SearchNearbyResponse', +'SearchTextRequest', +'SearchTextResponse', +'TravelMode', +) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/gapic_metadata.json b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/gapic_metadata.json new file mode 100644 index 000000000000..00da5ef96769 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/gapic_metadata.json @@ -0,0 +1,103 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.maps.places_v1", + "protoPackage": "google.maps.places.v1", + "schema": "1.0", + "services": { + "Places": { + "clients": { + "grpc": { + "libraryClient": "PlacesClient", + "rpcs": { + "AutocompletePlaces": { + "methods": [ + "autocomplete_places" + ] + }, + "GetPhotoMedia": { + "methods": [ + "get_photo_media" + ] + }, + "GetPlace": { + "methods": [ + "get_place" + ] + }, + "SearchNearby": { + "methods": [ + "search_nearby" + ] + }, + "SearchText": { + "methods": [ + "search_text" + ] + } + } + }, + "grpc-async": { + "libraryClient": "PlacesAsyncClient", + "rpcs": { + "AutocompletePlaces": { + "methods": [ + "autocomplete_places" + ] + }, + "GetPhotoMedia": { + "methods": [ + "get_photo_media" + ] + }, + "GetPlace": { + "methods": [ + "get_place" + ] + }, + "SearchNearby": { + "methods": [ + "search_nearby" + ] + }, + "SearchText": { + "methods": [ + "search_text" + ] + } + } + }, + "rest": { + "libraryClient": "PlacesClient", + "rpcs": { + "AutocompletePlaces": { + "methods": [ + "autocomplete_places" + ] + }, + "GetPhotoMedia": { + "methods": [ + "get_photo_media" + ] + }, + "GetPlace": { + "methods": [ + "get_place" + ] + }, + "SearchNearby": { + "methods": [ + "search_nearby" + ] + }, + "SearchText": { + "methods": [ + "search_text" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/gapic_version.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-maps-places/v1/google/maps/places_v1/py.typed b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/py.typed new file mode 100644 index 000000000000..ae821546ded2 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-maps-places package uses inline types. diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/__init__.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-maps-places/v1/google/maps/places_v1/services/places/__init__.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/__init__.py new file mode 100644 index 000000000000..3842d6478d3e --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 PlacesClient +from .async_client import PlacesAsyncClient + +__all__ = ( + 'PlacesClient', + 'PlacesAsyncClient', +) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/async_client.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/async_client.py new file mode 100644 index 000000000000..11accc1ee01f --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/async_client.py @@ -0,0 +1,724 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.places_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 + + +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.geo.type.types import viewport +from google.maps.places_v1.types import contextual_content +from google.maps.places_v1.types import ev_charging +from google.maps.places_v1.types import fuel_options +from google.maps.places_v1.types import photo +from google.maps.places_v1.types import place +from google.maps.places_v1.types import places_service +from google.maps.places_v1.types import price_range +from google.maps.places_v1.types import review +from google.maps.places_v1.types import routing_summary +from google.type import latlng_pb2 # type: ignore +from google.type import localized_text_pb2 # type: ignore +from .transports.base import PlacesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import PlacesGrpcAsyncIOTransport +from .client import PlacesClient + +try: + from google.api_core import client_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 PlacesAsyncClient: + """Service definition for the Places API. Note: every request (except + for Autocomplete requests) requires a field mask set outside of the + request proto (``all/*``, is not assumed). The field mask can be set + via the HTTP header ``X-Goog-FieldMask``. See: + https://developers.google.com/maps/documentation/places/web-service/choose-fields + """ + + _client: PlacesClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = PlacesClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = PlacesClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = PlacesClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = PlacesClient._DEFAULT_UNIVERSE + + photo_path = staticmethod(PlacesClient.photo_path) + parse_photo_path = staticmethod(PlacesClient.parse_photo_path) + photo_media_path = staticmethod(PlacesClient.photo_media_path) + parse_photo_media_path = staticmethod(PlacesClient.parse_photo_media_path) + place_path = staticmethod(PlacesClient.place_path) + parse_place_path = staticmethod(PlacesClient.parse_place_path) + review_path = staticmethod(PlacesClient.review_path) + parse_review_path = staticmethod(PlacesClient.parse_review_path) + common_billing_account_path = staticmethod(PlacesClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(PlacesClient.parse_common_billing_account_path) + common_folder_path = staticmethod(PlacesClient.common_folder_path) + parse_common_folder_path = staticmethod(PlacesClient.parse_common_folder_path) + common_organization_path = staticmethod(PlacesClient.common_organization_path) + parse_common_organization_path = staticmethod(PlacesClient.parse_common_organization_path) + common_project_path = staticmethod(PlacesClient.common_project_path) + parse_common_project_path = staticmethod(PlacesClient.parse_common_project_path) + common_location_path = staticmethod(PlacesClient.common_location_path) + parse_common_location_path = staticmethod(PlacesClient.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: + PlacesAsyncClient: The constructed client. + """ + return PlacesClient.from_service_account_info.__func__(PlacesAsyncClient, 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: + PlacesAsyncClient: The constructed client. + """ + return PlacesClient.from_service_account_file.__func__(PlacesAsyncClient, 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 PlacesClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> PlacesTransport: + """Returns the transport used by the client instance. + + Returns: + PlacesTransport: 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 = PlacesClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, PlacesTransport, Callable[..., PlacesTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the places 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,PlacesTransport,Callable[..., PlacesTransport]]]): + 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 PlacesTransport 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 = PlacesClient( + 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.maps.places_v1.PlacesAsyncClient`.", + extra = { + "serviceName": "google.maps.places.v1.Places", + "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.maps.places.v1.Places", + "credentialsType": None, + } + ) + + async def search_nearby(self, + request: Optional[Union[places_service.SearchNearbyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> places_service.SearchNearbyResponse: + r"""Search for places near locations. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import places_v1 + + async def sample_search_nearby(): + # Create a client + client = places_v1.PlacesAsyncClient() + + # Initialize request argument(s) + location_restriction = places_v1.LocationRestriction() + location_restriction.circle.radius = 0.648 + + request = places_v1.SearchNearbyRequest( + location_restriction=location_restriction, + ) + + # Make the request + response = await client.search_nearby(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.places_v1.types.SearchNearbyRequest, dict]]): + The request object. Request proto for Search Nearby. + 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.maps.places_v1.types.SearchNearbyResponse: + Response proto for Search Nearby. + """ + # 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, places_service.SearchNearbyRequest): + request = places_service.SearchNearbyRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.search_nearby] + + # 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 search_text(self, + request: Optional[Union[places_service.SearchTextRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> places_service.SearchTextResponse: + r"""Text query based place search. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import places_v1 + + async def sample_search_text(): + # Create a client + client = places_v1.PlacesAsyncClient() + + # Initialize request argument(s) + request = places_v1.SearchTextRequest( + text_query="text_query_value", + ) + + # Make the request + response = await client.search_text(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.places_v1.types.SearchTextRequest, dict]]): + The request object. Request proto for SearchText. + 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.maps.places_v1.types.SearchTextResponse: + Response proto for SearchText. + """ + # 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, places_service.SearchTextRequest): + request = places_service.SearchTextRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.search_text] + + # 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_photo_media(self, + request: Optional[Union[places_service.GetPhotoMediaRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> places_service.PhotoMedia: + r"""Get a photo media with a photo reference string. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import places_v1 + + async def sample_get_photo_media(): + # Create a client + client = places_v1.PlacesAsyncClient() + + # Initialize request argument(s) + request = places_v1.GetPhotoMediaRequest( + name="name_value", + ) + + # Make the request + response = await client.get_photo_media(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.places_v1.types.GetPhotoMediaRequest, dict]]): + The request object. Request for fetching a photo of a + place using a photo resource name. + name (:class:`str`): + Required. The resource name of a photo media in the + format: + ``places/{place_id}/photos/{photo_reference}/media``. + + The resource name of a photo as returned in a Place + object's ``photos.name`` field comes with the format + ``places/{place_id}/photos/{photo_reference}``. You need + to append ``/media`` at the end of the photo resource to + get the photo media resource name. + + 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.maps.places_v1.types.PhotoMedia: + A photo media from Places 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, places_service.GetPhotoMediaRequest): + request = places_service.GetPhotoMediaRequest(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_photo_media] + + # Certain 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_place(self, + request: Optional[Union[places_service.GetPlaceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> place.Place: + r"""Get the details of a place based on its resource name, which is + a string in the ``places/{place_id}`` format. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import places_v1 + + async def sample_get_place(): + # Create a client + client = places_v1.PlacesAsyncClient() + + # Initialize request argument(s) + request = places_v1.GetPlaceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_place(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.places_v1.types.GetPlaceRequest, dict]]): + The request object. Request for fetching a Place based on its resource name, + which is a string in the ``places/{place_id}`` format. + name (:class:`str`): + Required. The resource name of a place, in the + ``places/{place_id}`` format. + + 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.maps.places_v1.types.Place: + All the information representing a + Place. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, places_service.GetPlaceRequest): + request = places_service.GetPlaceRequest(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_place] + + # Certain 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 autocomplete_places(self, + request: Optional[Union[places_service.AutocompletePlacesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> places_service.AutocompletePlacesResponse: + r"""Returns predictions for the given input. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import places_v1 + + async def sample_autocomplete_places(): + # Create a client + client = places_v1.PlacesAsyncClient() + + # Initialize request argument(s) + request = places_v1.AutocompletePlacesRequest( + input="input_value", + ) + + # Make the request + response = await client.autocomplete_places(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.places_v1.types.AutocompletePlacesRequest, dict]]): + The request object. Request proto for AutocompletePlaces. + 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.maps.places_v1.types.AutocompletePlacesResponse: + Response proto for + AutocompletePlaces. + + """ + # 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, places_service.AutocompletePlacesRequest): + request = places_service.AutocompletePlacesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.autocomplete_places] + + # 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) -> "PlacesAsyncClient": + 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__) + + +__all__ = ( + "PlacesAsyncClient", +) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/client.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/client.py new file mode 100644 index 000000000000..e5eafbb91b62 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/client.py @@ -0,0 +1,1085 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +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.maps.places_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 + +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.geo.type.types import viewport +from google.maps.places_v1.types import contextual_content +from google.maps.places_v1.types import ev_charging +from google.maps.places_v1.types import fuel_options +from google.maps.places_v1.types import photo +from google.maps.places_v1.types import place +from google.maps.places_v1.types import places_service +from google.maps.places_v1.types import price_range +from google.maps.places_v1.types import review +from google.maps.places_v1.types import routing_summary +from google.type import latlng_pb2 # type: ignore +from google.type import localized_text_pb2 # type: ignore +from .transports.base import PlacesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import PlacesGrpcTransport +from .transports.grpc_asyncio import PlacesGrpcAsyncIOTransport +from .transports.rest import PlacesRestTransport + + +class PlacesClientMeta(type): + """Metaclass for the Places 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[PlacesTransport]] + _transport_registry["grpc"] = PlacesGrpcTransport + _transport_registry["grpc_asyncio"] = PlacesGrpcAsyncIOTransport + _transport_registry["rest"] = PlacesRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[PlacesTransport]: + """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 PlacesClient(metaclass=PlacesClientMeta): + """Service definition for the Places API. Note: every request (except + for Autocomplete requests) requires a field mask set outside of the + request proto (``all/*``, is not assumed). The field mask can be set + via the HTTP header ``X-Goog-FieldMask``. See: + https://developers.google.com/maps/documentation/places/web-service/choose-fields + """ + + @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 = "places.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "places.{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: + PlacesClient: 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: + PlacesClient: 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) -> PlacesTransport: + """Returns the transport used by the client instance. + + Returns: + PlacesTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def photo_path(place: str,photo: str,) -> str: + """Returns a fully-qualified photo string.""" + return "places/{place}/photos/{photo}".format(place=place, photo=photo, ) + + @staticmethod + def parse_photo_path(path: str) -> Dict[str,str]: + """Parses a photo path into its component segments.""" + m = re.match(r"^places/(?P.+?)/photos/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def photo_media_path(place_id: str,photo_reference: str,) -> str: + """Returns a fully-qualified photo_media string.""" + return "places/{place_id}/photos/{photo_reference}/media".format(place_id=place_id, photo_reference=photo_reference, ) + + @staticmethod + def parse_photo_media_path(path: str) -> Dict[str,str]: + """Parses a photo_media path into its component segments.""" + m = re.match(r"^places/(?P.+?)/photos/(?P.+?)/media$", path) + return m.groupdict() if m else {} + + @staticmethod + def place_path(place_id: str,) -> str: + """Returns a fully-qualified place string.""" + return "places/{place_id}".format(place_id=place_id, ) + + @staticmethod + def parse_place_path(path: str) -> Dict[str,str]: + """Parses a place path into its component segments.""" + m = re.match(r"^places/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def review_path(place: str,review: str,) -> str: + """Returns a fully-qualified review string.""" + return "places/{place}/reviews/{review}".format(place=place, review=review, ) + + @staticmethod + def parse_review_path(path: str) -> Dict[str,str]: + """Parses a review path into its component segments.""" + m = re.match(r"^places/(?P.+?)/reviews/(?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 = PlacesClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = PlacesClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = PlacesClient._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 = PlacesClient._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 + + @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, PlacesTransport, Callable[..., PlacesTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the places 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,PlacesTransport,Callable[..., PlacesTransport]]]): + 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 PlacesTransport 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 = PlacesClient._read_environment_variables() + self._client_cert_source = PlacesClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = PlacesClient._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, PlacesTransport) + if transport_provided: + # transport is a PlacesTransport 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(PlacesTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + PlacesClient._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[PlacesTransport], Callable[..., PlacesTransport]] = ( + PlacesClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., PlacesTransport], 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.maps.places_v1.PlacesClient`.", + extra = { + "serviceName": "google.maps.places.v1.Places", + "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.maps.places.v1.Places", + "credentialsType": None, + } + ) + + def search_nearby(self, + request: Optional[Union[places_service.SearchNearbyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> places_service.SearchNearbyResponse: + r"""Search for places near locations. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import places_v1 + + def sample_search_nearby(): + # Create a client + client = places_v1.PlacesClient() + + # Initialize request argument(s) + location_restriction = places_v1.LocationRestriction() + location_restriction.circle.radius = 0.648 + + request = places_v1.SearchNearbyRequest( + location_restriction=location_restriction, + ) + + # Make the request + response = client.search_nearby(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.places_v1.types.SearchNearbyRequest, dict]): + The request object. Request proto for Search Nearby. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.maps.places_v1.types.SearchNearbyResponse: + Response proto for Search Nearby. + """ + # 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, places_service.SearchNearbyRequest): + request = places_service.SearchNearbyRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.search_nearby] + + # 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 search_text(self, + request: Optional[Union[places_service.SearchTextRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> places_service.SearchTextResponse: + r"""Text query based place search. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import places_v1 + + def sample_search_text(): + # Create a client + client = places_v1.PlacesClient() + + # Initialize request argument(s) + request = places_v1.SearchTextRequest( + text_query="text_query_value", + ) + + # Make the request + response = client.search_text(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.places_v1.types.SearchTextRequest, dict]): + The request object. Request proto for SearchText. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.maps.places_v1.types.SearchTextResponse: + Response proto for SearchText. + """ + # 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, places_service.SearchTextRequest): + request = places_service.SearchTextRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.search_text] + + # 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_photo_media(self, + request: Optional[Union[places_service.GetPhotoMediaRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> places_service.PhotoMedia: + r"""Get a photo media with a photo reference string. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import places_v1 + + def sample_get_photo_media(): + # Create a client + client = places_v1.PlacesClient() + + # Initialize request argument(s) + request = places_v1.GetPhotoMediaRequest( + name="name_value", + ) + + # Make the request + response = client.get_photo_media(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.places_v1.types.GetPhotoMediaRequest, dict]): + The request object. Request for fetching a photo of a + place using a photo resource name. + name (str): + Required. The resource name of a photo media in the + format: + ``places/{place_id}/photos/{photo_reference}/media``. + + The resource name of a photo as returned in a Place + object's ``photos.name`` field comes with the format + ``places/{place_id}/photos/{photo_reference}``. You need + to append ``/media`` at the end of the photo resource to + get the photo media resource name. + + 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.maps.places_v1.types.PhotoMedia: + A photo media from Places 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, places_service.GetPhotoMediaRequest): + request = places_service.GetPhotoMediaRequest(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_photo_media] + + # Certain 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_place(self, + request: Optional[Union[places_service.GetPlaceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> place.Place: + r"""Get the details of a place based on its resource name, which is + a string in the ``places/{place_id}`` format. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import places_v1 + + def sample_get_place(): + # Create a client + client = places_v1.PlacesClient() + + # Initialize request argument(s) + request = places_v1.GetPlaceRequest( + name="name_value", + ) + + # Make the request + response = client.get_place(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.places_v1.types.GetPlaceRequest, dict]): + The request object. Request for fetching a Place based on its resource name, + which is a string in the ``places/{place_id}`` format. + name (str): + Required. The resource name of a place, in the + ``places/{place_id}`` format. + + 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.maps.places_v1.types.Place: + All the information representing a + Place. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, places_service.GetPlaceRequest): + request = places_service.GetPlaceRequest(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_place] + + # Certain 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 autocomplete_places(self, + request: Optional[Union[places_service.AutocompletePlacesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> places_service.AutocompletePlacesResponse: + r"""Returns predictions for the given input. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import places_v1 + + def sample_autocomplete_places(): + # Create a client + client = places_v1.PlacesClient() + + # Initialize request argument(s) + request = places_v1.AutocompletePlacesRequest( + input="input_value", + ) + + # Make the request + response = client.autocomplete_places(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.places_v1.types.AutocompletePlacesRequest, dict]): + The request object. Request proto for AutocompletePlaces. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.maps.places_v1.types.AutocompletePlacesResponse: + Response proto for + AutocompletePlaces. + + """ + # 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, places_service.AutocompletePlacesRequest): + request = places_service.AutocompletePlacesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.autocomplete_places] + + # 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) -> "PlacesClient": + 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__) + + +__all__ = ( + "PlacesClient", +) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/README.rst b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/README.rst new file mode 100644 index 000000000000..954b9149d54e --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`PlacesTransport` is the ABC for all transports. +- public child `PlacesGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `PlacesGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BasePlacesRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `PlacesRestTransport` 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-maps-places/v1/google/maps/places_v1/services/places/transports/__init__.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/__init__.py new file mode 100644 index 000000000000..6400d3052ce1 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 PlacesTransport +from .grpc import PlacesGrpcTransport +from .grpc_asyncio import PlacesGrpcAsyncIOTransport +from .rest import PlacesRestTransport +from .rest import PlacesRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[PlacesTransport]] +_transport_registry['grpc'] = PlacesGrpcTransport +_transport_registry['grpc_asyncio'] = PlacesGrpcAsyncIOTransport +_transport_registry['rest'] = PlacesRestTransport + +__all__ = ( + 'PlacesTransport', + 'PlacesGrpcTransport', + 'PlacesGrpcAsyncIOTransport', + 'PlacesRestTransport', + 'PlacesRestInterceptor', +) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/base.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/base.py new file mode 100644 index 000000000000..54e226142a89 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/base.py @@ -0,0 +1,210 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.places_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 + +from google.maps.places_v1.types import place +from google.maps.places_v1.types import places_service + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class PlacesTransport(abc.ABC): + """Abstract transport class for Places.""" + + AUTH_SCOPES = ( + ) + + DEFAULT_HOST: str = 'places.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: 'places.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to 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.search_nearby: gapic_v1.method.wrap_method( + self.search_nearby, + default_timeout=None, + client_info=client_info, + ), + self.search_text: gapic_v1.method.wrap_method( + self.search_text, + default_timeout=None, + client_info=client_info, + ), + self.get_photo_media: gapic_v1.method.wrap_method( + self.get_photo_media, + default_timeout=None, + client_info=client_info, + ), + self.get_place: gapic_v1.method.wrap_method( + self.get_place, + default_timeout=None, + client_info=client_info, + ), + self.autocomplete_places: gapic_v1.method.wrap_method( + self.autocomplete_places, + 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 search_nearby(self) -> Callable[ + [places_service.SearchNearbyRequest], + Union[ + places_service.SearchNearbyResponse, + Awaitable[places_service.SearchNearbyResponse] + ]]: + raise NotImplementedError() + + @property + def search_text(self) -> Callable[ + [places_service.SearchTextRequest], + Union[ + places_service.SearchTextResponse, + Awaitable[places_service.SearchTextResponse] + ]]: + raise NotImplementedError() + + @property + def get_photo_media(self) -> Callable[ + [places_service.GetPhotoMediaRequest], + Union[ + places_service.PhotoMedia, + Awaitable[places_service.PhotoMedia] + ]]: + raise NotImplementedError() + + @property + def get_place(self) -> Callable[ + [places_service.GetPlaceRequest], + Union[ + place.Place, + Awaitable[place.Place] + ]]: + raise NotImplementedError() + + @property + def autocomplete_places(self) -> Callable[ + [places_service.AutocompletePlacesRequest], + Union[ + places_service.AutocompletePlacesResponse, + Awaitable[places_service.AutocompletePlacesResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'PlacesTransport', +) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/grpc.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/grpc.py new file mode 100644 index 000000000000..84c3a151b6bf --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/grpc.py @@ -0,0 +1,457 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.places_v1.types import place +from google.maps.places_v1.types import places_service +from .base import PlacesTransport, 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.maps.places.v1.Places", + "rpcName": 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.maps.places.v1.Places", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class PlacesGrpcTransport(PlacesTransport): + """gRPC backend transport for Places. + + Service definition for the Places API. Note: every request (except + for Autocomplete requests) requires a field mask set outside of the + request proto (``all/*``, is not assumed). The field mask can be set + via the HTTP header ``X-Goog-FieldMask``. See: + https://developers.google.com/maps/documentation/places/web-service/choose-fields + + This 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 = 'places.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: 'places.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to 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 = 'places.googleapis.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 search_nearby(self) -> Callable[ + [places_service.SearchNearbyRequest], + places_service.SearchNearbyResponse]: + r"""Return a callable for the search nearby method over gRPC. + + Search for places near locations. + + Returns: + Callable[[~.SearchNearbyRequest], + ~.SearchNearbyResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search_nearby' not in self._stubs: + self._stubs['search_nearby'] = self._logged_channel.unary_unary( + '/google.maps.places.v1.Places/SearchNearby', + request_serializer=places_service.SearchNearbyRequest.serialize, + response_deserializer=places_service.SearchNearbyResponse.deserialize, + ) + return self._stubs['search_nearby'] + + @property + def search_text(self) -> Callable[ + [places_service.SearchTextRequest], + places_service.SearchTextResponse]: + r"""Return a callable for the search text method over gRPC. + + Text query based place search. + + Returns: + Callable[[~.SearchTextRequest], + ~.SearchTextResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search_text' not in self._stubs: + self._stubs['search_text'] = self._logged_channel.unary_unary( + '/google.maps.places.v1.Places/SearchText', + request_serializer=places_service.SearchTextRequest.serialize, + response_deserializer=places_service.SearchTextResponse.deserialize, + ) + return self._stubs['search_text'] + + @property + def get_photo_media(self) -> Callable[ + [places_service.GetPhotoMediaRequest], + places_service.PhotoMedia]: + r"""Return a callable for the get photo media method over gRPC. + + Get a photo media with a photo reference string. + + Returns: + Callable[[~.GetPhotoMediaRequest], + ~.PhotoMedia]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_photo_media' not in self._stubs: + self._stubs['get_photo_media'] = self._logged_channel.unary_unary( + '/google.maps.places.v1.Places/GetPhotoMedia', + request_serializer=places_service.GetPhotoMediaRequest.serialize, + response_deserializer=places_service.PhotoMedia.deserialize, + ) + return self._stubs['get_photo_media'] + + @property + def get_place(self) -> Callable[ + [places_service.GetPlaceRequest], + place.Place]: + r"""Return a callable for the get place method over gRPC. + + Get the details of a place based on its resource name, which is + a string in the ``places/{place_id}`` format. + + Returns: + Callable[[~.GetPlaceRequest], + ~.Place]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_place' not in self._stubs: + self._stubs['get_place'] = self._logged_channel.unary_unary( + '/google.maps.places.v1.Places/GetPlace', + request_serializer=places_service.GetPlaceRequest.serialize, + response_deserializer=place.Place.deserialize, + ) + return self._stubs['get_place'] + + @property + def autocomplete_places(self) -> Callable[ + [places_service.AutocompletePlacesRequest], + places_service.AutocompletePlacesResponse]: + r"""Return a callable for the autocomplete places method over gRPC. + + Returns predictions for the given input. + + Returns: + Callable[[~.AutocompletePlacesRequest], + ~.AutocompletePlacesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'autocomplete_places' not in self._stubs: + self._stubs['autocomplete_places'] = self._logged_channel.unary_unary( + '/google.maps.places.v1.Places/AutocompletePlaces', + request_serializer=places_service.AutocompletePlacesRequest.serialize, + response_deserializer=places_service.AutocompletePlacesResponse.deserialize, + ) + return self._stubs['autocomplete_places'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'PlacesGrpcTransport', +) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/grpc_asyncio.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/grpc_asyncio.py new file mode 100644 index 000000000000..f2be3e2b000e --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/grpc_asyncio.py @@ -0,0 +1,497 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.places_v1.types import place +from google.maps.places_v1.types import places_service +from .base import PlacesTransport, DEFAULT_CLIENT_INFO +from .grpc import PlacesGrpcTransport + +try: + from google.api_core import client_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.maps.places.v1.Places", + "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.maps.places.v1.Places", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class PlacesGrpcAsyncIOTransport(PlacesTransport): + """gRPC AsyncIO backend transport for Places. + + Service definition for the Places API. Note: every request (except + for Autocomplete requests) requires a field mask set outside of the + request proto (``all/*``, is not assumed). The field mask can be set + via the HTTP header ``X-Goog-FieldMask``. See: + https://developers.google.com/maps/documentation/places/web-service/choose-fields + + This 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 = 'places.googleapis.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 = 'places.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: 'places.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to 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 search_nearby(self) -> Callable[ + [places_service.SearchNearbyRequest], + Awaitable[places_service.SearchNearbyResponse]]: + r"""Return a callable for the search nearby method over gRPC. + + Search for places near locations. + + Returns: + Callable[[~.SearchNearbyRequest], + Awaitable[~.SearchNearbyResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search_nearby' not in self._stubs: + self._stubs['search_nearby'] = self._logged_channel.unary_unary( + '/google.maps.places.v1.Places/SearchNearby', + request_serializer=places_service.SearchNearbyRequest.serialize, + response_deserializer=places_service.SearchNearbyResponse.deserialize, + ) + return self._stubs['search_nearby'] + + @property + def search_text(self) -> Callable[ + [places_service.SearchTextRequest], + Awaitable[places_service.SearchTextResponse]]: + r"""Return a callable for the search text method over gRPC. + + Text query based place search. + + Returns: + Callable[[~.SearchTextRequest], + Awaitable[~.SearchTextResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search_text' not in self._stubs: + self._stubs['search_text'] = self._logged_channel.unary_unary( + '/google.maps.places.v1.Places/SearchText', + request_serializer=places_service.SearchTextRequest.serialize, + response_deserializer=places_service.SearchTextResponse.deserialize, + ) + return self._stubs['search_text'] + + @property + def get_photo_media(self) -> Callable[ + [places_service.GetPhotoMediaRequest], + Awaitable[places_service.PhotoMedia]]: + r"""Return a callable for the get photo media method over gRPC. + + Get a photo media with a photo reference string. + + Returns: + Callable[[~.GetPhotoMediaRequest], + Awaitable[~.PhotoMedia]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_photo_media' not in self._stubs: + self._stubs['get_photo_media'] = self._logged_channel.unary_unary( + '/google.maps.places.v1.Places/GetPhotoMedia', + request_serializer=places_service.GetPhotoMediaRequest.serialize, + response_deserializer=places_service.PhotoMedia.deserialize, + ) + return self._stubs['get_photo_media'] + + @property + def get_place(self) -> Callable[ + [places_service.GetPlaceRequest], + Awaitable[place.Place]]: + r"""Return a callable for the get place method over gRPC. + + Get the details of a place based on its resource name, which is + a string in the ``places/{place_id}`` format. + + Returns: + Callable[[~.GetPlaceRequest], + Awaitable[~.Place]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_place' not in self._stubs: + self._stubs['get_place'] = self._logged_channel.unary_unary( + '/google.maps.places.v1.Places/GetPlace', + request_serializer=places_service.GetPlaceRequest.serialize, + response_deserializer=place.Place.deserialize, + ) + return self._stubs['get_place'] + + @property + def autocomplete_places(self) -> Callable[ + [places_service.AutocompletePlacesRequest], + Awaitable[places_service.AutocompletePlacesResponse]]: + r"""Return a callable for the autocomplete places method over gRPC. + + Returns predictions for the given input. + + Returns: + Callable[[~.AutocompletePlacesRequest], + Awaitable[~.AutocompletePlacesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'autocomplete_places' not in self._stubs: + self._stubs['autocomplete_places'] = self._logged_channel.unary_unary( + '/google.maps.places.v1.Places/AutocompletePlaces', + request_serializer=places_service.AutocompletePlacesRequest.serialize, + response_deserializer=places_service.AutocompletePlacesResponse.deserialize, + ) + return self._stubs['autocomplete_places'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.search_nearby: self._wrap_method( + self.search_nearby, + default_timeout=None, + client_info=client_info, + ), + self.search_text: self._wrap_method( + self.search_text, + default_timeout=None, + client_info=client_info, + ), + self.get_photo_media: self._wrap_method( + self.get_photo_media, + default_timeout=None, + client_info=client_info, + ), + self.get_place: self._wrap_method( + self.get_place, + default_timeout=None, + client_info=client_info, + ), + self.autocomplete_places: self._wrap_method( + self.autocomplete_places, + 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__ = ( + 'PlacesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/rest.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/rest.py new file mode 100644 index 000000000000..db320d32a841 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/rest.py @@ -0,0 +1,946 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +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.maps.places_v1.types import place +from google.maps.places_v1.types import places_service + + +from .rest_base import _BasePlacesRestTransport +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}", +) + + +class PlacesRestInterceptor: + """Interceptor for Places. + + 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 PlacesRestTransport. + + .. code-block:: python + class MyCustomPlacesInterceptor(PlacesRestInterceptor): + def pre_autocomplete_places(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_autocomplete_places(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_photo_media(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_photo_media(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_place(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_place(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_search_nearby(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_search_nearby(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_search_text(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_search_text(self, response): + logging.log(f"Received response: {response}") + return response + + transport = PlacesRestTransport(interceptor=MyCustomPlacesInterceptor()) + client = PlacesClient(transport=transport) + + + """ + def pre_autocomplete_places(self, request: places_service.AutocompletePlacesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[places_service.AutocompletePlacesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for autocomplete_places + + Override in a subclass to manipulate the request or metadata + before they are sent to the Places server. + """ + return request, metadata + + def post_autocomplete_places(self, response: places_service.AutocompletePlacesResponse) -> places_service.AutocompletePlacesResponse: + """Post-rpc interceptor for autocomplete_places + + Override in a subclass to manipulate the response + after it is returned by the Places server but before + it is returned to user code. + """ + return response + + def pre_get_photo_media(self, request: places_service.GetPhotoMediaRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[places_service.GetPhotoMediaRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_photo_media + + Override in a subclass to manipulate the request or metadata + before they are sent to the Places server. + """ + return request, metadata + + def post_get_photo_media(self, response: places_service.PhotoMedia) -> places_service.PhotoMedia: + """Post-rpc interceptor for get_photo_media + + Override in a subclass to manipulate the response + after it is returned by the Places server but before + it is returned to user code. + """ + return response + + def pre_get_place(self, request: places_service.GetPlaceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[places_service.GetPlaceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_place + + Override in a subclass to manipulate the request or metadata + before they are sent to the Places server. + """ + return request, metadata + + def post_get_place(self, response: place.Place) -> place.Place: + """Post-rpc interceptor for get_place + + Override in a subclass to manipulate the response + after it is returned by the Places server but before + it is returned to user code. + """ + return response + + def pre_search_nearby(self, request: places_service.SearchNearbyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[places_service.SearchNearbyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for search_nearby + + Override in a subclass to manipulate the request or metadata + before they are sent to the Places server. + """ + return request, metadata + + def post_search_nearby(self, response: places_service.SearchNearbyResponse) -> places_service.SearchNearbyResponse: + """Post-rpc interceptor for search_nearby + + Override in a subclass to manipulate the response + after it is returned by the Places server but before + it is returned to user code. + """ + return response + + def pre_search_text(self, request: places_service.SearchTextRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[places_service.SearchTextRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for search_text + + Override in a subclass to manipulate the request or metadata + before they are sent to the Places server. + """ + return request, metadata + + def post_search_text(self, response: places_service.SearchTextResponse) -> places_service.SearchTextResponse: + """Post-rpc interceptor for search_text + + Override in a subclass to manipulate the response + after it is returned by the Places server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class PlacesRestStub: + _session: AuthorizedSession + _host: str + _interceptor: PlacesRestInterceptor + + +class PlacesRestTransport(_BasePlacesRestTransport): + """REST backend synchronous transport for Places. + + Service definition for the Places API. Note: every request (except + for Autocomplete requests) requires a field mask set outside of the + request proto (``all/*``, is not assumed). The field mask can be set + via the HTTP header ``X-Goog-FieldMask``. See: + https://developers.google.com/maps/documentation/places/web-service/choose-fields + + This 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 = 'places.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[PlacesRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'places.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to 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 PlacesRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _AutocompletePlaces(_BasePlacesRestTransport._BaseAutocompletePlaces, PlacesRestStub): + def __hash__(self): + return hash("PlacesRestTransport.AutocompletePlaces") + + @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: places_service.AutocompletePlacesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> places_service.AutocompletePlacesResponse: + r"""Call the autocomplete places method over HTTP. + + Args: + request (~.places_service.AutocompletePlacesRequest): + The request object. Request proto for AutocompletePlaces. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.places_service.AutocompletePlacesResponse: + Response proto for + AutocompletePlaces. + + """ + + http_options = _BasePlacesRestTransport._BaseAutocompletePlaces._get_http_options() + + request, metadata = self._interceptor.pre_autocomplete_places(request, metadata) + transcoded_request = _BasePlacesRestTransport._BaseAutocompletePlaces._get_transcoded_request(http_options, request) + + body = _BasePlacesRestTransport._BaseAutocompletePlaces._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BasePlacesRestTransport._BaseAutocompletePlaces._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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.maps.places_v1.PlacesClient.AutocompletePlaces", + extra = { + "serviceName": "google.maps.places.v1.Places", + "rpcName": "AutocompletePlaces", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PlacesRestTransport._AutocompletePlaces._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 = places_service.AutocompletePlacesResponse() + pb_resp = places_service.AutocompletePlacesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_autocomplete_places(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = places_service.AutocompletePlacesResponse.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.maps.places_v1.PlacesClient.autocomplete_places", + extra = { + "serviceName": "google.maps.places.v1.Places", + "rpcName": "AutocompletePlaces", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetPhotoMedia(_BasePlacesRestTransport._BaseGetPhotoMedia, PlacesRestStub): + def __hash__(self): + return hash("PlacesRestTransport.GetPhotoMedia") + + @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: places_service.GetPhotoMediaRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> places_service.PhotoMedia: + r"""Call the get photo media method over HTTP. + + Args: + request (~.places_service.GetPhotoMediaRequest): + The request object. Request for fetching a photo of a + place using a photo resource name. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.places_service.PhotoMedia: + A photo media from Places API. + """ + + http_options = _BasePlacesRestTransport._BaseGetPhotoMedia._get_http_options() + + request, metadata = self._interceptor.pre_get_photo_media(request, metadata) + transcoded_request = _BasePlacesRestTransport._BaseGetPhotoMedia._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BasePlacesRestTransport._BaseGetPhotoMedia._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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.maps.places_v1.PlacesClient.GetPhotoMedia", + extra = { + "serviceName": "google.maps.places.v1.Places", + "rpcName": "GetPhotoMedia", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PlacesRestTransport._GetPhotoMedia._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 = places_service.PhotoMedia() + pb_resp = places_service.PhotoMedia.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_photo_media(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = places_service.PhotoMedia.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.maps.places_v1.PlacesClient.get_photo_media", + extra = { + "serviceName": "google.maps.places.v1.Places", + "rpcName": "GetPhotoMedia", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetPlace(_BasePlacesRestTransport._BaseGetPlace, PlacesRestStub): + def __hash__(self): + return hash("PlacesRestTransport.GetPlace") + + @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: places_service.GetPlaceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> place.Place: + r"""Call the get place method over HTTP. + + Args: + request (~.places_service.GetPlaceRequest): + The request object. Request for fetching a Place based on its resource name, + which is a string in the ``places/{place_id}`` format. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.place.Place: + All the information representing a + Place. + + """ + + http_options = _BasePlacesRestTransport._BaseGetPlace._get_http_options() + + request, metadata = self._interceptor.pre_get_place(request, metadata) + transcoded_request = _BasePlacesRestTransport._BaseGetPlace._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BasePlacesRestTransport._BaseGetPlace._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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.maps.places_v1.PlacesClient.GetPlace", + extra = { + "serviceName": "google.maps.places.v1.Places", + "rpcName": "GetPlace", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PlacesRestTransport._GetPlace._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 = place.Place() + pb_resp = place.Place.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_place(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = place.Place.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.maps.places_v1.PlacesClient.get_place", + extra = { + "serviceName": "google.maps.places.v1.Places", + "rpcName": "GetPlace", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _SearchNearby(_BasePlacesRestTransport._BaseSearchNearby, PlacesRestStub): + def __hash__(self): + return hash("PlacesRestTransport.SearchNearby") + + @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: places_service.SearchNearbyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> places_service.SearchNearbyResponse: + r"""Call the search nearby method over HTTP. + + Args: + request (~.places_service.SearchNearbyRequest): + The request object. Request proto for Search Nearby. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.places_service.SearchNearbyResponse: + Response proto for Search Nearby. + """ + + http_options = _BasePlacesRestTransport._BaseSearchNearby._get_http_options() + + request, metadata = self._interceptor.pre_search_nearby(request, metadata) + transcoded_request = _BasePlacesRestTransport._BaseSearchNearby._get_transcoded_request(http_options, request) + + body = _BasePlacesRestTransport._BaseSearchNearby._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BasePlacesRestTransport._BaseSearchNearby._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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.maps.places_v1.PlacesClient.SearchNearby", + extra = { + "serviceName": "google.maps.places.v1.Places", + "rpcName": "SearchNearby", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PlacesRestTransport._SearchNearby._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 = places_service.SearchNearbyResponse() + pb_resp = places_service.SearchNearbyResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_search_nearby(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = places_service.SearchNearbyResponse.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.maps.places_v1.PlacesClient.search_nearby", + extra = { + "serviceName": "google.maps.places.v1.Places", + "rpcName": "SearchNearby", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _SearchText(_BasePlacesRestTransport._BaseSearchText, PlacesRestStub): + def __hash__(self): + return hash("PlacesRestTransport.SearchText") + + @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: places_service.SearchTextRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> places_service.SearchTextResponse: + r"""Call the search text method over HTTP. + + Args: + request (~.places_service.SearchTextRequest): + The request object. Request proto for SearchText. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.places_service.SearchTextResponse: + Response proto for SearchText. + """ + + http_options = _BasePlacesRestTransport._BaseSearchText._get_http_options() + + request, metadata = self._interceptor.pre_search_text(request, metadata) + transcoded_request = _BasePlacesRestTransport._BaseSearchText._get_transcoded_request(http_options, request) + + body = _BasePlacesRestTransport._BaseSearchText._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BasePlacesRestTransport._BaseSearchText._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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.maps.places_v1.PlacesClient.SearchText", + extra = { + "serviceName": "google.maps.places.v1.Places", + "rpcName": "SearchText", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PlacesRestTransport._SearchText._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 = places_service.SearchTextResponse() + pb_resp = places_service.SearchTextResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_search_text(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = places_service.SearchTextResponse.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.maps.places_v1.PlacesClient.search_text", + extra = { + "serviceName": "google.maps.places.v1.Places", + "rpcName": "SearchText", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def autocomplete_places(self) -> Callable[ + [places_service.AutocompletePlacesRequest], + places_service.AutocompletePlacesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._AutocompletePlaces(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_photo_media(self) -> Callable[ + [places_service.GetPhotoMediaRequest], + places_service.PhotoMedia]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetPhotoMedia(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_place(self) -> Callable[ + [places_service.GetPlaceRequest], + place.Place]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetPlace(self._session, self._host, self._interceptor) # type: ignore + + @property + def search_nearby(self) -> Callable[ + [places_service.SearchNearbyRequest], + places_service.SearchNearbyResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SearchNearby(self._session, self._host, self._interceptor) # type: ignore + + @property + def search_text(self) -> Callable[ + [places_service.SearchTextRequest], + places_service.SearchTextResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SearchText(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'PlacesRestTransport', +) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/rest_base.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/rest_base.py new file mode 100644 index 000000000000..b20551b4308c --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/rest_base.py @@ -0,0 +1,307 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 PlacesTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.maps.places_v1.types import place +from google.maps.places_v1.types import places_service + + +class _BasePlacesRestTransport(PlacesTransport): + """Base REST backend transport for Places. + + 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 = 'places.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: 'places.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 _BaseAutocompletePlaces: + 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': '/v1/places:autocomplete', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = places_service.AutocompletePlacesRequest.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(_BasePlacesRestTransport._BaseAutocompletePlaces._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetPhotoMedia: + 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': '/v1/{name=places/*/photos/*/media}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = places_service.GetPhotoMediaRequest.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(_BasePlacesRestTransport._BaseGetPhotoMedia._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetPlace: + 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': '/v1/{name=places/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = places_service.GetPlaceRequest.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(_BasePlacesRestTransport._BaseGetPlace._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseSearchNearby: + 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': '/v1/places:searchNearby', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = places_service.SearchNearbyRequest.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(_BasePlacesRestTransport._BaseSearchNearby._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseSearchText: + 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': '/v1/places:searchText', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = places_service.SearchTextRequest.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(_BasePlacesRestTransport._BaseSearchText._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BasePlacesRestTransport', +) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/__init__.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/__init__.py new file mode 100644 index 000000000000..7795dad518e6 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/__init__.py @@ -0,0 +1,108 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .attribution import ( + AuthorAttribution, +) +from .content_block import ( + ContentBlock, +) +from .contextual_content import ( + ContextualContent, +) +from .ev_charging import ( + EVChargeOptions, + EVConnectorType, +) +from .fuel_options import ( + FuelOptions, +) +from .geometry import ( + Circle, +) +from .photo import ( + Photo, +) +from .place import ( + Place, + PriceLevel, +) +from .places_service import ( + AutocompletePlacesRequest, + AutocompletePlacesResponse, + GetPhotoMediaRequest, + GetPlaceRequest, + PhotoMedia, + RoutingParameters, + SearchNearbyRequest, + SearchNearbyResponse, + SearchTextRequest, + SearchTextResponse, +) +from .polyline import ( + Polyline, +) +from .price_range import ( + PriceRange, +) +from .reference import ( + References, +) +from .review import ( + Review, +) +from .route_modifiers import ( + RouteModifiers, +) +from .routing_preference import ( + RoutingPreference, +) +from .routing_summary import ( + RoutingSummary, +) +from .travel_mode import ( + TravelMode, +) + +__all__ = ( + 'AuthorAttribution', + 'ContentBlock', + 'ContextualContent', + 'EVChargeOptions', + 'EVConnectorType', + 'FuelOptions', + 'Circle', + 'Photo', + 'Place', + 'PriceLevel', + 'AutocompletePlacesRequest', + 'AutocompletePlacesResponse', + 'GetPhotoMediaRequest', + 'GetPlaceRequest', + 'PhotoMedia', + 'RoutingParameters', + 'SearchNearbyRequest', + 'SearchNearbyResponse', + 'SearchTextRequest', + 'SearchTextResponse', + 'Polyline', + 'PriceRange', + 'References', + 'Review', + 'RouteModifiers', + 'RoutingPreference', + 'RoutingSummary', + 'TravelMode', +) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/attribution.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/attribution.py new file mode 100644 index 000000000000..a22226438126 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/attribution.py @@ -0,0 +1,65 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.places.v1', + manifest={ + 'AuthorAttribution', + }, +) + + +class AuthorAttribution(proto.Message): + r"""Information about the author of the UGC data. Used in + [Photo][google.maps.places.v1.Photo], and + [Review][google.maps.places.v1.Review]. + + Attributes: + display_name (str): + Name of the author of the + [Photo][google.maps.places.v1.Photo] or + [Review][google.maps.places.v1.Review]. + uri (str): + URI of the author of the + [Photo][google.maps.places.v1.Photo] or + [Review][google.maps.places.v1.Review]. + photo_uri (str): + Profile photo URI of the author of the + [Photo][google.maps.places.v1.Photo] or + [Review][google.maps.places.v1.Review]. + """ + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + photo_uri: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/content_block.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/content_block.py new file mode 100644 index 000000000000..d5f47e4b7a99 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/content_block.py @@ -0,0 +1,68 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.places_v1.types import reference +from google.type import localized_text_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.places.v1', + manifest={ + 'ContentBlock', + }, +) + + +class ContentBlock(proto.Message): + r"""A block of content that can be served individually. + + Attributes: + topic (str): + The topic of the content, for example + "overview" or "restaurant". + content (google.type.localized_text_pb2.LocalizedText): + Content related to the topic. + references (google.maps.places_v1.types.References): + Experimental: See + https://developers.google.com/maps/documentation/places/web-service/experimental/places-generative + for more details. + + References that are related to this block of + content. + """ + + topic: str = proto.Field( + proto.STRING, + number=1, + ) + content: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=2, + message=localized_text_pb2.LocalizedText, + ) + references: reference.References = proto.Field( + proto.MESSAGE, + number=3, + message=reference.References, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/contextual_content.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/contextual_content.py new file mode 100644 index 000000000000..d1dbb7caa603 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/contextual_content.py @@ -0,0 +1,218 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.places_v1.types import photo +from google.maps.places_v1.types import review as gmp_review + + +__protobuf__ = proto.module( + package='google.maps.places.v1', + manifest={ + 'ContextualContent', + }, +) + + +class ContextualContent(proto.Message): + r"""Experimental: See + https://developers.google.com/maps/documentation/places/web-service/experimental/places-generative + for more details. + + Content that is contextual to the place query. + + Attributes: + reviews (MutableSequence[google.maps.places_v1.types.Review]): + List of reviews about this place, contexual + to the place query. + photos (MutableSequence[google.maps.places_v1.types.Photo]): + Information (including references) about + photos of this place, contexual to the place + query. + justifications (MutableSequence[google.maps.places_v1.types.ContextualContent.Justification]): + Experimental: See + https://developers.google.com/maps/documentation/places/web-service/experimental/places-generative + for more details. + + Justifications for the place. + """ + + class Justification(proto.Message): + r"""Experimental: See + https://developers.google.com/maps/documentation/places/web-service/experimental/places-generative + for more details. + + Justifications for the place. Justifications answers the + question of why a place could interest an end user. + + 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: + review_justification (google.maps.places_v1.types.ContextualContent.Justification.ReviewJustification): + Experimental: See + https://developers.google.com/maps/documentation/places/web-service/experimental/places-generative + for more details. + + This field is a member of `oneof`_ ``justification``. + business_availability_attributes_justification (google.maps.places_v1.types.ContextualContent.Justification.BusinessAvailabilityAttributesJustification): + Experimental: See + https://developers.google.com/maps/documentation/places/web-service/experimental/places-generative + for more details. + + This field is a member of `oneof`_ ``justification``. + """ + + class ReviewJustification(proto.Message): + r"""Experimental: See + https://developers.google.com/maps/documentation/places/web-service/experimental/places-generative + for more details. + + User review justifications. This highlights a section of the + user review that would interest an end user. For instance, if + the search query is "firewood pizza", the review justification + highlights the text relevant to the search query. + + Attributes: + highlighted_text (google.maps.places_v1.types.ContextualContent.Justification.ReviewJustification.HighlightedText): + + review (google.maps.places_v1.types.Review): + The review that the highlighted text is + generated from. + """ + + class HighlightedText(proto.Message): + r"""The text highlighted by the justification. This is a subset + of the review itself. The exact word to highlight is marked by + the HighlightedTextRange. There could be several words in the + text being highlighted. + + Attributes: + text (str): + + highlighted_text_ranges (MutableSequence[google.maps.places_v1.types.ContextualContent.Justification.ReviewJustification.HighlightedText.HighlightedTextRange]): + The list of the ranges of the highlighted + text. + """ + + class HighlightedTextRange(proto.Message): + r"""The range of highlighted text. + + Attributes: + start_index (int): + + end_index (int): + + """ + + start_index: int = proto.Field( + proto.INT32, + number=1, + ) + end_index: int = proto.Field( + proto.INT32, + number=2, + ) + + text: str = proto.Field( + proto.STRING, + number=1, + ) + highlighted_text_ranges: MutableSequence['ContextualContent.Justification.ReviewJustification.HighlightedText.HighlightedTextRange'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='ContextualContent.Justification.ReviewJustification.HighlightedText.HighlightedTextRange', + ) + + highlighted_text: 'ContextualContent.Justification.ReviewJustification.HighlightedText' = proto.Field( + proto.MESSAGE, + number=1, + message='ContextualContent.Justification.ReviewJustification.HighlightedText', + ) + review: gmp_review.Review = proto.Field( + proto.MESSAGE, + number=2, + message=gmp_review.Review, + ) + + class BusinessAvailabilityAttributesJustification(proto.Message): + r"""Experimental: See + https://developers.google.com/maps/documentation/places/web-service/experimental/places-generative + for more details. + BusinessAvailabilityAttributes justifications. This shows some + attributes a business has that could interest an end user. + + Attributes: + takeout (bool): + If a place provides takeout. + delivery (bool): + If a place provides delivery. + dine_in (bool): + If a place provides dine-in. + """ + + takeout: bool = proto.Field( + proto.BOOL, + number=1, + ) + delivery: bool = proto.Field( + proto.BOOL, + number=2, + ) + dine_in: bool = proto.Field( + proto.BOOL, + number=3, + ) + + review_justification: 'ContextualContent.Justification.ReviewJustification' = proto.Field( + proto.MESSAGE, + number=1, + oneof='justification', + message='ContextualContent.Justification.ReviewJustification', + ) + business_availability_attributes_justification: 'ContextualContent.Justification.BusinessAvailabilityAttributesJustification' = proto.Field( + proto.MESSAGE, + number=2, + oneof='justification', + message='ContextualContent.Justification.BusinessAvailabilityAttributesJustification', + ) + + reviews: MutableSequence[gmp_review.Review] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gmp_review.Review, + ) + photos: MutableSequence[photo.Photo] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=photo.Photo, + ) + justifications: MutableSequence[Justification] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=Justification, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/ev_charging.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/ev_charging.py new file mode 100644 index 000000000000..17763d21f927 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/ev_charging.py @@ -0,0 +1,176 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.places.v1', + manifest={ + 'EVConnectorType', + 'EVChargeOptions', + }, +) + + +class EVConnectorType(proto.Enum): + r"""See + http://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=6872107 for + additional information/context on EV charging connector types. + + Values: + EV_CONNECTOR_TYPE_UNSPECIFIED (0): + Unspecified connector. + EV_CONNECTOR_TYPE_OTHER (1): + Other connector types. + EV_CONNECTOR_TYPE_J1772 (2): + J1772 type 1 connector. + EV_CONNECTOR_TYPE_TYPE_2 (3): + IEC 62196 type 2 connector. Often referred to + as MENNEKES. + EV_CONNECTOR_TYPE_CHADEMO (4): + CHAdeMO type connector. + EV_CONNECTOR_TYPE_CCS_COMBO_1 (5): + Combined Charging System (AC and DC). Based + on SAE. Type-1 J-1772 connector + EV_CONNECTOR_TYPE_CCS_COMBO_2 (6): + Combined Charging System (AC and DC). Based + on Type-2 Mennekes connector + EV_CONNECTOR_TYPE_TESLA (7): + The generic TESLA connector. This is NACS in + the North America but can be non-NACS in other + parts of the world (e.g. CCS Combo 2 (CCS2) or + GB/T). This value is less representative of an + actual connector type, and more represents the + ability to charge a Tesla brand vehicle at a + Tesla owned charging station. + EV_CONNECTOR_TYPE_UNSPECIFIED_GB_T (8): + GB/T type corresponds to the GB/T standard in China. This + type covers all GB_T types. + EV_CONNECTOR_TYPE_UNSPECIFIED_WALL_OUTLET (9): + Unspecified wall outlet. + """ + EV_CONNECTOR_TYPE_UNSPECIFIED = 0 + EV_CONNECTOR_TYPE_OTHER = 1 + EV_CONNECTOR_TYPE_J1772 = 2 + EV_CONNECTOR_TYPE_TYPE_2 = 3 + EV_CONNECTOR_TYPE_CHADEMO = 4 + EV_CONNECTOR_TYPE_CCS_COMBO_1 = 5 + EV_CONNECTOR_TYPE_CCS_COMBO_2 = 6 + EV_CONNECTOR_TYPE_TESLA = 7 + EV_CONNECTOR_TYPE_UNSPECIFIED_GB_T = 8 + EV_CONNECTOR_TYPE_UNSPECIFIED_WALL_OUTLET = 9 + + +class EVChargeOptions(proto.Message): + r"""Information about the EV Charge Station hosted in Place. Terminology + follows + https://afdc.energy.gov/fuels/electricity_infrastructure.html One + port could charge one car at a time. One port has one or more + connectors. One station has one or more ports. + + Attributes: + connector_count (int): + Number of connectors at this station. + However, because some ports can have multiple + connectors but only be able to charge one car at + a time (e.g.) the number of connectors may be + greater than the total number of cars which can + charge simultaneously. + connector_aggregation (MutableSequence[google.maps.places_v1.types.EVChargeOptions.ConnectorAggregation]): + A list of EV charging connector aggregations + that contain connectors of the same type and + same charge rate. + """ + + class ConnectorAggregation(proto.Message): + r"""EV charging information grouped by [type, max_charge_rate_kw]. Shows + EV charge aggregation of connectors that have the same type and max + charge rate in kw. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + type_ (google.maps.places_v1.types.EVConnectorType): + The connector type of this aggregation. + max_charge_rate_kw (float): + The static max charging rate in kw of each + connector in the aggregation. + count (int): + Number of connectors in this aggregation. + available_count (int): + Number of connectors in this aggregation that + are currently available. + + This field is a member of `oneof`_ ``_available_count``. + out_of_service_count (int): + Number of connectors in this aggregation that + are currently out of service. + + This field is a member of `oneof`_ ``_out_of_service_count``. + availability_last_update_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when the connector availability + information in this aggregation was last + updated. + """ + + type_: 'EVConnectorType' = proto.Field( + proto.ENUM, + number=1, + enum='EVConnectorType', + ) + max_charge_rate_kw: float = proto.Field( + proto.DOUBLE, + number=2, + ) + count: int = proto.Field( + proto.INT32, + number=3, + ) + available_count: int = proto.Field( + proto.INT32, + number=4, + optional=True, + ) + out_of_service_count: int = proto.Field( + proto.INT32, + number=5, + optional=True, + ) + availability_last_update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + + connector_count: int = proto.Field( + proto.INT32, + number=1, + ) + connector_aggregation: MutableSequence[ConnectorAggregation] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=ConnectorAggregation, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/fuel_options.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/fuel_options.py new file mode 100644 index 000000000000..e1395160614d --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/fuel_options.py @@ -0,0 +1,143 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 timestamp_pb2 # type: ignore +from google.type import money_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.places.v1', + manifest={ + 'FuelOptions', + }, +) + + +class FuelOptions(proto.Message): + r"""The most recent information about fuel options in a gas + station. This information is updated regularly. + + Attributes: + fuel_prices (MutableSequence[google.maps.places_v1.types.FuelOptions.FuelPrice]): + The last known fuel price for each type of + fuel this station has. There is one entry per + fuel type this station has. Order is not + important. + """ + + class FuelPrice(proto.Message): + r"""Fuel price information for a given type. + + Attributes: + type_ (google.maps.places_v1.types.FuelOptions.FuelPrice.FuelType): + The type of fuel. + price (google.type.money_pb2.Money): + The price of the fuel. + update_time (google.protobuf.timestamp_pb2.Timestamp): + The time the fuel price was last updated. + """ + class FuelType(proto.Enum): + r"""Types of fuel. + + Values: + FUEL_TYPE_UNSPECIFIED (0): + Unspecified fuel type. + DIESEL (1): + Diesel fuel. + REGULAR_UNLEADED (2): + Regular unleaded. + MIDGRADE (3): + Midgrade. + PREMIUM (4): + Premium. + SP91 (5): + SP 91. + SP91_E10 (6): + SP 91 E10. + SP92 (7): + SP 92. + SP95 (8): + SP 95. + SP95_E10 (9): + SP95 E10. + SP98 (10): + SP 98. + SP99 (11): + SP 99. + SP100 (12): + SP 100. + LPG (13): + LPG. + E80 (14): + E 80. + E85 (15): + E 85. + METHANE (16): + Methane. + BIO_DIESEL (17): + Bio-diesel. + TRUCK_DIESEL (18): + Truck diesel. + """ + FUEL_TYPE_UNSPECIFIED = 0 + DIESEL = 1 + REGULAR_UNLEADED = 2 + MIDGRADE = 3 + PREMIUM = 4 + SP91 = 5 + SP91_E10 = 6 + SP92 = 7 + SP95 = 8 + SP95_E10 = 9 + SP98 = 10 + SP99 = 11 + SP100 = 12 + LPG = 13 + E80 = 14 + E85 = 15 + METHANE = 16 + BIO_DIESEL = 17 + TRUCK_DIESEL = 18 + + type_: 'FuelOptions.FuelPrice.FuelType' = proto.Field( + proto.ENUM, + number=1, + enum='FuelOptions.FuelPrice.FuelType', + ) + price: money_pb2.Money = proto.Field( + proto.MESSAGE, + number=2, + message=money_pb2.Money, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + fuel_prices: MutableSequence[FuelPrice] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=FuelPrice, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/geometry.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/geometry.py new file mode 100644 index 000000000000..b3d1cf8c1eb3 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/geometry.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 latlng_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.places.v1', + manifest={ + 'Circle', + }, +) + + +class Circle(proto.Message): + r"""Circle with a LatLng as center and radius. + + Attributes: + center (google.type.latlng_pb2.LatLng): + Required. Center latitude and longitude. + + The range of latitude must be within [-90.0, 90.0]. The + range of the longitude must be within [-180.0, 180.0]. + radius (float): + Required. Radius measured in meters. The radius must be + within [0.0, 50000.0]. + """ + + center: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=1, + message=latlng_pb2.LatLng, + ) + radius: float = proto.Field( + proto.DOUBLE, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/photo.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/photo.py new file mode 100644 index 000000000000..45bc33ecb53e --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/photo.py @@ -0,0 +1,69 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.places_v1.types import attribution + + +__protobuf__ = proto.module( + package='google.maps.places.v1', + manifest={ + 'Photo', + }, +) + + +class Photo(proto.Message): + r"""Information about a photo of a place. + + Attributes: + name (str): + Identifier. A reference representing this place photo which + may be used to look up this place photo again (also called + the API "resource" name: + ``places/{place_id}/photos/{photo}``). + width_px (int): + The maximum available width, in pixels. + height_px (int): + The maximum available height, in pixels. + author_attributions (MutableSequence[google.maps.places_v1.types.AuthorAttribution]): + This photo's authors. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + width_px: int = proto.Field( + proto.INT32, + number=2, + ) + height_px: int = proto.Field( + proto.INT32, + number=3, + ) + author_attributions: MutableSequence[attribution.AuthorAttribution] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=attribution.AuthorAttribution, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/place.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/place.py new file mode 100644 index 000000000000..34e44adedb46 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/place.py @@ -0,0 +1,1286 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.geo.type.types import viewport as ggt_viewport +from google.maps.places_v1.types import content_block +from google.maps.places_v1.types import ev_charging +from google.maps.places_v1.types import fuel_options as gmp_fuel_options +from google.maps.places_v1.types import photo +from google.maps.places_v1.types import price_range as gmp_price_range +from google.maps.places_v1.types import reference +from google.maps.places_v1.types import review +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore +from google.type import localized_text_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.places.v1', + manifest={ + 'PriceLevel', + 'Place', + }, +) + + +class PriceLevel(proto.Enum): + r"""Price level of the place. + + Values: + PRICE_LEVEL_UNSPECIFIED (0): + Place price level is unspecified or unknown. + PRICE_LEVEL_FREE (1): + Place provides free services. + PRICE_LEVEL_INEXPENSIVE (2): + Place provides inexpensive services. + PRICE_LEVEL_MODERATE (3): + Place provides moderately priced services. + PRICE_LEVEL_EXPENSIVE (4): + Place provides expensive services. + PRICE_LEVEL_VERY_EXPENSIVE (5): + Place provides very expensive services. + """ + PRICE_LEVEL_UNSPECIFIED = 0 + PRICE_LEVEL_FREE = 1 + PRICE_LEVEL_INEXPENSIVE = 2 + PRICE_LEVEL_MODERATE = 3 + PRICE_LEVEL_EXPENSIVE = 4 + PRICE_LEVEL_VERY_EXPENSIVE = 5 + + +class Place(proto.Message): + r"""All the information representing a Place. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + This Place's resource name, in ``places/{place_id}`` format. + Can be used to look up the Place. + id (str): + The unique identifier of a place. + display_name (google.type.localized_text_pb2.LocalizedText): + The localized name of the place, suitable as + a short human-readable description. For example, + "Google Sydney", "Starbucks", "Pyrmont", etc. + types (MutableSequence[str]): + A set of type tags for this result. For + example, "political" and "locality". For the + complete list of possible values, see Table A + and Table B at + https://developers.google.com/maps/documentation/places/web-service/place-types + primary_type (str): + The primary type of the given result. This + type must one of the Places API supported types. + For example, "restaurant", "cafe", "airport", + etc. A place can only have a single primary + type. For the complete list of possible values, + see Table A and Table B at + https://developers.google.com/maps/documentation/places/web-service/place-types + primary_type_display_name (google.type.localized_text_pb2.LocalizedText): + The display name of the primary type, + localized to the request language if applicable. + For the complete list of possible values, see + Table A and Table B at + https://developers.google.com/maps/documentation/places/web-service/place-types + national_phone_number (str): + A human-readable phone number for the place, + in national format. + international_phone_number (str): + A human-readable phone number for the place, + in international format. + formatted_address (str): + A full, human-readable address for this + place. + short_formatted_address (str): + A short, human-readable address for this + place. + address_components (MutableSequence[google.maps.places_v1.types.Place.AddressComponent]): + Repeated components for each locality level. Note the + following facts about the address_components[] array: + + - The array of address components may contain more + components than the formatted_address. + - The array does not necessarily include all the political + entities that contain an address, apart from those + included in the formatted_address. To retrieve all the + political entities that contain a specific address, you + should use reverse geocoding, passing the + latitude/longitude of the address as a parameter to the + request. + - The format of the response is not guaranteed to remain + the same between requests. In particular, the number of + address_components varies based on the address requested + and can change over time for the same address. A + component can change position in the array. The type of + the component can change. A particular component may be + missing in a later response. + plus_code (google.maps.places_v1.types.Place.PlusCode): + Plus code of the place location lat/long. + location (google.type.latlng_pb2.LatLng): + The position of this place. + viewport (google.geo.type.types.Viewport): + A viewport suitable for displaying the place + on an average-sized map. This viewport should + not be used as the physical boundary or the + service area of the business. + rating (float): + A rating between 1.0 and 5.0, based on user + reviews of this place. + google_maps_uri (str): + A URL providing more information about this + place. + website_uri (str): + The authoritative website for this place, + e.g. a business' homepage. Note that for places + that are part of a chain (e.g. an IKEA store), + this will usually be the website for the + individual store, not the overall chain. + reviews (MutableSequence[google.maps.places_v1.types.Review]): + List of reviews about this place, sorted by + relevance. A maximum of 5 reviews can be + returned. + regular_opening_hours (google.maps.places_v1.types.Place.OpeningHours): + The regular hours of operation. + utc_offset_minutes (int): + Number of minutes this place's timezone is + currently offset from UTC. This is expressed in + minutes to support timezones that are offset by + fractions of an hour, e.g. X hours and 15 + minutes. + + This field is a member of `oneof`_ ``_utc_offset_minutes``. + photos (MutableSequence[google.maps.places_v1.types.Photo]): + Information (including references) about + photos of this place. A maximum of 10 photos can + be returned. + adr_format_address (str): + The place's address in adr microformat: + http://microformats.org/wiki/adr. + business_status (google.maps.places_v1.types.Place.BusinessStatus): + + price_level (google.maps.places_v1.types.PriceLevel): + Price level of the place. + attributions (MutableSequence[google.maps.places_v1.types.Place.Attribution]): + A set of data provider that must be shown + with this result. + user_rating_count (int): + The total number of reviews (with or without + text) for this place. + + This field is a member of `oneof`_ ``_user_rating_count``. + icon_mask_base_uri (str): + A truncated URL to an icon mask. User can + access different icon type by appending type + suffix to the end (eg, ".svg" or ".png"). + icon_background_color (str): + Background color for icon_mask in hex format, e.g. #909CE1. + takeout (bool): + Specifies if the business supports takeout. + + This field is a member of `oneof`_ ``_takeout``. + delivery (bool): + Specifies if the business supports delivery. + + This field is a member of `oneof`_ ``_delivery``. + dine_in (bool): + Specifies if the business supports indoor or + outdoor seating options. + + This field is a member of `oneof`_ ``_dine_in``. + curbside_pickup (bool): + Specifies if the business supports curbside + pickup. + + This field is a member of `oneof`_ ``_curbside_pickup``. + reservable (bool): + Specifies if the place supports reservations. + + This field is a member of `oneof`_ ``_reservable``. + serves_breakfast (bool): + Specifies if the place serves breakfast. + + This field is a member of `oneof`_ ``_serves_breakfast``. + serves_lunch (bool): + Specifies if the place serves lunch. + + This field is a member of `oneof`_ ``_serves_lunch``. + serves_dinner (bool): + Specifies if the place serves dinner. + + This field is a member of `oneof`_ ``_serves_dinner``. + serves_beer (bool): + Specifies if the place serves beer. + + This field is a member of `oneof`_ ``_serves_beer``. + serves_wine (bool): + Specifies if the place serves wine. + + This field is a member of `oneof`_ ``_serves_wine``. + serves_brunch (bool): + Specifies if the place serves brunch. + + This field is a member of `oneof`_ ``_serves_brunch``. + serves_vegetarian_food (bool): + Specifies if the place serves vegetarian + food. + + This field is a member of `oneof`_ ``_serves_vegetarian_food``. + current_opening_hours (google.maps.places_v1.types.Place.OpeningHours): + The hours of operation for the next seven days (including + today). The time period starts at midnight on the date of + the request and ends at 11:59 pm six days later. This field + includes the special_days subfield of all hours, set for + dates that have exceptional hours. + current_secondary_opening_hours (MutableSequence[google.maps.places_v1.types.Place.OpeningHours]): + Contains an array of entries for the next seven days + including information about secondary hours of a business. + Secondary hours are different from a business's main hours. + For example, a restaurant can specify drive through hours or + delivery hours as its secondary hours. This field populates + the type subfield, which draws from a predefined list of + opening hours types (such as DRIVE_THROUGH, PICKUP, or + TAKEOUT) based on the types of the place. This field + includes the special_days subfield of all hours, set for + dates that have exceptional hours. + regular_secondary_opening_hours (MutableSequence[google.maps.places_v1.types.Place.OpeningHours]): + Contains an array of entries for information about regular + secondary hours of a business. Secondary hours are different + from a business's main hours. For example, a restaurant can + specify drive through hours or delivery hours as its + secondary hours. This field populates the type subfield, + which draws from a predefined list of opening hours types + (such as DRIVE_THROUGH, PICKUP, or TAKEOUT) based on the + types of the place. + editorial_summary (google.type.localized_text_pb2.LocalizedText): + Contains a summary of the place. A summary is + comprised of a textual overview, and also + includes the language code for these if + applicable. Summary text must be presented as-is + and can not be modified or altered. + outdoor_seating (bool): + Place provides outdoor seating. + + This field is a member of `oneof`_ ``_outdoor_seating``. + live_music (bool): + Place provides live music. + + This field is a member of `oneof`_ ``_live_music``. + menu_for_children (bool): + Place has a children's menu. + + This field is a member of `oneof`_ ``_menu_for_children``. + serves_cocktails (bool): + Place serves cocktails. + + This field is a member of `oneof`_ ``_serves_cocktails``. + serves_dessert (bool): + Place serves dessert. + + This field is a member of `oneof`_ ``_serves_dessert``. + serves_coffee (bool): + Place serves coffee. + + This field is a member of `oneof`_ ``_serves_coffee``. + good_for_children (bool): + Place is good for children. + + This field is a member of `oneof`_ ``_good_for_children``. + allows_dogs (bool): + Place allows dogs. + + This field is a member of `oneof`_ ``_allows_dogs``. + restroom (bool): + Place has restroom. + + This field is a member of `oneof`_ ``_restroom``. + good_for_groups (bool): + Place accommodates groups. + + This field is a member of `oneof`_ ``_good_for_groups``. + good_for_watching_sports (bool): + Place is suitable for watching sports. + + This field is a member of `oneof`_ ``_good_for_watching_sports``. + payment_options (google.maps.places_v1.types.Place.PaymentOptions): + Payment options the place accepts. If a + payment option data is not available, the + payment option field will be unset. + parking_options (google.maps.places_v1.types.Place.ParkingOptions): + Options of parking provided by the place. + sub_destinations (MutableSequence[google.maps.places_v1.types.Place.SubDestination]): + A list of sub destinations related to the + place. + accessibility_options (google.maps.places_v1.types.Place.AccessibilityOptions): + Information about the accessibility options a + place offers. + + This field is a member of `oneof`_ ``_accessibility_options``. + fuel_options (google.maps.places_v1.types.FuelOptions): + The most recent information about fuel + options in a gas station. This information is + updated regularly. + ev_charge_options (google.maps.places_v1.types.EVChargeOptions): + Information of ev charging options. + generative_summary (google.maps.places_v1.types.Place.GenerativeSummary): + Experimental: See + https://developers.google.com/maps/documentation/places/web-service/experimental/places-generative + for more details. + + AI-generated summary of the place. + area_summary (google.maps.places_v1.types.Place.AreaSummary): + Experimental: See + https://developers.google.com/maps/documentation/places/web-service/experimental/places-generative + for more details. + + AI-generated summary of the area that the place + is in. + containing_places (MutableSequence[google.maps.places_v1.types.Place.ContainingPlace]): + List of places in which the current place is + located. + pure_service_area_business (bool): + Indicates whether the place is a pure service + area business. Pure service area business is a + business that visits or delivers to customers + directly but does not serve customers at their + business address. For example, businesses like + cleaning services or plumbers. Those businesses + may not have a physical address or location on + Google Maps. + + This field is a member of `oneof`_ ``_pure_service_area_business``. + price_range (google.maps.places_v1.types.PriceRange): + The price range associated with a Place. + """ + class BusinessStatus(proto.Enum): + r"""Business status for the place. + + Values: + BUSINESS_STATUS_UNSPECIFIED (0): + Default value. This value is unused. + OPERATIONAL (1): + The establishment is operational, not + necessarily open now. + CLOSED_TEMPORARILY (2): + The establishment is temporarily closed. + CLOSED_PERMANENTLY (3): + The establishment is permanently closed. + """ + BUSINESS_STATUS_UNSPECIFIED = 0 + OPERATIONAL = 1 + CLOSED_TEMPORARILY = 2 + CLOSED_PERMANENTLY = 3 + + class AddressComponent(proto.Message): + r"""The structured components that form the formatted address, if + this information is available. + + Attributes: + long_text (str): + The full text description or name of the address component. + For example, an address component for the country Australia + may have a long_name of "Australia". + short_text (str): + An abbreviated textual name for the address component, if + available. For example, an address component for the country + of Australia may have a short_name of "AU". + types (MutableSequence[str]): + An array indicating the type(s) of the + address component. + language_code (str): + The language used to format this components, + in CLDR notation. + """ + + long_text: str = proto.Field( + proto.STRING, + number=1, + ) + short_text: str = proto.Field( + proto.STRING, + number=2, + ) + types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + language_code: str = proto.Field( + proto.STRING, + number=4, + ) + + class PlusCode(proto.Message): + r"""Plus code (http://plus.codes) is a location reference with + two formats: global code defining a 14mx14m (1/8000th of a + degree) or smaller rectangle, and compound code, replacing the + prefix with a reference location. + + Attributes: + global_code (str): + Place's global (full) code, such as + "9FWM33GV+HQ", representing an 1/8000 by 1/8000 + degree area (~14 by 14 meters). + compound_code (str): + Place's compound code, such as "33GV+HQ, + Ramberg, Norway", containing the suffix of the + global code and replacing the prefix with a + formatted name of a reference entity. + """ + + global_code: str = proto.Field( + proto.STRING, + number=1, + ) + compound_code: str = proto.Field( + proto.STRING, + number=2, + ) + + class OpeningHours(proto.Message): + r"""Information about business hour of the place. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + open_now (bool): + Whether the opening hours period is currently + active. For regular opening hours and current + opening hours, this field means whether the + place is open. For secondary opening hours and + current secondary opening hours, this field + means whether the secondary hours of this place + is active. + + This field is a member of `oneof`_ ``_open_now``. + periods (MutableSequence[google.maps.places_v1.types.Place.OpeningHours.Period]): + The periods that this place is open during + the week. The periods are in chronological + order, starting with Sunday in the place-local + timezone. An empty (but not absent) value + indicates a place that is never open, e.g. + because it is closed temporarily for + renovations. + weekday_descriptions (MutableSequence[str]): + Localized strings describing the opening + hours of this place, one string for each day of + the week. Will be empty if the hours are + unknown or could not be converted to localized + text. Example: "Sun: 18:00–06:00". + secondary_hours_type (google.maps.places_v1.types.Place.OpeningHours.SecondaryHoursType): + A type string used to identify the type of + secondary hours. + special_days (MutableSequence[google.maps.places_v1.types.Place.OpeningHours.SpecialDay]): + Structured information for special days that fall within the + period that the returned opening hours cover. Special days + are days that could impact the business hours of a place, + e.g. Christmas day. Set for current_opening_hours and + current_secondary_opening_hours if there are exceptional + hours. + next_open_time (google.protobuf.timestamp_pb2.Timestamp): + The next time the current opening hours + period starts up to 7 days in the future. This + field is only populated if the opening hours + period is not active at the time of serving the + request. + next_close_time (google.protobuf.timestamp_pb2.Timestamp): + The next time the current opening hours + period ends up to 7 days in the future. This + field is only populated if the opening hours + period is active at the time of serving the + request. + """ + class SecondaryHoursType(proto.Enum): + r"""A type used to identify the type of secondary hours. + + Values: + SECONDARY_HOURS_TYPE_UNSPECIFIED (0): + Default value when secondary hour type is not + specified. + DRIVE_THROUGH (1): + The drive-through hour for banks, + restaurants, or pharmacies. + HAPPY_HOUR (2): + The happy hour. + DELIVERY (3): + The delivery hour. + TAKEOUT (4): + The takeout hour. + KITCHEN (5): + The kitchen hour. + BREAKFAST (6): + The breakfast hour. + LUNCH (7): + The lunch hour. + DINNER (8): + The dinner hour. + BRUNCH (9): + The brunch hour. + PICKUP (10): + The pickup hour. + ACCESS (11): + The access hours for storage places. + SENIOR_HOURS (12): + The special hours for seniors. + ONLINE_SERVICE_HOURS (13): + The online service hours. + """ + SECONDARY_HOURS_TYPE_UNSPECIFIED = 0 + DRIVE_THROUGH = 1 + HAPPY_HOUR = 2 + DELIVERY = 3 + TAKEOUT = 4 + KITCHEN = 5 + BREAKFAST = 6 + LUNCH = 7 + DINNER = 8 + BRUNCH = 9 + PICKUP = 10 + ACCESS = 11 + SENIOR_HOURS = 12 + ONLINE_SERVICE_HOURS = 13 + + class Period(proto.Message): + r"""A period the place remains in open_now status. + + Attributes: + open_ (google.maps.places_v1.types.Place.OpeningHours.Period.Point): + The time that the place starts to be open. + close (google.maps.places_v1.types.Place.OpeningHours.Period.Point): + The time that the place starts to be closed. + """ + + class Point(proto.Message): + r"""Status changing points. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + day (int): + A day of the week, as an integer in the range + 0-6. 0 is Sunday, 1 is Monday, etc. + + This field is a member of `oneof`_ ``_day``. + hour (int): + The hour in 2 digits. Ranges from 00 to 23. + + This field is a member of `oneof`_ ``_hour``. + minute (int): + The minute in 2 digits. Ranges from 00 to 59. + + This field is a member of `oneof`_ ``_minute``. + date (google.type.date_pb2.Date): + Date in the local timezone for the place. + truncated (bool): + Whether or not this endpoint was truncated. Truncation + occurs when the real hours are outside the times we are + willing to return hours between, so we truncate the hours + back to these boundaries. This ensures that at most 24 \* 7 + hours from midnight of the day of the request are returned. + """ + + day: int = proto.Field( + proto.INT32, + number=1, + optional=True, + ) + hour: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + minute: int = proto.Field( + proto.INT32, + number=3, + optional=True, + ) + date: date_pb2.Date = proto.Field( + proto.MESSAGE, + number=6, + message=date_pb2.Date, + ) + truncated: bool = proto.Field( + proto.BOOL, + number=5, + ) + + open_: 'Place.OpeningHours.Period.Point' = proto.Field( + proto.MESSAGE, + number=1, + message='Place.OpeningHours.Period.Point', + ) + close: 'Place.OpeningHours.Period.Point' = proto.Field( + proto.MESSAGE, + number=2, + message='Place.OpeningHours.Period.Point', + ) + + class SpecialDay(proto.Message): + r"""Structured information for special days that fall within the + period that the returned opening hours cover. Special days are + days that could impact the business hours of a place, e.g. + Christmas day. + + Attributes: + date (google.type.date_pb2.Date): + The date of this special day. + """ + + date: date_pb2.Date = proto.Field( + proto.MESSAGE, + number=1, + message=date_pb2.Date, + ) + + open_now: bool = proto.Field( + proto.BOOL, + number=1, + optional=True, + ) + periods: MutableSequence['Place.OpeningHours.Period'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Place.OpeningHours.Period', + ) + weekday_descriptions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + secondary_hours_type: 'Place.OpeningHours.SecondaryHoursType' = proto.Field( + proto.ENUM, + number=4, + enum='Place.OpeningHours.SecondaryHoursType', + ) + special_days: MutableSequence['Place.OpeningHours.SpecialDay'] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message='Place.OpeningHours.SpecialDay', + ) + next_open_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + next_close_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + + class Attribution(proto.Message): + r"""Information about data providers of this place. + + Attributes: + provider (str): + Name of the Place's data provider. + provider_uri (str): + URI to the Place's data provider. + """ + + provider: str = proto.Field( + proto.STRING, + number=1, + ) + provider_uri: str = proto.Field( + proto.STRING, + number=2, + ) + + class PaymentOptions(proto.Message): + r"""Payment options the place accepts. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + accepts_credit_cards (bool): + Place accepts credit cards as payment. + + This field is a member of `oneof`_ ``_accepts_credit_cards``. + accepts_debit_cards (bool): + Place accepts debit cards as payment. + + This field is a member of `oneof`_ ``_accepts_debit_cards``. + accepts_cash_only (bool): + Place accepts cash only as payment. Places + with this attribute may still accept other + payment methods. + + This field is a member of `oneof`_ ``_accepts_cash_only``. + accepts_nfc (bool): + Place accepts NFC payments. + + This field is a member of `oneof`_ ``_accepts_nfc``. + """ + + accepts_credit_cards: bool = proto.Field( + proto.BOOL, + number=1, + optional=True, + ) + accepts_debit_cards: bool = proto.Field( + proto.BOOL, + number=2, + optional=True, + ) + accepts_cash_only: bool = proto.Field( + proto.BOOL, + number=3, + optional=True, + ) + accepts_nfc: bool = proto.Field( + proto.BOOL, + number=4, + optional=True, + ) + + class ParkingOptions(proto.Message): + r"""Information about parking options for the place. A parking + lot could support more than one option at the same time. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + free_parking_lot (bool): + Place offers free parking lots. + + This field is a member of `oneof`_ ``_free_parking_lot``. + paid_parking_lot (bool): + Place offers paid parking lots. + + This field is a member of `oneof`_ ``_paid_parking_lot``. + free_street_parking (bool): + Place offers free street parking. + + This field is a member of `oneof`_ ``_free_street_parking``. + paid_street_parking (bool): + Place offers paid street parking. + + This field is a member of `oneof`_ ``_paid_street_parking``. + valet_parking (bool): + Place offers valet parking. + + This field is a member of `oneof`_ ``_valet_parking``. + free_garage_parking (bool): + Place offers free garage parking. + + This field is a member of `oneof`_ ``_free_garage_parking``. + paid_garage_parking (bool): + Place offers paid garage parking. + + This field is a member of `oneof`_ ``_paid_garage_parking``. + """ + + free_parking_lot: bool = proto.Field( + proto.BOOL, + number=1, + optional=True, + ) + paid_parking_lot: bool = proto.Field( + proto.BOOL, + number=2, + optional=True, + ) + free_street_parking: bool = proto.Field( + proto.BOOL, + number=3, + optional=True, + ) + paid_street_parking: bool = proto.Field( + proto.BOOL, + number=4, + optional=True, + ) + valet_parking: bool = proto.Field( + proto.BOOL, + number=5, + optional=True, + ) + free_garage_parking: bool = proto.Field( + proto.BOOL, + number=6, + optional=True, + ) + paid_garage_parking: bool = proto.Field( + proto.BOOL, + number=7, + optional=True, + ) + + class SubDestination(proto.Message): + r"""Place resource name and id of sub destinations that relate to + the place. For example, different terminals are different + destinations of an airport. + + Attributes: + name (str): + The resource name of the sub destination. + id (str): + The place id of the sub destination. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + id: str = proto.Field( + proto.STRING, + number=2, + ) + + class AccessibilityOptions(proto.Message): + r"""Information about the accessibility options a place offers. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + wheelchair_accessible_parking (bool): + Place offers wheelchair accessible parking. + + This field is a member of `oneof`_ ``_wheelchair_accessible_parking``. + wheelchair_accessible_entrance (bool): + Places has wheelchair accessible entrance. + + This field is a member of `oneof`_ ``_wheelchair_accessible_entrance``. + wheelchair_accessible_restroom (bool): + Place has wheelchair accessible restroom. + + This field is a member of `oneof`_ ``_wheelchair_accessible_restroom``. + wheelchair_accessible_seating (bool): + Place has wheelchair accessible seating. + + This field is a member of `oneof`_ ``_wheelchair_accessible_seating``. + """ + + wheelchair_accessible_parking: bool = proto.Field( + proto.BOOL, + number=1, + optional=True, + ) + wheelchair_accessible_entrance: bool = proto.Field( + proto.BOOL, + number=2, + optional=True, + ) + wheelchair_accessible_restroom: bool = proto.Field( + proto.BOOL, + number=3, + optional=True, + ) + wheelchair_accessible_seating: bool = proto.Field( + proto.BOOL, + number=4, + optional=True, + ) + + class GenerativeSummary(proto.Message): + r"""Experimental: See + https://developers.google.com/maps/documentation/places/web-service/experimental/places-generative + for more details. + + AI-generated summary of the place. + + Attributes: + overview (google.type.localized_text_pb2.LocalizedText): + The overview of the place. + description (google.type.localized_text_pb2.LocalizedText): + The detailed description of the place. + references (google.maps.places_v1.types.References): + References that are used to generate the + summary description. + """ + + overview: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=1, + message=localized_text_pb2.LocalizedText, + ) + description: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=2, + message=localized_text_pb2.LocalizedText, + ) + references: reference.References = proto.Field( + proto.MESSAGE, + number=3, + message=reference.References, + ) + + class AreaSummary(proto.Message): + r"""Experimental: See + https://developers.google.com/maps/documentation/places/web-service/experimental/places-generative + for more details. + + AI-generated summary of the area that the place is in. + + Attributes: + content_blocks (MutableSequence[google.maps.places_v1.types.ContentBlock]): + Content blocks that compose the area summary. + Each block has a separate topic about the area. + """ + + content_blocks: MutableSequence[content_block.ContentBlock] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=content_block.ContentBlock, + ) + + class ContainingPlace(proto.Message): + r"""Info about the place in which this place is located. + + Attributes: + name (str): + The resource name of the place in which this + place is located. + id (str): + The place id of the place in which this place + is located. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + id: str = proto.Field( + proto.STRING, + number=2, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + id: str = proto.Field( + proto.STRING, + number=2, + ) + display_name: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=31, + message=localized_text_pb2.LocalizedText, + ) + types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + primary_type: str = proto.Field( + proto.STRING, + number=50, + ) + primary_type_display_name: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=32, + message=localized_text_pb2.LocalizedText, + ) + national_phone_number: str = proto.Field( + proto.STRING, + number=7, + ) + international_phone_number: str = proto.Field( + proto.STRING, + number=8, + ) + formatted_address: str = proto.Field( + proto.STRING, + number=9, + ) + short_formatted_address: str = proto.Field( + proto.STRING, + number=51, + ) + address_components: MutableSequence[AddressComponent] = proto.RepeatedField( + proto.MESSAGE, + number=10, + message=AddressComponent, + ) + plus_code: PlusCode = proto.Field( + proto.MESSAGE, + number=11, + message=PlusCode, + ) + location: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=12, + message=latlng_pb2.LatLng, + ) + viewport: ggt_viewport.Viewport = proto.Field( + proto.MESSAGE, + number=13, + message=ggt_viewport.Viewport, + ) + rating: float = proto.Field( + proto.DOUBLE, + number=14, + ) + google_maps_uri: str = proto.Field( + proto.STRING, + number=15, + ) + website_uri: str = proto.Field( + proto.STRING, + number=16, + ) + reviews: MutableSequence[review.Review] = proto.RepeatedField( + proto.MESSAGE, + number=53, + message=review.Review, + ) + regular_opening_hours: OpeningHours = proto.Field( + proto.MESSAGE, + number=21, + message=OpeningHours, + ) + utc_offset_minutes: int = proto.Field( + proto.INT32, + number=22, + optional=True, + ) + photos: MutableSequence[photo.Photo] = proto.RepeatedField( + proto.MESSAGE, + number=54, + message=photo.Photo, + ) + adr_format_address: str = proto.Field( + proto.STRING, + number=24, + ) + business_status: BusinessStatus = proto.Field( + proto.ENUM, + number=25, + enum=BusinessStatus, + ) + price_level: 'PriceLevel' = proto.Field( + proto.ENUM, + number=26, + enum='PriceLevel', + ) + attributions: MutableSequence[Attribution] = proto.RepeatedField( + proto.MESSAGE, + number=27, + message=Attribution, + ) + user_rating_count: int = proto.Field( + proto.INT32, + number=28, + optional=True, + ) + icon_mask_base_uri: str = proto.Field( + proto.STRING, + number=29, + ) + icon_background_color: str = proto.Field( + proto.STRING, + number=30, + ) + takeout: bool = proto.Field( + proto.BOOL, + number=33, + optional=True, + ) + delivery: bool = proto.Field( + proto.BOOL, + number=34, + optional=True, + ) + dine_in: bool = proto.Field( + proto.BOOL, + number=35, + optional=True, + ) + curbside_pickup: bool = proto.Field( + proto.BOOL, + number=36, + optional=True, + ) + reservable: bool = proto.Field( + proto.BOOL, + number=38, + optional=True, + ) + serves_breakfast: bool = proto.Field( + proto.BOOL, + number=39, + optional=True, + ) + serves_lunch: bool = proto.Field( + proto.BOOL, + number=40, + optional=True, + ) + serves_dinner: bool = proto.Field( + proto.BOOL, + number=41, + optional=True, + ) + serves_beer: bool = proto.Field( + proto.BOOL, + number=42, + optional=True, + ) + serves_wine: bool = proto.Field( + proto.BOOL, + number=43, + optional=True, + ) + serves_brunch: bool = proto.Field( + proto.BOOL, + number=44, + optional=True, + ) + serves_vegetarian_food: bool = proto.Field( + proto.BOOL, + number=45, + optional=True, + ) + current_opening_hours: OpeningHours = proto.Field( + proto.MESSAGE, + number=46, + message=OpeningHours, + ) + current_secondary_opening_hours: MutableSequence[OpeningHours] = proto.RepeatedField( + proto.MESSAGE, + number=47, + message=OpeningHours, + ) + regular_secondary_opening_hours: MutableSequence[OpeningHours] = proto.RepeatedField( + proto.MESSAGE, + number=49, + message=OpeningHours, + ) + editorial_summary: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=52, + message=localized_text_pb2.LocalizedText, + ) + outdoor_seating: bool = proto.Field( + proto.BOOL, + number=55, + optional=True, + ) + live_music: bool = proto.Field( + proto.BOOL, + number=56, + optional=True, + ) + menu_for_children: bool = proto.Field( + proto.BOOL, + number=57, + optional=True, + ) + serves_cocktails: bool = proto.Field( + proto.BOOL, + number=58, + optional=True, + ) + serves_dessert: bool = proto.Field( + proto.BOOL, + number=59, + optional=True, + ) + serves_coffee: bool = proto.Field( + proto.BOOL, + number=60, + optional=True, + ) + good_for_children: bool = proto.Field( + proto.BOOL, + number=62, + optional=True, + ) + allows_dogs: bool = proto.Field( + proto.BOOL, + number=63, + optional=True, + ) + restroom: bool = proto.Field( + proto.BOOL, + number=64, + optional=True, + ) + good_for_groups: bool = proto.Field( + proto.BOOL, + number=65, + optional=True, + ) + good_for_watching_sports: bool = proto.Field( + proto.BOOL, + number=66, + optional=True, + ) + payment_options: PaymentOptions = proto.Field( + proto.MESSAGE, + number=67, + message=PaymentOptions, + ) + parking_options: ParkingOptions = proto.Field( + proto.MESSAGE, + number=70, + message=ParkingOptions, + ) + sub_destinations: MutableSequence[SubDestination] = proto.RepeatedField( + proto.MESSAGE, + number=71, + message=SubDestination, + ) + accessibility_options: AccessibilityOptions = proto.Field( + proto.MESSAGE, + number=72, + optional=True, + message=AccessibilityOptions, + ) + fuel_options: gmp_fuel_options.FuelOptions = proto.Field( + proto.MESSAGE, + number=78, + message=gmp_fuel_options.FuelOptions, + ) + ev_charge_options: ev_charging.EVChargeOptions = proto.Field( + proto.MESSAGE, + number=79, + message=ev_charging.EVChargeOptions, + ) + generative_summary: GenerativeSummary = proto.Field( + proto.MESSAGE, + number=80, + message=GenerativeSummary, + ) + area_summary: AreaSummary = proto.Field( + proto.MESSAGE, + number=81, + message=AreaSummary, + ) + containing_places: MutableSequence[ContainingPlace] = proto.RepeatedField( + proto.MESSAGE, + number=82, + message=ContainingPlace, + ) + pure_service_area_business: bool = proto.Field( + proto.BOOL, + number=83, + optional=True, + ) + price_range: gmp_price_range.PriceRange = proto.Field( + proto.MESSAGE, + number=86, + message=gmp_price_range.PriceRange, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/places_service.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/places_service.py new file mode 100644 index 000000000000..efd86f57ba22 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/places_service.py @@ -0,0 +1,1340 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.geo.type.types import viewport +from google.maps.places_v1.types import contextual_content +from google.maps.places_v1.types import ev_charging +from google.maps.places_v1.types import geometry +from google.maps.places_v1.types import place as gmp_place +from google.maps.places_v1.types import polyline as gmp_polyline +from google.maps.places_v1.types import route_modifiers as gmp_route_modifiers +from google.maps.places_v1.types import routing_preference as gmp_routing_preference +from google.maps.places_v1.types import routing_summary +from google.maps.places_v1.types import travel_mode as gmp_travel_mode +from google.type import latlng_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.places.v1', + manifest={ + 'RoutingParameters', + 'SearchNearbyRequest', + 'SearchNearbyResponse', + 'SearchTextRequest', + 'SearchTextResponse', + 'GetPhotoMediaRequest', + 'PhotoMedia', + 'GetPlaceRequest', + 'AutocompletePlacesRequest', + 'AutocompletePlacesResponse', + }, +) + + +class RoutingParameters(proto.Message): + r"""Parameters to configure the routing calculations to the + places in the response, both along a route (where result ranking + will be influenced) and for calculating travel times on results. + + Attributes: + origin (google.type.latlng_pb2.LatLng): + Optional. An explicit routing origin that + overrides the origin defined in the polyline. By + default, the polyline origin is used. + travel_mode (google.maps.places_v1.types.TravelMode): + Optional. The travel mode. + route_modifiers (google.maps.places_v1.types.RouteModifiers): + Optional. The route modifiers. + routing_preference (google.maps.places_v1.types.RoutingPreference): + Optional. Specifies how to compute the routing summaries. + The server attempts to use the selected routing preference + to compute the route. The traffic aware routing preference + is only available for the ``DRIVE`` or ``TWO_WHEELER`` + ``travelMode``. + """ + + origin: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=1, + message=latlng_pb2.LatLng, + ) + travel_mode: gmp_travel_mode.TravelMode = proto.Field( + proto.ENUM, + number=2, + enum=gmp_travel_mode.TravelMode, + ) + route_modifiers: gmp_route_modifiers.RouteModifiers = proto.Field( + proto.MESSAGE, + number=3, + message=gmp_route_modifiers.RouteModifiers, + ) + routing_preference: gmp_routing_preference.RoutingPreference = proto.Field( + proto.ENUM, + number=4, + enum=gmp_routing_preference.RoutingPreference, + ) + + +class SearchNearbyRequest(proto.Message): + r"""Request proto for Search Nearby. + + Attributes: + language_code (str): + Place details will be displayed with the + preferred language if available. If the language + code is unspecified or unrecognized, place + details of any language may be returned, with a + preference for English if such details exist. + + Current list of supported languages: + + https://developers.google.com/maps/faq#languagesupport. + region_code (str): + The Unicode country/region code (CLDR) of the location where + the request is coming from. This parameter is used to + display the place details, like region-specific place name, + if available. The parameter can affect results based on + applicable law. + + For more information, see + https://www.unicode.org/cldr/charts/latest/supplemental/territory_language_information.html. + + Note that 3-digit region codes are not currently supported. + included_types (MutableSequence[str]): + Included Place type (eg, "restaurant" or "gas_station") from + https://developers.google.com/maps/documentation/places/web-service/place-types. + + Up to 50 types from `Table + A `__ + may be specified. + + If there are any conflicting types, i.e. a type appears in + both included_types and excluded_types, an INVALID_ARGUMENT + error is returned. + + If a Place type is specified with multiple type + restrictions, only places that satisfy all of the + restrictions are returned. For example, if we have + {included_types = ["restaurant"], excluded_primary_types = + ["restaurant"]}, the returned places provide "restaurant" + related services but do not operate primarily as + "restaurants". + excluded_types (MutableSequence[str]): + Excluded Place type (eg, "restaurant" or "gas_station") from + https://developers.google.com/maps/documentation/places/web-service/place-types. + + Up to 50 types from `Table + A `__ + may be specified. + + If the client provides both included_types (e.g. restaurant) + and excluded_types (e.g. cafe), then the response should + include places that are restaurant but not cafe. The + response includes places that match at least one of the + included_types and none of the excluded_types. + + If there are any conflicting types, i.e. a type appears in + both included_types and excluded_types, an INVALID_ARGUMENT + error is returned. + + If a Place type is specified with multiple type + restrictions, only places that satisfy all of the + restrictions are returned. For example, if we have + {included_types = ["restaurant"], excluded_primary_types = + ["restaurant"]}, the returned places provide "restaurant" + related services but do not operate primarily as + "restaurants". + included_primary_types (MutableSequence[str]): + Included primary Place type (e.g. "restaurant" or + "gas_station") from + https://developers.google.com/maps/documentation/places/web-service/place-types. + A place can only have a single primary type from the + supported types table associated with it. + + Up to 50 types from `Table + A `__ + may be specified. + + If there are any conflicting primary types, i.e. a type + appears in both included_primary_types and + excluded_primary_types, an INVALID_ARGUMENT error is + returned. + + If a Place type is specified with multiple type + restrictions, only places that satisfy all of the + restrictions are returned. For example, if we have + {included_types = ["restaurant"], excluded_primary_types = + ["restaurant"]}, the returned places provide "restaurant" + related services but do not operate primarily as + "restaurants". + excluded_primary_types (MutableSequence[str]): + Excluded primary Place type (e.g. "restaurant" or + "gas_station") from + https://developers.google.com/maps/documentation/places/web-service/place-types. + + Up to 50 types from `Table + A `__ + may be specified. + + If there are any conflicting primary types, i.e. a type + appears in both included_primary_types and + excluded_primary_types, an INVALID_ARGUMENT error is + returned. + + If a Place type is specified with multiple type + restrictions, only places that satisfy all of the + restrictions are returned. For example, if we have + {included_types = ["restaurant"], excluded_primary_types = + ["restaurant"]}, the returned places provide "restaurant" + related services but do not operate primarily as + "restaurants". + max_result_count (int): + Maximum number of results to return. It must be between 1 + and 20 (default), inclusively. If the number is unset, it + falls back to the upper limit. If the number is set to + negative or exceeds the upper limit, an INVALID_ARGUMENT + error is returned. + location_restriction (google.maps.places_v1.types.SearchNearbyRequest.LocationRestriction): + Required. The region to search. + rank_preference (google.maps.places_v1.types.SearchNearbyRequest.RankPreference): + How results will be ranked in the response. + routing_parameters (google.maps.places_v1.types.RoutingParameters): + Optional. Parameters that affect the routing + to the search results. + """ + class RankPreference(proto.Enum): + r"""How results will be ranked in the response. + + Values: + RANK_PREFERENCE_UNSPECIFIED (0): + RankPreference value not set. Will use rank + by POPULARITY by default. + DISTANCE (1): + Ranks results by distance. + POPULARITY (2): + Ranks results by popularity. + """ + RANK_PREFERENCE_UNSPECIFIED = 0 + DISTANCE = 1 + POPULARITY = 2 + + class LocationRestriction(proto.Message): + r"""The region to search. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + circle (google.maps.places_v1.types.Circle): + A circle defined by center point and radius. + + This field is a member of `oneof`_ ``type``. + """ + + circle: geometry.Circle = proto.Field( + proto.MESSAGE, + number=2, + oneof='type', + message=geometry.Circle, + ) + + language_code: str = proto.Field( + proto.STRING, + number=1, + ) + region_code: str = proto.Field( + proto.STRING, + number=2, + ) + included_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + excluded_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + included_primary_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + excluded_primary_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=6, + ) + max_result_count: int = proto.Field( + proto.INT32, + number=7, + ) + location_restriction: LocationRestriction = proto.Field( + proto.MESSAGE, + number=8, + message=LocationRestriction, + ) + rank_preference: RankPreference = proto.Field( + proto.ENUM, + number=9, + enum=RankPreference, + ) + routing_parameters: 'RoutingParameters' = proto.Field( + proto.MESSAGE, + number=10, + message='RoutingParameters', + ) + + +class SearchNearbyResponse(proto.Message): + r"""Response proto for Search Nearby. + + Attributes: + places (MutableSequence[google.maps.places_v1.types.Place]): + A list of places that meets user's + requirements like places types, number of places + and specific location restriction. + routing_summaries (MutableSequence[google.maps.places_v1.types.RoutingSummary]): + A list of routing summaries where each entry associates to + the corresponding place in the same index in the ``places`` + field. If the routing summary is not available for one of + the places, it will contain an empty entry. This list should + have as many entries as the list of places if requested. + """ + + places: MutableSequence[gmp_place.Place] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gmp_place.Place, + ) + routing_summaries: MutableSequence[routing_summary.RoutingSummary] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=routing_summary.RoutingSummary, + ) + + +class SearchTextRequest(proto.Message): + r"""Request proto for SearchText. + + Attributes: + text_query (str): + Required. The text query for textual search. + language_code (str): + Place details will be displayed with the + preferred language if available. If the language + code is unspecified or unrecognized, place + details of any language may be returned, with a + preference for English if such details exist. + + Current list of supported languages: + + https://developers.google.com/maps/faq#languagesupport. + region_code (str): + The Unicode country/region code (CLDR) of the location where + the request is coming from. This parameter is used to + display the place details, like region-specific place name, + if available. The parameter can affect results based on + applicable law. + + For more information, see + https://www.unicode.org/cldr/charts/latest/supplemental/territory_language_information.html. + + Note that 3-digit region codes are not currently supported. + rank_preference (google.maps.places_v1.types.SearchTextRequest.RankPreference): + How results will be ranked in the response. + included_type (str): + The requested place type. Full list of types + supported: + https://developers.google.com/maps/documentation/places/web-service/place-types. + Only support one included type. + open_now (bool): + Used to restrict the search to places that + are currently open. The default is false. + min_rating (float): + Filter out results whose average user rating is strictly + less than this limit. A valid value must be a float between + 0 and 5 (inclusively) at a 0.5 cadence i.e. [0, 0.5, 1.0, + ... , 5.0] inclusively. The input rating will round up to + the nearest 0.5(ceiling). For instance, a rating of 0.6 will + eliminate all results with a less than 1.0 rating. + max_result_count (int): + Maximum number of results to return. It must be between 1 + and 20, inclusively. The default is 20. If the number is + unset, it falls back to the upper limit. If the number is + set to negative or exceeds the upper limit, an + INVALID_ARGUMENT error is returned. + price_levels (MutableSequence[google.maps.places_v1.types.PriceLevel]): + Used to restrict the search to places that + are marked as certain price levels. Users can + choose any combinations of price levels. Default + to select all price levels. + strict_type_filtering (bool): + Used to set strict type filtering for included_type. If set + to true, only results of the same type will be returned. + Default to false. + location_bias (google.maps.places_v1.types.SearchTextRequest.LocationBias): + The region to search. This location serves as a bias which + means results around given location might be returned. + Cannot be set along with location_restriction. + location_restriction (google.maps.places_v1.types.SearchTextRequest.LocationRestriction): + The region to search. This location serves as a restriction + which means results outside given location will not be + returned. Cannot be set along with location_bias. + ev_options (google.maps.places_v1.types.SearchTextRequest.EVOptions): + Optional. Set the searchable EV options of a + place search request. + routing_parameters (google.maps.places_v1.types.RoutingParameters): + Optional. Additional parameters for routing + to results. + search_along_route_parameters (google.maps.places_v1.types.SearchTextRequest.SearchAlongRouteParameters): + Optional. Additional parameters proto for + searching along a route. + include_pure_service_area_businesses (bool): + Optional. Include pure service area businesses if the field + is set to true. Pure service area business is a business + that visits or delivers to customers directly but does not + serve customers at their business address. For example, + businesses like cleaning services or plumbers. Those + businesses do not have a physical address or location on + Google Maps. Places will not return fields including + ``location``, ``plus_code``, and other location related + fields for these businesses. + """ + class RankPreference(proto.Enum): + r"""How results will be ranked in the response. + + Values: + RANK_PREFERENCE_UNSPECIFIED (0): + For a categorical query such as "Restaurants + in New York City", RELEVANCE is the default. For + non-categorical queries such as "Mountain View, + CA" we recommend that you leave rankPreference + unset. + DISTANCE (1): + Ranks results by distance. + RELEVANCE (2): + Ranks results by relevance. Sort order + determined by normal ranking stack. + """ + RANK_PREFERENCE_UNSPECIFIED = 0 + DISTANCE = 1 + RELEVANCE = 2 + + class LocationBias(proto.Message): + r"""The region to search. This location serves as a bias which + means results around given location might be returned. + + 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: + rectangle (google.geo.type.types.Viewport): + A rectangle box defined by northeast and southwest corner. + ``rectangle.high()`` must be the northeast point of the + rectangle viewport. ``rectangle.low()`` must be the + southwest point of the rectangle viewport. + ``rectangle.low().latitude()`` cannot be greater than + ``rectangle.high().latitude()``. This will result in an + empty latitude range. A rectangle viewport cannot be wider + than 180 degrees. + + This field is a member of `oneof`_ ``type``. + circle (google.maps.places_v1.types.Circle): + A circle defined by center point and radius. + + This field is a member of `oneof`_ ``type``. + """ + + rectangle: viewport.Viewport = proto.Field( + proto.MESSAGE, + number=1, + oneof='type', + message=viewport.Viewport, + ) + circle: geometry.Circle = proto.Field( + proto.MESSAGE, + number=2, + oneof='type', + message=geometry.Circle, + ) + + class LocationRestriction(proto.Message): + r"""The region to search. This location serves as a restriction + which means results outside given location will not be returned. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + rectangle (google.geo.type.types.Viewport): + A rectangle box defined by northeast and southwest corner. + ``rectangle.high()`` must be the northeast point of the + rectangle viewport. ``rectangle.low()`` must be the + southwest point of the rectangle viewport. + ``rectangle.low().latitude()`` cannot be greater than + ``rectangle.high().latitude()``. This will result in an + empty latitude range. A rectangle viewport cannot be wider + than 180 degrees. + + This field is a member of `oneof`_ ``type``. + """ + + rectangle: viewport.Viewport = proto.Field( + proto.MESSAGE, + number=1, + oneof='type', + message=viewport.Viewport, + ) + + class EVOptions(proto.Message): + r"""Searchable EV options of a place search request. + + Attributes: + minimum_charging_rate_kw (float): + Optional. Minimum required charging rate in + kilowatts. A place with a charging rate less + than the specified rate is filtered out. + connector_types (MutableSequence[google.maps.places_v1.types.EVConnectorType]): + Optional. The list of preferred EV connector + types. A place that does not support any of the + listed connector types is filtered out. + """ + + minimum_charging_rate_kw: float = proto.Field( + proto.DOUBLE, + number=1, + ) + connector_types: MutableSequence[ev_charging.EVConnectorType] = proto.RepeatedField( + proto.ENUM, + number=2, + enum=ev_charging.EVConnectorType, + ) + + class SearchAlongRouteParameters(proto.Message): + r"""Specifies a precalculated polyline from the `Routes + API `__ + defining the route to search. Searching along a route is similar to + using the ``locationBias`` or ``locationRestriction`` request option + to bias the search results. However, while the ``locationBias`` and + ``locationRestriction`` options let you specify a region to bias the + search results, this option lets you bias the results along a trip + route. + + Results are not guaranteed to be along the route provided, but + rather are ranked within the search area defined by the polyline + and, optionally, by the ``locationBias`` or ``locationRestriction`` + based on minimal detour times from origin to destination. The + results might be along an alternate route, especially if the + provided polyline does not define an optimal route from origin to + destination. + + Attributes: + polyline (google.maps.places_v1.types.Polyline): + Required. The route polyline. + """ + + polyline: gmp_polyline.Polyline = proto.Field( + proto.MESSAGE, + number=1, + message=gmp_polyline.Polyline, + ) + + text_query: str = proto.Field( + proto.STRING, + number=1, + ) + language_code: str = proto.Field( + proto.STRING, + number=2, + ) + region_code: str = proto.Field( + proto.STRING, + number=3, + ) + rank_preference: RankPreference = proto.Field( + proto.ENUM, + number=4, + enum=RankPreference, + ) + included_type: str = proto.Field( + proto.STRING, + number=6, + ) + open_now: bool = proto.Field( + proto.BOOL, + number=7, + ) + min_rating: float = proto.Field( + proto.DOUBLE, + number=9, + ) + max_result_count: int = proto.Field( + proto.INT32, + number=10, + ) + price_levels: MutableSequence[gmp_place.PriceLevel] = proto.RepeatedField( + proto.ENUM, + number=11, + enum=gmp_place.PriceLevel, + ) + strict_type_filtering: bool = proto.Field( + proto.BOOL, + number=12, + ) + location_bias: LocationBias = proto.Field( + proto.MESSAGE, + number=13, + message=LocationBias, + ) + location_restriction: LocationRestriction = proto.Field( + proto.MESSAGE, + number=14, + message=LocationRestriction, + ) + ev_options: EVOptions = proto.Field( + proto.MESSAGE, + number=15, + message=EVOptions, + ) + routing_parameters: 'RoutingParameters' = proto.Field( + proto.MESSAGE, + number=16, + message='RoutingParameters', + ) + search_along_route_parameters: SearchAlongRouteParameters = proto.Field( + proto.MESSAGE, + number=17, + message=SearchAlongRouteParameters, + ) + include_pure_service_area_businesses: bool = proto.Field( + proto.BOOL, + number=20, + ) + + +class SearchTextResponse(proto.Message): + r"""Response proto for SearchText. + + Attributes: + places (MutableSequence[google.maps.places_v1.types.Place]): + A list of places that meet the user's text + search criteria. + routing_summaries (MutableSequence[google.maps.places_v1.types.RoutingSummary]): + A list of routing summaries where each entry associates to + the corresponding place in the same index in the ``places`` + field. If the routing summary is not available for one of + the places, it will contain an empty entry. This list will + have as many entries as the list of places if requested. + contextual_contents (MutableSequence[google.maps.places_v1.types.ContextualContent]): + Experimental: See + https://developers.google.com/maps/documentation/places/web-service/experimental/places-generative + for more details. + + A list of contextual contents where each entry associates to + the corresponding place in the same index in the places + field. The contents that are relevant to the ``text_query`` + in the request are preferred. If the contextual content is + not available for one of the places, it will return + non-contextual content. It will be empty only when the + content is unavailable for this place. This list will have + as many entries as the list of places if requested. + """ + + places: MutableSequence[gmp_place.Place] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gmp_place.Place, + ) + routing_summaries: MutableSequence[routing_summary.RoutingSummary] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=routing_summary.RoutingSummary, + ) + contextual_contents: MutableSequence[contextual_content.ContextualContent] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=contextual_content.ContextualContent, + ) + + +class GetPhotoMediaRequest(proto.Message): + r"""Request for fetching a photo of a place using a photo + resource name. + + Attributes: + name (str): + Required. The resource name of a photo media in the format: + ``places/{place_id}/photos/{photo_reference}/media``. + + The resource name of a photo as returned in a Place object's + ``photos.name`` field comes with the format + ``places/{place_id}/photos/{photo_reference}``. You need to + append ``/media`` at the end of the photo resource to get + the photo media resource name. + max_width_px (int): + Optional. Specifies the maximum desired width, in pixels, of + the image. If the image is smaller than the values + specified, the original image will be returned. If the image + is larger in either dimension, it will be scaled to match + the smaller of the two dimensions, restricted to its + original aspect ratio. Both the max_height_px and + max_width_px properties accept an integer between 1 and + 4800, inclusively. If the value is not within the allowed + range, an INVALID_ARGUMENT error will be returned. + + At least one of max_height_px or max_width_px needs to be + specified. If neither max_height_px nor max_width_px is + specified, an INVALID_ARGUMENT error will be returned. + max_height_px (int): + Optional. Specifies the maximum desired height, in pixels, + of the image. If the image is smaller than the values + specified, the original image will be returned. If the image + is larger in either dimension, it will be scaled to match + the smaller of the two dimensions, restricted to its + original aspect ratio. Both the max_height_px and + max_width_px properties accept an integer between 1 and + 4800, inclusively. If the value is not within the allowed + range, an INVALID_ARGUMENT error will be returned. + + At least one of max_height_px or max_width_px needs to be + specified. If neither max_height_px nor max_width_px is + specified, an INVALID_ARGUMENT error will be returned. + skip_http_redirect (bool): + Optional. If set, skip the default HTTP + redirect behavior and render a text format (for + example, in JSON format for HTTP use case) + response. If not set, an HTTP redirect will be + issued to redirect the call to the image media. + This option is ignored for non-HTTP requests. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + max_width_px: int = proto.Field( + proto.INT32, + number=2, + ) + max_height_px: int = proto.Field( + proto.INT32, + number=3, + ) + skip_http_redirect: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class PhotoMedia(proto.Message): + r"""A photo media from Places API. + + Attributes: + name (str): + The resource name of a photo media in the format: + ``places/{place_id}/photos/{photo_reference}/media``. + photo_uri (str): + A short-lived uri that can be used to render + the photo. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + photo_uri: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetPlaceRequest(proto.Message): + r"""Request for fetching a Place based on its resource name, which is a + string in the ``places/{place_id}`` format. + + Attributes: + name (str): + Required. The resource name of a place, in the + ``places/{place_id}`` format. + language_code (str): + Optional. Place details will be displayed + with the preferred language if available. + + Current list of supported languages: + + https://developers.google.com/maps/faq#languagesupport. + region_code (str): + Optional. The Unicode country/region code (CLDR) of the + location where the request is coming from. This parameter is + used to display the place details, like region-specific + place name, if available. The parameter can affect results + based on applicable law. For more information, see + https://www.unicode.org/cldr/charts/latest/supplemental/territory_language_information.html. + + Note that 3-digit region codes are not currently supported. + session_token (str): + Optional. A string which identifies an Autocomplete session + for billing purposes. Must be a URL and filename safe base64 + string with at most 36 ASCII characters in length. Otherwise + an INVALID_ARGUMENT error is returned. + + The session begins when the user starts typing a query, and + concludes when they select a place and a call to Place + Details or Address Validation is made. Each session can have + multiple queries, followed by one Place Details or Address + Validation request. The credentials used for each request + within a session must belong to the same Google Cloud + Console project. Once a session has concluded, the token is + no longer valid; your app must generate a fresh token for + each session. If the ``session_token`` parameter is omitted, + or if you reuse a session token, the session is charged as + if no session token was provided (each request is billed + separately). + + We recommend the following guidelines: + + - Use session tokens for all Place Autocomplete calls. + - Generate a fresh token for each session. Using a version + 4 UUID is recommended. + - Ensure that the credentials used for all Place + Autocomplete, Place Details, and Address Validation + requests within a session belong to the same Cloud + Console project. + - Be sure to pass a unique session token for each new + session. Using the same token for more than one session + will result in each request being billed individually. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + language_code: str = proto.Field( + proto.STRING, + number=2, + ) + region_code: str = proto.Field( + proto.STRING, + number=3, + ) + session_token: str = proto.Field( + proto.STRING, + number=4, + ) + + +class AutocompletePlacesRequest(proto.Message): + r"""Request proto for AutocompletePlaces. + + Attributes: + input (str): + Required. The text string on which to search. + location_bias (google.maps.places_v1.types.AutocompletePlacesRequest.LocationBias): + Optional. Bias results to a specified location. + + At most one of ``location_bias`` or ``location_restriction`` + should be set. If neither are set, the results will be + biased by IP address, meaning the IP address will be mapped + to an imprecise location and used as a biasing signal. + location_restriction (google.maps.places_v1.types.AutocompletePlacesRequest.LocationRestriction): + Optional. Restrict results to a specified location. + + At most one of ``location_bias`` or ``location_restriction`` + should be set. If neither are set, the results will be + biased by IP address, meaning the IP address will be mapped + to an imprecise location and used as a biasing signal. + included_primary_types (MutableSequence[str]): + Optional. Included primary Place type (for example, + "restaurant" or "gas_station") in Place Types + (https://developers.google.com/maps/documentation/places/web-service/place-types), + or only ``(regions)``, or only ``(cities)``. A Place is only + returned if its primary type is included in this list. Up to + 5 values can be specified. If no types are specified, all + Place types are returned. + included_region_codes (MutableSequence[str]): + Optional. Only include results in the specified regions, + specified as up to 15 CLDR two-character region codes. An + empty set will not restrict the results. If both + ``location_restriction`` and ``included_region_codes`` are + set, the results will be located in the area of + intersection. + language_code (str): + Optional. The language in which to return results. Defaults + to en-US. The results may be in mixed languages if the + language used in ``input`` is different from + ``language_code`` or if the returned Place does not have a + translation from the local language to ``language_code``. + region_code (str): + Optional. The region code, specified as a CLDR two-character + region code. This affects address formatting, result + ranking, and may influence what results are returned. This + does not restrict results to the specified region. To + restrict results to a region, use + ``region_code_restriction``. + origin (google.type.latlng_pb2.LatLng): + Optional. The origin point from which to calculate geodesic + distance to the destination (returned as + ``distance_meters``). If this value is omitted, geodesic + distance will not be returned. + input_offset (int): + Optional. A zero-based Unicode character offset of ``input`` + indicating the cursor position in ``input``. The cursor + position may influence what predictions are returned. + + If empty, defaults to the length of ``input``. + include_query_predictions (bool): + Optional. If true, the response will include + both Place and query predictions. Otherwise the + response will only return Place predictions. + session_token (str): + Optional. A string which identifies an Autocomplete session + for billing purposes. Must be a URL and filename safe base64 + string with at most 36 ASCII characters in length. Otherwise + an INVALID_ARGUMENT error is returned. + + The session begins when the user starts typing a query, and + concludes when they select a place and a call to Place + Details or Address Validation is made. Each session can have + multiple queries, followed by one Place Details or Address + Validation request. The credentials used for each request + within a session must belong to the same Google Cloud + Console project. Once a session has concluded, the token is + no longer valid; your app must generate a fresh token for + each session. If the ``session_token`` parameter is omitted, + or if you reuse a session token, the session is charged as + if no session token was provided (each request is billed + separately). + + We recommend the following guidelines: + + - Use session tokens for all Place Autocomplete calls. + - Generate a fresh token for each session. Using a version + 4 UUID is recommended. + - Ensure that the credentials used for all Place + Autocomplete, Place Details, and Address Validation + requests within a session belong to the same Cloud + Console project. + - Be sure to pass a unique session token for each new + session. Using the same token for more than one session + will result in each request being billed individually. + include_pure_service_area_businesses (bool): + Optional. Include pure service area businesses if the field + is set to true. Pure service area business is a business + that visits or delivers to customers directly but does not + serve customers at their business address. For example, + businesses like cleaning services or plumbers. Those + businesses do not have a physical address or location on + Google Maps. Places will not return fields including + ``location``, ``plus_code``, and other location related + fields for these businesses. + """ + + class LocationBias(proto.Message): + r"""The region to search. The results may be biased around the + specified region. + + 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: + rectangle (google.geo.type.types.Viewport): + A viewport defined by a northeast and a + southwest corner. + + This field is a member of `oneof`_ ``type``. + circle (google.maps.places_v1.types.Circle): + A circle defined by a center point and + radius. + + This field is a member of `oneof`_ ``type``. + """ + + rectangle: viewport.Viewport = proto.Field( + proto.MESSAGE, + number=1, + oneof='type', + message=viewport.Viewport, + ) + circle: geometry.Circle = proto.Field( + proto.MESSAGE, + number=2, + oneof='type', + message=geometry.Circle, + ) + + class LocationRestriction(proto.Message): + r"""The region to search. The results will be restricted to the + specified region. + + 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: + rectangle (google.geo.type.types.Viewport): + A viewport defined by a northeast and a + southwest corner. + + This field is a member of `oneof`_ ``type``. + circle (google.maps.places_v1.types.Circle): + A circle defined by a center point and + radius. + + This field is a member of `oneof`_ ``type``. + """ + + rectangle: viewport.Viewport = proto.Field( + proto.MESSAGE, + number=1, + oneof='type', + message=viewport.Viewport, + ) + circle: geometry.Circle = proto.Field( + proto.MESSAGE, + number=2, + oneof='type', + message=geometry.Circle, + ) + + input: str = proto.Field( + proto.STRING, + number=1, + ) + location_bias: LocationBias = proto.Field( + proto.MESSAGE, + number=2, + message=LocationBias, + ) + location_restriction: LocationRestriction = proto.Field( + proto.MESSAGE, + number=3, + message=LocationRestriction, + ) + included_primary_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + included_region_codes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + language_code: str = proto.Field( + proto.STRING, + number=6, + ) + region_code: str = proto.Field( + proto.STRING, + number=7, + ) + origin: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=8, + message=latlng_pb2.LatLng, + ) + input_offset: int = proto.Field( + proto.INT32, + number=9, + ) + include_query_predictions: bool = proto.Field( + proto.BOOL, + number=10, + ) + session_token: str = proto.Field( + proto.STRING, + number=11, + ) + include_pure_service_area_businesses: bool = proto.Field( + proto.BOOL, + number=12, + ) + + +class AutocompletePlacesResponse(proto.Message): + r"""Response proto for AutocompletePlaces. + + Attributes: + suggestions (MutableSequence[google.maps.places_v1.types.AutocompletePlacesResponse.Suggestion]): + Contains a list of suggestions, ordered in + descending order of relevance. + """ + + class Suggestion(proto.Message): + r"""An Autocomplete suggestion result. + + 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: + place_prediction (google.maps.places_v1.types.AutocompletePlacesResponse.Suggestion.PlacePrediction): + A prediction for a Place. + + This field is a member of `oneof`_ ``kind``. + query_prediction (google.maps.places_v1.types.AutocompletePlacesResponse.Suggestion.QueryPrediction): + A prediction for a query. + + This field is a member of `oneof`_ ``kind``. + """ + + class StringRange(proto.Message): + r"""Identifies a substring within a given text. + + Attributes: + start_offset (int): + Zero-based offset of the first Unicode + character of the string (inclusive). + end_offset (int): + Zero-based offset of the last Unicode + character (exclusive). + """ + + start_offset: int = proto.Field( + proto.INT32, + number=1, + ) + end_offset: int = proto.Field( + proto.INT32, + number=2, + ) + + class FormattableText(proto.Message): + r"""Text representing a Place or query prediction. The text may + be used as is or formatted. + + Attributes: + text (str): + Text that may be used as is or formatted with ``matches``. + matches (MutableSequence[google.maps.places_v1.types.AutocompletePlacesResponse.Suggestion.StringRange]): + A list of string ranges identifying where the input request + matched in ``text``. The ranges can be used to format + specific parts of ``text``. The substrings may not be exact + matches of ``input`` if the matching was determined by + criteria other than string matching (for example, spell + corrections or transliterations). + + These values are Unicode character offsets of ``text``. The + ranges are guaranteed to be ordered in increasing offset + values. + """ + + text: str = proto.Field( + proto.STRING, + number=1, + ) + matches: MutableSequence['AutocompletePlacesResponse.Suggestion.StringRange'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='AutocompletePlacesResponse.Suggestion.StringRange', + ) + + class StructuredFormat(proto.Message): + r"""Contains a breakdown of a Place or query prediction into main + text and secondary text. + + For Place predictions, the main text contains the specific name + of the Place. For query predictions, the main text contains the + query. + + The secondary text contains additional disambiguating features + (such as a city or region) to further identify the Place or + refine the query. + + Attributes: + main_text (google.maps.places_v1.types.AutocompletePlacesResponse.Suggestion.FormattableText): + Represents the name of the Place or query. + secondary_text (google.maps.places_v1.types.AutocompletePlacesResponse.Suggestion.FormattableText): + Represents additional disambiguating features + (such as a city or region) to further identify + the Place or refine the query. + """ + + main_text: 'AutocompletePlacesResponse.Suggestion.FormattableText' = proto.Field( + proto.MESSAGE, + number=1, + message='AutocompletePlacesResponse.Suggestion.FormattableText', + ) + secondary_text: 'AutocompletePlacesResponse.Suggestion.FormattableText' = proto.Field( + proto.MESSAGE, + number=2, + message='AutocompletePlacesResponse.Suggestion.FormattableText', + ) + + class PlacePrediction(proto.Message): + r"""Prediction results for a Place Autocomplete prediction. + + Attributes: + place (str): + The resource name of the suggested Place. + This name can be used in other APIs that accept + Place names. + place_id (str): + The unique identifier of the suggested Place. + This identifier can be used in other APIs that + accept Place IDs. + text (google.maps.places_v1.types.AutocompletePlacesResponse.Suggestion.FormattableText): + Contains the human-readable name for the returned result. + For establishment results, this is usually the business name + and address. + + ``text`` is recommended for developers who wish to show a + single UI element. Developers who wish to show two separate, + but related, UI elements may want to use + ``structured_format`` instead. They are two different ways + to represent a Place prediction. Users should not try to + parse ``structured_format`` into ``text`` or vice versa. + + This text may be different from the ``display_name`` + returned by GetPlace. + + May be in mixed languages if the request ``input`` and + ``language_code`` are in different languages or if the Place + does not have a translation from the local language to + ``language_code``. + structured_format (google.maps.places_v1.types.AutocompletePlacesResponse.Suggestion.StructuredFormat): + A breakdown of the Place prediction into main text + containing the name of the Place and secondary text + containing additional disambiguating features (such as a + city or region). + + ``structured_format`` is recommended for developers who wish + to show two separate, but related, UI elements. Developers + who wish to show a single UI element may want to use + ``text`` instead. They are two different ways to represent a + Place prediction. Users should not try to parse + ``structured_format`` into ``text`` or vice versa. + types (MutableSequence[str]): + List of types that apply to this Place from + Table A or Table B in + https://developers.google.com/maps/documentation/places/web-service/place-types. + + A type is a categorization of a Place. Places + with shared types will share similar + characteristics. + distance_meters (int): + The length of the geodesic in meters from ``origin`` if + ``origin`` is specified. Certain predictions such as routes + may not populate this field. + """ + + place: str = proto.Field( + proto.STRING, + number=1, + ) + place_id: str = proto.Field( + proto.STRING, + number=2, + ) + text: 'AutocompletePlacesResponse.Suggestion.FormattableText' = proto.Field( + proto.MESSAGE, + number=3, + message='AutocompletePlacesResponse.Suggestion.FormattableText', + ) + structured_format: 'AutocompletePlacesResponse.Suggestion.StructuredFormat' = proto.Field( + proto.MESSAGE, + number=4, + message='AutocompletePlacesResponse.Suggestion.StructuredFormat', + ) + types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + distance_meters: int = proto.Field( + proto.INT32, + number=6, + ) + + class QueryPrediction(proto.Message): + r"""Prediction results for a Query Autocomplete prediction. + + Attributes: + text (google.maps.places_v1.types.AutocompletePlacesResponse.Suggestion.FormattableText): + The predicted text. This text does not represent a Place, + but rather a text query that could be used in a search + endpoint (for example, Text Search). + + ``text`` is recommended for developers who wish to show a + single UI element. Developers who wish to show two separate, + but related, UI elements may want to use + ``structured_format`` instead. They are two different ways + to represent a query prediction. Users should not try to + parse ``structured_format`` into ``text`` or vice versa. + + May be in mixed languages if the request ``input`` and + ``language_code`` are in different languages or if part of + the query does not have a translation from the local + language to ``language_code``. + structured_format (google.maps.places_v1.types.AutocompletePlacesResponse.Suggestion.StructuredFormat): + A breakdown of the query prediction into main text + containing the query and secondary text containing + additional disambiguating features (such as a city or + region). + + ``structured_format`` is recommended for developers who wish + to show two separate, but related, UI elements. Developers + who wish to show a single UI element may want to use + ``text`` instead. They are two different ways to represent a + query prediction. Users should not try to parse + ``structured_format`` into ``text`` or vice versa. + """ + + text: 'AutocompletePlacesResponse.Suggestion.FormattableText' = proto.Field( + proto.MESSAGE, + number=1, + message='AutocompletePlacesResponse.Suggestion.FormattableText', + ) + structured_format: 'AutocompletePlacesResponse.Suggestion.StructuredFormat' = proto.Field( + proto.MESSAGE, + number=2, + message='AutocompletePlacesResponse.Suggestion.StructuredFormat', + ) + + place_prediction: 'AutocompletePlacesResponse.Suggestion.PlacePrediction' = proto.Field( + proto.MESSAGE, + number=1, + oneof='kind', + message='AutocompletePlacesResponse.Suggestion.PlacePrediction', + ) + query_prediction: 'AutocompletePlacesResponse.Suggestion.QueryPrediction' = proto.Field( + proto.MESSAGE, + number=2, + oneof='kind', + message='AutocompletePlacesResponse.Suggestion.QueryPrediction', + ) + + suggestions: MutableSequence[Suggestion] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=Suggestion, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/polyline.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/polyline.py new file mode 100644 index 000000000000..6c0ee26282c7 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/polyline.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.places.v1', + manifest={ + 'Polyline', + }, +) + + +class Polyline(proto.Message): + r"""A route polyline. Only supports an `encoded + polyline `__, + which can be passed as a string and includes compression with + minimal lossiness. This is the Routes API default output. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + encoded_polyline (str): + An `encoded + polyline `__, + as returned by the `Routes API by + default `__. + See the + `encoder `__ + and + `decoder `__ + tools. + + This field is a member of `oneof`_ ``polyline_type``. + """ + + encoded_polyline: str = proto.Field( + proto.STRING, + number=1, + oneof='polyline_type', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/price_range.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/price_range.py new file mode 100644 index 000000000000..597eaba8af64 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/price_range.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 money_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.places.v1', + manifest={ + 'PriceRange', + }, +) + + +class PriceRange(proto.Message): + r"""The price range associated with a Place. ``end_price`` could be + unset, which indicates a range without upper bound (e.g. "More than + $100"). + + Attributes: + start_price (google.type.money_pb2.Money): + The low end of the price range (inclusive). + Price should be at or above this amount. + end_price (google.type.money_pb2.Money): + The high end of the price range (exclusive). + Price should be lower than this amount. + """ + + start_price: money_pb2.Money = proto.Field( + proto.MESSAGE, + number=1, + message=money_pb2.Money, + ) + end_price: money_pb2.Money = proto.Field( + proto.MESSAGE, + number=2, + message=money_pb2.Money, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/reference.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/reference.py new file mode 100644 index 000000000000..5dee1df6fa73 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/reference.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.places_v1.types import review + + +__protobuf__ = proto.module( + package='google.maps.places.v1', + manifest={ + 'References', + }, +) + + +class References(proto.Message): + r"""Experimental: See + https://developers.google.com/maps/documentation/places/web-service/experimental/places-generative + for more details. + + Reference that the generative content is related to. + + Attributes: + reviews (MutableSequence[google.maps.places_v1.types.Review]): + Reviews that serve as references. + places (MutableSequence[str]): + The list of resource names of the referenced + places. This name can be used in other APIs that + accept Place resource names. + """ + + reviews: MutableSequence[review.Review] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=review.Review, + ) + places: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/review.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/review.py new file mode 100644 index 000000000000..96e161266398 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/review.py @@ -0,0 +1,94 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.places_v1.types import attribution +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import localized_text_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.places.v1', + manifest={ + 'Review', + }, +) + + +class Review(proto.Message): + r"""Information about a review of a place. + + Attributes: + name (str): + A reference representing this place review which may be used + to look up this place review again (also called the API + "resource" name: ``places/{place_id}/reviews/{review}``). + relative_publish_time_description (str): + A string of formatted recent time, expressing + the review time relative to the current time in + a form appropriate for the language and country. + text (google.type.localized_text_pb2.LocalizedText): + The localized text of the review. + original_text (google.type.localized_text_pb2.LocalizedText): + The review text in its original language. + rating (float): + A number between 1.0 and 5.0, also called the + number of stars. + author_attribution (google.maps.places_v1.types.AuthorAttribution): + This review's author. + publish_time (google.protobuf.timestamp_pb2.Timestamp): + Timestamp for the review. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + relative_publish_time_description: str = proto.Field( + proto.STRING, + number=2, + ) + text: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=9, + message=localized_text_pb2.LocalizedText, + ) + original_text: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=12, + message=localized_text_pb2.LocalizedText, + ) + rating: float = proto.Field( + proto.DOUBLE, + number=7, + ) + author_attribution: attribution.AuthorAttribution = proto.Field( + proto.MESSAGE, + number=13, + message=attribution.AuthorAttribution, + ) + publish_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=14, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/route_modifiers.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/route_modifiers.py new file mode 100644 index 000000000000..8ad10991ebd9 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/route_modifiers.py @@ -0,0 +1,76 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.places.v1', + manifest={ + 'RouteModifiers', + }, +) + + +class RouteModifiers(proto.Message): + r"""Encapsulates a set of optional conditions to satisfy when + calculating the routes. + + Attributes: + avoid_tolls (bool): + Optional. When set to true, avoids toll roads where + reasonable, giving preference to routes not containing toll + roads. Applies only to the ``DRIVE`` and ``TWO_WHEELER`` + [``TravelMode``][google.maps.places.v1.TravelMode]. + avoid_highways (bool): + Optional. When set to true, avoids highways where + reasonable, giving preference to routes not containing + highways. Applies only to the ``DRIVE`` and ``TWO_WHEELER`` + [``TravelMode``][google.maps.places.v1.TravelMode]. + avoid_ferries (bool): + Optional. When set to true, avoids ferries where reasonable, + giving preference to routes not containing ferries. Applies + only to the ``DRIVE`` and ``TWO_WHEELER`` + [``TravelMode``][google.maps.places.v1.TravelMode]. + avoid_indoor (bool): + Optional. When set to true, avoids navigating indoors where + reasonable, giving preference to routes not containing + indoor navigation. Applies only to the ``WALK`` + [``TravelMode``][google.maps.places.v1.TravelMode]. + """ + + avoid_tolls: bool = proto.Field( + proto.BOOL, + number=1, + ) + avoid_highways: bool = proto.Field( + proto.BOOL, + number=2, + ) + avoid_ferries: bool = proto.Field( + proto.BOOL, + number=3, + ) + avoid_indoor: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/routing_preference.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/routing_preference.py new file mode 100644 index 000000000000..56db65ad4e2a --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/routing_preference.py @@ -0,0 +1,71 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.places.v1', + manifest={ + 'RoutingPreference', + }, +) + + +class RoutingPreference(proto.Enum): + r"""A set of values that specify factors to take into + consideration when calculating the route. + + Values: + ROUTING_PREFERENCE_UNSPECIFIED (0): + No routing preference specified. Default to + ``TRAFFIC_UNAWARE``. + TRAFFIC_UNAWARE (1): + Computes routes without taking live traffic conditions into + consideration. Suitable when traffic conditions don't matter + or are not applicable. Using this value produces the lowest + latency. Note: For + [``TravelMode``][google.maps.places.v1.TravelMode] ``DRIVE`` + and ``TWO_WHEELER``, the route and duration chosen are based + on road network and average time-independent traffic + conditions, not current road conditions. Consequently, + routes may include roads that are temporarily closed. + Results for a given request may vary over time due to + changes in the road network, updated average traffic + conditions, and the distributed nature of the service. + Results may also vary between nearly-equivalent routes at + any time or frequency. + TRAFFIC_AWARE (2): + Calculates routes taking live traffic conditions into + consideration. In contrast to ``TRAFFIC_AWARE_OPTIMAL``, + some optimizations are applied to significantly reduce + latency. + TRAFFIC_AWARE_OPTIMAL (3): + Calculates the routes taking live traffic + conditions into consideration, without applying + most performance optimizations. Using this value + produces the highest latency. + """ + ROUTING_PREFERENCE_UNSPECIFIED = 0 + TRAFFIC_UNAWARE = 1 + TRAFFIC_AWARE = 2 + TRAFFIC_AWARE_OPTIMAL = 3 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/routing_summary.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/routing_summary.py new file mode 100644 index 000000000000..741e004f7541 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/routing_summary.py @@ -0,0 +1,95 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 duration_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.places.v1', + manifest={ + 'RoutingSummary', + }, +) + + +class RoutingSummary(proto.Message): + r"""The duration and distance from the routing origin to a place in the + response, and a second leg from that place to the destination, if + requested. **Note:** Adding ``routingSummaries`` in the field mask + without also including either the ``routingParameters.origin`` + parameter or the + ``searchAlongRouteParameters.polyline.encodedPolyline`` parameter in + the request causes an error. + + Attributes: + legs (MutableSequence[google.maps.places_v1.types.RoutingSummary.Leg]): + The legs of the trip. + + When you calculate travel duration and distance from a set + origin, ``legs`` contains a single leg containing the + duration and distance from the origin to the destination. + When you do a search along route, ``legs`` contains two + legs: one from the origin to place, and one from the place + to the destination. + directions_uri (str): + A link to show directions on Google Maps using the waypoints + from the given routing summary. The route generated by this + link is not guaranteed to be the same as the route used to + generate the routing summary. The link uses information + provided in the request, from fields including + ``routingParameters`` and ``searchAlongRouteParameters`` + when applicable, to generate the directions link. + """ + + class Leg(proto.Message): + r"""A leg is a single portion of a journey from one location to + another. + + Attributes: + duration (google.protobuf.duration_pb2.Duration): + The time it takes to complete this leg of the + trip. + distance_meters (int): + The distance of this leg of the trip. + """ + + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + distance_meters: int = proto.Field( + proto.INT32, + number=2, + ) + + legs: MutableSequence[Leg] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=Leg, + ) + directions_uri: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/travel_mode.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/travel_mode.py new file mode 100644 index 000000000000..270ba1245921 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/travel_mode.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.places.v1', + manifest={ + 'TravelMode', + }, +) + + +class TravelMode(proto.Enum): + r"""Travel mode options. These options map to what `Routes API + offers `__. + + Values: + TRAVEL_MODE_UNSPECIFIED (0): + No travel mode specified. Defaults to ``DRIVE``. + DRIVE (1): + Travel by passenger car. + BICYCLE (2): + Travel by bicycle. Not supported with + ``search_along_route_parameters``. + WALK (3): + Travel by walking. Not supported with + ``search_along_route_parameters``. + TWO_WHEELER (4): + Motorized two wheeled vehicles of all kinds such as scooters + and motorcycles. Note that this is distinct from the + ``BICYCLE`` travel mode which covers human-powered + transport. Not supported with + ``search_along_route_parameters``. Only supported in those + countries listed at `Countries and regions supported for + two-wheeled + vehicles `__. + """ + TRAVEL_MODE_UNSPECIFIED = 0 + DRIVE = 1 + BICYCLE = 2 + WALK = 3 + TWO_WHEELER = 4 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/mypy.ini b/owl-bot-staging/google-maps-places/v1/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-maps-places/v1/noxfile.py b/owl-bot-staging/google-maps-places/v1/noxfile.py new file mode 100644 index 000000000000..ef3066e9ef06 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/noxfile.py @@ -0,0 +1,280 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = 'google-maps-places' + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.13" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "prerelease_deps", +] + +@nox.session(python=ALL_PYTHON) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def unit(session, protobuf_implementation): + """Run the unit test suite.""" + + 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+") + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") + + # 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") + + session.run( + 'py.test', + '--quiet', + '--cov=google/maps/places_v1/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)), + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + +@nox.session(python=ALL_PYTHON[-1]) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def prerelease_deps(session, protobuf_implementation): + """Run the unit test suite against pre-release versions of dependencies.""" + + 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 test environment dependencies + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + + # Install the package without dependencies + session.install('-e', '.', '--no-deps') + + # We test the minimum dependency versions using the minimum Python + # version so the lowest python runtime that we test has a corresponding constraints + # file, located at `testing/constraints--.txt`, which contains all of the + # 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 + ) + ] + + session.install(*constraints_deps) + + prerel_deps = [ + "googleapis-common-protos", + "google-api-core", + "google-auth", + # Exclude grpcio!=1.67.0rc1 which does not support python 3.13 + "grpcio!=1.67.0rc1", + "grpcio-status", + "protobuf", + "proto-plus", + ] + + for dep in prerel_deps: + session.install("--pre", "--no-deps", "--upgrade", dep) + + # Remaining dependencies + other_deps = [ + "requests", + ] + session.install(*other_deps) + + # Print out prerelease package versions + + session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") + session.run("python", "-c", "import google.auth; print(google.auth.__version__)") + session.run("python", "-c", "import grpc; print(grpc.__version__)") + session.run( + "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" + ) + session.run( + "python", "-c", "import proto; print(proto.__version__)" + ) + + session.run( + 'py.test', + '--quiet', + '--cov=google/maps/places_v1/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)), + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + + +@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=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 docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==7.0.1", "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=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", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) diff --git a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_autocomplete_places_async.py b/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_autocomplete_places_async.py new file mode 100644 index 000000000000..abd008c9c11a --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_autocomplete_places_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AutocompletePlaces +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-places + + +# [START places_v1_generated_Places_AutocompletePlaces_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.maps import places_v1 + + +async def sample_autocomplete_places(): + # Create a client + client = places_v1.PlacesAsyncClient() + + # Initialize request argument(s) + request = places_v1.AutocompletePlacesRequest( + input="input_value", + ) + + # Make the request + response = await client.autocomplete_places(request=request) + + # Handle the response + print(response) + +# [END places_v1_generated_Places_AutocompletePlaces_async] diff --git a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_autocomplete_places_sync.py b/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_autocomplete_places_sync.py new file mode 100644 index 000000000000..cf942b606419 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_autocomplete_places_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AutocompletePlaces +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-places + + +# [START places_v1_generated_Places_AutocompletePlaces_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.maps import places_v1 + + +def sample_autocomplete_places(): + # Create a client + client = places_v1.PlacesClient() + + # Initialize request argument(s) + request = places_v1.AutocompletePlacesRequest( + input="input_value", + ) + + # Make the request + response = client.autocomplete_places(request=request) + + # Handle the response + print(response) + +# [END places_v1_generated_Places_AutocompletePlaces_sync] diff --git a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_photo_media_async.py b/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_photo_media_async.py new file mode 100644 index 000000000000..45461ad3fabb --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_photo_media_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetPhotoMedia +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-places + + +# [START places_v1_generated_Places_GetPhotoMedia_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.maps import places_v1 + + +async def sample_get_photo_media(): + # Create a client + client = places_v1.PlacesAsyncClient() + + # Initialize request argument(s) + request = places_v1.GetPhotoMediaRequest( + name="name_value", + ) + + # Make the request + response = await client.get_photo_media(request=request) + + # Handle the response + print(response) + +# [END places_v1_generated_Places_GetPhotoMedia_async] diff --git a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_photo_media_sync.py b/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_photo_media_sync.py new file mode 100644 index 000000000000..3f76e66b03dc --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_photo_media_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetPhotoMedia +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-places + + +# [START places_v1_generated_Places_GetPhotoMedia_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.maps import places_v1 + + +def sample_get_photo_media(): + # Create a client + client = places_v1.PlacesClient() + + # Initialize request argument(s) + request = places_v1.GetPhotoMediaRequest( + name="name_value", + ) + + # Make the request + response = client.get_photo_media(request=request) + + # Handle the response + print(response) + +# [END places_v1_generated_Places_GetPhotoMedia_sync] diff --git a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_place_async.py b/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_place_async.py new file mode 100644 index 000000000000..405094ecdc49 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_place_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetPlace +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-places + + +# [START places_v1_generated_Places_GetPlace_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.maps import places_v1 + + +async def sample_get_place(): + # Create a client + client = places_v1.PlacesAsyncClient() + + # Initialize request argument(s) + request = places_v1.GetPlaceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_place(request=request) + + # Handle the response + print(response) + +# [END places_v1_generated_Places_GetPlace_async] diff --git a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_place_sync.py b/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_place_sync.py new file mode 100644 index 000000000000..8f06103be971 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_place_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetPlace +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-places + + +# [START places_v1_generated_Places_GetPlace_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.maps import places_v1 + + +def sample_get_place(): + # Create a client + client = places_v1.PlacesClient() + + # Initialize request argument(s) + request = places_v1.GetPlaceRequest( + name="name_value", + ) + + # Make the request + response = client.get_place(request=request) + + # Handle the response + print(response) + +# [END places_v1_generated_Places_GetPlace_sync] diff --git a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_nearby_async.py b/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_nearby_async.py new file mode 100644 index 000000000000..ea224ebeb855 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_nearby_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SearchNearby +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-places + + +# [START places_v1_generated_Places_SearchNearby_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.maps import places_v1 + + +async def sample_search_nearby(): + # Create a client + client = places_v1.PlacesAsyncClient() + + # Initialize request argument(s) + location_restriction = places_v1.LocationRestriction() + location_restriction.circle.radius = 0.648 + + request = places_v1.SearchNearbyRequest( + location_restriction=location_restriction, + ) + + # Make the request + response = await client.search_nearby(request=request) + + # Handle the response + print(response) + +# [END places_v1_generated_Places_SearchNearby_async] diff --git a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_nearby_sync.py b/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_nearby_sync.py new file mode 100644 index 000000000000..777bbc051f7f --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_nearby_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SearchNearby +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-places + + +# [START places_v1_generated_Places_SearchNearby_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.maps import places_v1 + + +def sample_search_nearby(): + # Create a client + client = places_v1.PlacesClient() + + # Initialize request argument(s) + location_restriction = places_v1.LocationRestriction() + location_restriction.circle.radius = 0.648 + + request = places_v1.SearchNearbyRequest( + location_restriction=location_restriction, + ) + + # Make the request + response = client.search_nearby(request=request) + + # Handle the response + print(response) + +# [END places_v1_generated_Places_SearchNearby_sync] diff --git a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_text_async.py b/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_text_async.py new file mode 100644 index 000000000000..5f4b02670755 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_text_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SearchText +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-places + + +# [START places_v1_generated_Places_SearchText_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.maps import places_v1 + + +async def sample_search_text(): + # Create a client + client = places_v1.PlacesAsyncClient() + + # Initialize request argument(s) + request = places_v1.SearchTextRequest( + text_query="text_query_value", + ) + + # Make the request + response = await client.search_text(request=request) + + # Handle the response + print(response) + +# [END places_v1_generated_Places_SearchText_async] diff --git a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_text_sync.py b/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_text_sync.py new file mode 100644 index 000000000000..fc156bc302cd --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_text_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SearchText +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-places + + +# [START places_v1_generated_Places_SearchText_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.maps import places_v1 + + +def sample_search_text(): + # Create a client + client = places_v1.PlacesClient() + + # Initialize request argument(s) + request = places_v1.SearchTextRequest( + text_query="text_query_value", + ) + + # Make the request + response = client.search_text(request=request) + + # Handle the response + print(response) + +# [END places_v1_generated_Places_SearchText_sync] diff --git a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/snippet_metadata_google.maps.places.v1.json b/owl-bot-staging/google-maps-places/v1/samples/generated_samples/snippet_metadata_google.maps.places.v1.json new file mode 100644 index 000000000000..bea29a42b294 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/samples/generated_samples/snippet_metadata_google.maps.places.v1.json @@ -0,0 +1,796 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.maps.places.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-maps-places", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.places_v1.PlacesAsyncClient", + "shortName": "PlacesAsyncClient" + }, + "fullName": "google.maps.places_v1.PlacesAsyncClient.autocomplete_places", + "method": { + "fullName": "google.maps.places.v1.Places.AutocompletePlaces", + "service": { + "fullName": "google.maps.places.v1.Places", + "shortName": "Places" + }, + "shortName": "AutocompletePlaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.places_v1.types.AutocompletePlacesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.maps.places_v1.types.AutocompletePlacesResponse", + "shortName": "autocomplete_places" + }, + "description": "Sample for AutocompletePlaces", + "file": "places_v1_generated_places_autocomplete_places_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "places_v1_generated_Places_AutocompletePlaces_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": "places_v1_generated_places_autocomplete_places_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.places_v1.PlacesClient", + "shortName": "PlacesClient" + }, + "fullName": "google.maps.places_v1.PlacesClient.autocomplete_places", + "method": { + "fullName": "google.maps.places.v1.Places.AutocompletePlaces", + "service": { + "fullName": "google.maps.places.v1.Places", + "shortName": "Places" + }, + "shortName": "AutocompletePlaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.places_v1.types.AutocompletePlacesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.maps.places_v1.types.AutocompletePlacesResponse", + "shortName": "autocomplete_places" + }, + "description": "Sample for AutocompletePlaces", + "file": "places_v1_generated_places_autocomplete_places_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "places_v1_generated_Places_AutocompletePlaces_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": "places_v1_generated_places_autocomplete_places_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.places_v1.PlacesAsyncClient", + "shortName": "PlacesAsyncClient" + }, + "fullName": "google.maps.places_v1.PlacesAsyncClient.get_photo_media", + "method": { + "fullName": "google.maps.places.v1.Places.GetPhotoMedia", + "service": { + "fullName": "google.maps.places.v1.Places", + "shortName": "Places" + }, + "shortName": "GetPhotoMedia" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.places_v1.types.GetPhotoMediaRequest" + }, + { + "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.maps.places_v1.types.PhotoMedia", + "shortName": "get_photo_media" + }, + "description": "Sample for GetPhotoMedia", + "file": "places_v1_generated_places_get_photo_media_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "places_v1_generated_Places_GetPhotoMedia_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": "places_v1_generated_places_get_photo_media_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.places_v1.PlacesClient", + "shortName": "PlacesClient" + }, + "fullName": "google.maps.places_v1.PlacesClient.get_photo_media", + "method": { + "fullName": "google.maps.places.v1.Places.GetPhotoMedia", + "service": { + "fullName": "google.maps.places.v1.Places", + "shortName": "Places" + }, + "shortName": "GetPhotoMedia" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.places_v1.types.GetPhotoMediaRequest" + }, + { + "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.maps.places_v1.types.PhotoMedia", + "shortName": "get_photo_media" + }, + "description": "Sample for GetPhotoMedia", + "file": "places_v1_generated_places_get_photo_media_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "places_v1_generated_Places_GetPhotoMedia_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": "places_v1_generated_places_get_photo_media_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.places_v1.PlacesAsyncClient", + "shortName": "PlacesAsyncClient" + }, + "fullName": "google.maps.places_v1.PlacesAsyncClient.get_place", + "method": { + "fullName": "google.maps.places.v1.Places.GetPlace", + "service": { + "fullName": "google.maps.places.v1.Places", + "shortName": "Places" + }, + "shortName": "GetPlace" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.places_v1.types.GetPlaceRequest" + }, + { + "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.maps.places_v1.types.Place", + "shortName": "get_place" + }, + "description": "Sample for GetPlace", + "file": "places_v1_generated_places_get_place_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "places_v1_generated_Places_GetPlace_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": "places_v1_generated_places_get_place_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.places_v1.PlacesClient", + "shortName": "PlacesClient" + }, + "fullName": "google.maps.places_v1.PlacesClient.get_place", + "method": { + "fullName": "google.maps.places.v1.Places.GetPlace", + "service": { + "fullName": "google.maps.places.v1.Places", + "shortName": "Places" + }, + "shortName": "GetPlace" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.places_v1.types.GetPlaceRequest" + }, + { + "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.maps.places_v1.types.Place", + "shortName": "get_place" + }, + "description": "Sample for GetPlace", + "file": "places_v1_generated_places_get_place_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "places_v1_generated_Places_GetPlace_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": "places_v1_generated_places_get_place_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.places_v1.PlacesAsyncClient", + "shortName": "PlacesAsyncClient" + }, + "fullName": "google.maps.places_v1.PlacesAsyncClient.search_nearby", + "method": { + "fullName": "google.maps.places.v1.Places.SearchNearby", + "service": { + "fullName": "google.maps.places.v1.Places", + "shortName": "Places" + }, + "shortName": "SearchNearby" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.places_v1.types.SearchNearbyRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.maps.places_v1.types.SearchNearbyResponse", + "shortName": "search_nearby" + }, + "description": "Sample for SearchNearby", + "file": "places_v1_generated_places_search_nearby_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "places_v1_generated_Places_SearchNearby_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": "places_v1_generated_places_search_nearby_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.places_v1.PlacesClient", + "shortName": "PlacesClient" + }, + "fullName": "google.maps.places_v1.PlacesClient.search_nearby", + "method": { + "fullName": "google.maps.places.v1.Places.SearchNearby", + "service": { + "fullName": "google.maps.places.v1.Places", + "shortName": "Places" + }, + "shortName": "SearchNearby" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.places_v1.types.SearchNearbyRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.maps.places_v1.types.SearchNearbyResponse", + "shortName": "search_nearby" + }, + "description": "Sample for SearchNearby", + "file": "places_v1_generated_places_search_nearby_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "places_v1_generated_Places_SearchNearby_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": "places_v1_generated_places_search_nearby_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.places_v1.PlacesAsyncClient", + "shortName": "PlacesAsyncClient" + }, + "fullName": "google.maps.places_v1.PlacesAsyncClient.search_text", + "method": { + "fullName": "google.maps.places.v1.Places.SearchText", + "service": { + "fullName": "google.maps.places.v1.Places", + "shortName": "Places" + }, + "shortName": "SearchText" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.places_v1.types.SearchTextRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.maps.places_v1.types.SearchTextResponse", + "shortName": "search_text" + }, + "description": "Sample for SearchText", + "file": "places_v1_generated_places_search_text_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "places_v1_generated_Places_SearchText_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": "places_v1_generated_places_search_text_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.places_v1.PlacesClient", + "shortName": "PlacesClient" + }, + "fullName": "google.maps.places_v1.PlacesClient.search_text", + "method": { + "fullName": "google.maps.places.v1.Places.SearchText", + "service": { + "fullName": "google.maps.places.v1.Places", + "shortName": "Places" + }, + "shortName": "SearchText" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.places_v1.types.SearchTextRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.maps.places_v1.types.SearchTextResponse", + "shortName": "search_text" + }, + "description": "Sample for SearchText", + "file": "places_v1_generated_places_search_text_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "places_v1_generated_Places_SearchText_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": "places_v1_generated_places_search_text_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-maps-places/v1/scripts/fixup_places_v1_keywords.py b/owl-bot-staging/google-maps-places/v1/scripts/fixup_places_v1_keywords.py new file mode 100644 index 000000000000..c1c498261a9a --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/scripts/fixup_places_v1_keywords.py @@ -0,0 +1,180 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 placesCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'autocomplete_places': ('input', 'location_bias', 'location_restriction', 'included_primary_types', 'included_region_codes', 'language_code', 'region_code', 'origin', 'input_offset', 'include_query_predictions', 'session_token', 'include_pure_service_area_businesses', ), + 'get_photo_media': ('name', 'max_width_px', 'max_height_px', 'skip_http_redirect', ), + 'get_place': ('name', 'language_code', 'region_code', 'session_token', ), + 'search_nearby': ('location_restriction', 'language_code', 'region_code', 'included_types', 'excluded_types', 'included_primary_types', 'excluded_primary_types', 'max_result_count', 'rank_preference', 'routing_parameters', ), + 'search_text': ('text_query', 'language_code', 'region_code', 'rank_preference', 'included_type', 'open_now', 'min_rating', 'max_result_count', 'price_levels', 'strict_type_filtering', 'location_bias', 'location_restriction', 'ev_options', 'routing_parameters', 'search_along_route_parameters', 'include_pure_service_area_businesses', ), + } + + 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=placesCallTransformer(), +): + """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 places 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-maps-places/v1/setup.py b/owl-bot-staging/google-maps-places/v1/setup.py new file mode 100644 index 000000000000..90538f3b071c --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/setup.py @@ -0,0 +1,99 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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-maps-places' + + +description = "Google Maps Places API client library" + +version = None + +with open(os.path.join(package_root, 'google/maps/places/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.0dev,!=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.0dev,!=2.24.0,!=2.25.0", + "proto-plus >= 1.22.3, <2.0.0dev", + "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'", + "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", + "google-geo-type >= 0.1.0, <1.0.0dev", +] +extras = { +} +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-places" + +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-maps-places/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-maps-places/v1/testing/constraints-3.10.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-places/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-geo-type diff --git a/owl-bot-staging/google-maps-places/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-maps-places/v1/testing/constraints-3.11.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-places/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-geo-type diff --git a/owl-bot-staging/google-maps-places/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-maps-places/v1/testing/constraints-3.12.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-places/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-geo-type diff --git a/owl-bot-staging/google-maps-places/v1/testing/constraints-3.13.txt b/owl-bot-staging/google-maps-places/v1/testing/constraints-3.13.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/testing/constraints-3.13.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-geo-type diff --git a/owl-bot-staging/google-maps-places/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-maps-places/v1/testing/constraints-3.7.txt new file mode 100644 index 000000000000..277853c664a0 --- /dev/null +++ b/owl-bot-staging/google-maps-places/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.0dev", +# 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-geo-type==0.1.0 diff --git a/owl-bot-staging/google-maps-places/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-maps-places/v1/testing/constraints-3.8.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-places/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-geo-type diff --git a/owl-bot-staging/google-maps-places/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-maps-places/v1/testing/constraints-3.9.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-places/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-geo-type diff --git a/owl-bot-staging/google-maps-places/v1/tests/__init__.py b/owl-bot-staging/google-maps-places/v1/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-maps-places/v1/tests/unit/__init__.py b/owl-bot-staging/google-maps-places/v1/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-maps-places/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-maps-places/v1/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-maps-places/v1/tests/unit/gapic/places_v1/__init__.py b/owl-bot-staging/google-maps-places/v1/tests/unit/gapic/places_v1/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/tests/unit/gapic/places_v1/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-maps-places/v1/tests/unit/gapic/places_v1/test_places.py b/owl-bot-staging/google-maps-places/v1/tests/unit/gapic/places_v1/test_places.py new file mode 100644 index 000000000000..2020fff86e8d --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/tests/unit/gapic/places_v1/test_places.py @@ -0,0 +1,4467 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.geo.type.types import viewport +from google.maps.places_v1.services.places import PlacesAsyncClient +from google.maps.places_v1.services.places import PlacesClient +from google.maps.places_v1.services.places import transports +from google.maps.places_v1.types import contextual_content +from google.maps.places_v1.types import ev_charging +from google.maps.places_v1.types import fuel_options +from google.maps.places_v1.types import geometry +from google.maps.places_v1.types import photo +from google.maps.places_v1.types import place +from google.maps.places_v1.types import places_service +from google.maps.places_v1.types import polyline +from google.maps.places_v1.types import price_range +from google.maps.places_v1.types import review +from google.maps.places_v1.types import route_modifiers +from google.maps.places_v1.types import routing_preference +from google.maps.places_v1.types import routing_summary +from google.maps.places_v1.types import travel_mode +from google.oauth2 import service_account +from google.type import latlng_pb2 # type: ignore +from google.type import localized_text_pb2 # type: ignore +import google.auth + + +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 PlacesClient._get_default_mtls_endpoint(None) is None + assert PlacesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert PlacesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert PlacesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert PlacesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert PlacesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert PlacesClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert PlacesClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert PlacesClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + PlacesClient._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 PlacesClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert PlacesClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert PlacesClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + PlacesClient._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 PlacesClient._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 PlacesClient._get_client_cert_source(None, False) is None + assert PlacesClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert PlacesClient._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 PlacesClient._get_client_cert_source(None, True) is mock_default_cert_source + assert PlacesClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(PlacesClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PlacesClient)) +@mock.patch.object(PlacesAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PlacesAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = PlacesClient._DEFAULT_UNIVERSE + default_endpoint = PlacesClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = PlacesClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert PlacesClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert PlacesClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == PlacesClient.DEFAULT_MTLS_ENDPOINT + assert PlacesClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert PlacesClient._get_api_endpoint(None, None, default_universe, "always") == PlacesClient.DEFAULT_MTLS_ENDPOINT + assert PlacesClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == PlacesClient.DEFAULT_MTLS_ENDPOINT + assert PlacesClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert PlacesClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + PlacesClient._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 PlacesClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert PlacesClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert PlacesClient._get_universe_domain(None, None) == PlacesClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + PlacesClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize("client_class,transport_name", [ + (PlacesClient, "grpc"), + (PlacesAsyncClient, "grpc_asyncio"), + (PlacesClient, "rest"), +]) +def test_places_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 == ( + 'places.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://places.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.PlacesGrpcTransport, "grpc"), + (transports.PlacesGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.PlacesRestTransport, "rest"), +]) +def test_places_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", [ + (PlacesClient, "grpc"), + (PlacesAsyncClient, "grpc_asyncio"), + (PlacesClient, "rest"), +]) +def test_places_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 == ( + 'places.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://places.googleapis.com' + ) + + +def test_places_client_get_transport_class(): + transport = PlacesClient.get_transport_class() + available_transports = [ + transports.PlacesGrpcTransport, + transports.PlacesRestTransport, + ] + assert transport in available_transports + + transport = PlacesClient.get_transport_class("grpc") + assert transport == transports.PlacesGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (PlacesClient, transports.PlacesGrpcTransport, "grpc"), + (PlacesAsyncClient, transports.PlacesGrpcAsyncIOTransport, "grpc_asyncio"), + (PlacesClient, transports.PlacesRestTransport, "rest"), +]) +@mock.patch.object(PlacesClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PlacesClient)) +@mock.patch.object(PlacesAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PlacesAsyncClient)) +def test_places_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(PlacesClient, '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(PlacesClient, '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", [ + (PlacesClient, transports.PlacesGrpcTransport, "grpc", "true"), + (PlacesAsyncClient, transports.PlacesGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (PlacesClient, transports.PlacesGrpcTransport, "grpc", "false"), + (PlacesAsyncClient, transports.PlacesGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (PlacesClient, transports.PlacesRestTransport, "rest", "true"), + (PlacesClient, transports.PlacesRestTransport, "rest", "false"), +]) +@mock.patch.object(PlacesClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PlacesClient)) +@mock.patch.object(PlacesAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PlacesAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_places_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", [ + PlacesClient, PlacesAsyncClient +]) +@mock.patch.object(PlacesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PlacesClient)) +@mock.patch.object(PlacesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PlacesAsyncClient)) +def test_places_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", [ + PlacesClient, PlacesAsyncClient +]) +@mock.patch.object(PlacesClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PlacesClient)) +@mock.patch.object(PlacesAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PlacesAsyncClient)) +def test_places_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = PlacesClient._DEFAULT_UNIVERSE + default_endpoint = PlacesClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = PlacesClient._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", [ + (PlacesClient, transports.PlacesGrpcTransport, "grpc"), + (PlacesAsyncClient, transports.PlacesGrpcAsyncIOTransport, "grpc_asyncio"), + (PlacesClient, transports.PlacesRestTransport, "rest"), +]) +def test_places_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", [ + (PlacesClient, transports.PlacesGrpcTransport, "grpc", grpc_helpers), + (PlacesAsyncClient, transports.PlacesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (PlacesClient, transports.PlacesRestTransport, "rest", None), +]) +def test_places_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_places_client_client_options_from_dict(): + with mock.patch('google.maps.places_v1.services.places.transports.PlacesGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = PlacesClient( + 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", [ + (PlacesClient, transports.PlacesGrpcTransport, "grpc", grpc_helpers), + (PlacesAsyncClient, transports.PlacesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_places_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( + "places.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( +), + scopes=None, + default_host="places.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + places_service.SearchNearbyRequest, + dict, +]) +def test_search_nearby(request_type, transport: str = 'grpc'): + client = PlacesClient( + 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.search_nearby), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = places_service.SearchNearbyResponse( + ) + response = client.search_nearby(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = places_service.SearchNearbyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, places_service.SearchNearbyResponse) + + +def test_search_nearby_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 = PlacesClient( + 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 = places_service.SearchNearbyRequest( + language_code='language_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.search_nearby), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.search_nearby(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == places_service.SearchNearbyRequest( + language_code='language_code_value', + region_code='region_code_value', + ) + +def test_search_nearby_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = PlacesClient( + 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.search_nearby in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.search_nearby] = mock_rpc + request = {} + client.search_nearby(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.search_nearby(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_search_nearby_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = PlacesAsyncClient( + 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.search_nearby in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.search_nearby] = mock_rpc + + request = {} + await client.search_nearby(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.search_nearby(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_search_nearby_async(transport: str = 'grpc_asyncio', request_type=places_service.SearchNearbyRequest): + client = PlacesAsyncClient( + 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.search_nearby), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(places_service.SearchNearbyResponse( + )) + response = await client.search_nearby(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = places_service.SearchNearbyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, places_service.SearchNearbyResponse) + + +@pytest.mark.asyncio +async def test_search_nearby_async_from_dict(): + await test_search_nearby_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + places_service.SearchTextRequest, + dict, +]) +def test_search_text(request_type, transport: str = 'grpc'): + client = PlacesClient( + 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.search_text), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = places_service.SearchTextResponse( + ) + response = client.search_text(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = places_service.SearchTextRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, places_service.SearchTextResponse) + + +def test_search_text_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 = PlacesClient( + 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 = places_service.SearchTextRequest( + text_query='text_query_value', + language_code='language_code_value', + region_code='region_code_value', + included_type='included_type_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_text), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.search_text(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == places_service.SearchTextRequest( + text_query='text_query_value', + language_code='language_code_value', + region_code='region_code_value', + included_type='included_type_value', + ) + +def test_search_text_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = PlacesClient( + 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.search_text in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.search_text] = mock_rpc + request = {} + client.search_text(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.search_text(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_search_text_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = PlacesAsyncClient( + 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.search_text in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.search_text] = mock_rpc + + request = {} + await client.search_text(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.search_text(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_search_text_async(transport: str = 'grpc_asyncio', request_type=places_service.SearchTextRequest): + client = PlacesAsyncClient( + 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.search_text), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(places_service.SearchTextResponse( + )) + response = await client.search_text(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = places_service.SearchTextRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, places_service.SearchTextResponse) + + +@pytest.mark.asyncio +async def test_search_text_async_from_dict(): + await test_search_text_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + places_service.GetPhotoMediaRequest, + dict, +]) +def test_get_photo_media(request_type, transport: str = 'grpc'): + client = PlacesClient( + 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_photo_media), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = places_service.PhotoMedia( + name='name_value', + photo_uri='photo_uri_value', + ) + response = client.get_photo_media(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = places_service.GetPhotoMediaRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, places_service.PhotoMedia) + assert response.name == 'name_value' + assert response.photo_uri == 'photo_uri_value' + + +def test_get_photo_media_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 = PlacesClient( + 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 = places_service.GetPhotoMediaRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_photo_media), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_photo_media(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == places_service.GetPhotoMediaRequest( + name='name_value', + ) + +def test_get_photo_media_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = PlacesClient( + 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_photo_media in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_photo_media] = mock_rpc + request = {} + client.get_photo_media(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_photo_media(request) + + # Establish that a new wrapper 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_photo_media_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = PlacesAsyncClient( + 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_photo_media in client._client._transport._wrapped_methods + + # 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_photo_media] = mock_rpc + + request = {} + await client.get_photo_media(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_photo_media(request) + + # Establish that a new wrapper 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_photo_media_async(transport: str = 'grpc_asyncio', request_type=places_service.GetPhotoMediaRequest): + client = PlacesAsyncClient( + 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_photo_media), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(places_service.PhotoMedia( + name='name_value', + photo_uri='photo_uri_value', + )) + response = await client.get_photo_media(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = places_service.GetPhotoMediaRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, places_service.PhotoMedia) + assert response.name == 'name_value' + assert response.photo_uri == 'photo_uri_value' + + +@pytest.mark.asyncio +async def test_get_photo_media_async_from_dict(): + await test_get_photo_media_async(request_type=dict) + +def test_get_photo_media_field_headers(): + client = PlacesClient( + 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 = places_service.GetPhotoMediaRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_photo_media), + '__call__') as call: + call.return_value = places_service.PhotoMedia() + client.get_photo_media(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_photo_media_field_headers_async(): + client = PlacesAsyncClient( + 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 = places_service.GetPhotoMediaRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_photo_media), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(places_service.PhotoMedia()) + await client.get_photo_media(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_photo_media_flattened(): + client = PlacesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_photo_media), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = places_service.PhotoMedia() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_photo_media( + 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_photo_media_flattened_error(): + client = PlacesClient( + 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_photo_media( + places_service.GetPhotoMediaRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_photo_media_flattened_async(): + client = PlacesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_photo_media), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = places_service.PhotoMedia() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(places_service.PhotoMedia()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_photo_media( + 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_photo_media_flattened_error_async(): + client = PlacesAsyncClient( + 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_photo_media( + places_service.GetPhotoMediaRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + places_service.GetPlaceRequest, + dict, +]) +def test_get_place(request_type, transport: str = 'grpc'): + client = PlacesClient( + 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_place), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = place.Place( + name='name_value', + id='id_value', + types=['types_value'], + primary_type='primary_type_value', + national_phone_number='national_phone_number_value', + international_phone_number='international_phone_number_value', + formatted_address='formatted_address_value', + short_formatted_address='short_formatted_address_value', + rating=0.645, + google_maps_uri='google_maps_uri_value', + website_uri='website_uri_value', + utc_offset_minutes=1942, + adr_format_address='adr_format_address_value', + business_status=place.Place.BusinessStatus.OPERATIONAL, + price_level=place.PriceLevel.PRICE_LEVEL_FREE, + user_rating_count=1835, + icon_mask_base_uri='icon_mask_base_uri_value', + icon_background_color='icon_background_color_value', + takeout=True, + delivery=True, + dine_in=True, + curbside_pickup=True, + reservable=True, + serves_breakfast=True, + serves_lunch=True, + serves_dinner=True, + serves_beer=True, + serves_wine=True, + serves_brunch=True, + serves_vegetarian_food=True, + outdoor_seating=True, + live_music=True, + menu_for_children=True, + serves_cocktails=True, + serves_dessert=True, + serves_coffee=True, + good_for_children=True, + allows_dogs=True, + restroom=True, + good_for_groups=True, + good_for_watching_sports=True, + pure_service_area_business=True, + ) + response = client.get_place(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = places_service.GetPlaceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, place.Place) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.types == ['types_value'] + assert response.primary_type == 'primary_type_value' + assert response.national_phone_number == 'national_phone_number_value' + assert response.international_phone_number == 'international_phone_number_value' + assert response.formatted_address == 'formatted_address_value' + assert response.short_formatted_address == 'short_formatted_address_value' + assert math.isclose(response.rating, 0.645, rel_tol=1e-6) + assert response.google_maps_uri == 'google_maps_uri_value' + assert response.website_uri == 'website_uri_value' + assert response.utc_offset_minutes == 1942 + assert response.adr_format_address == 'adr_format_address_value' + assert response.business_status == place.Place.BusinessStatus.OPERATIONAL + assert response.price_level == place.PriceLevel.PRICE_LEVEL_FREE + assert response.user_rating_count == 1835 + assert response.icon_mask_base_uri == 'icon_mask_base_uri_value' + assert response.icon_background_color == 'icon_background_color_value' + assert response.takeout is True + assert response.delivery is True + assert response.dine_in is True + assert response.curbside_pickup is True + assert response.reservable is True + assert response.serves_breakfast is True + assert response.serves_lunch is True + assert response.serves_dinner is True + assert response.serves_beer is True + assert response.serves_wine is True + assert response.serves_brunch is True + assert response.serves_vegetarian_food is True + assert response.outdoor_seating is True + assert response.live_music is True + assert response.menu_for_children is True + assert response.serves_cocktails is True + assert response.serves_dessert is True + assert response.serves_coffee is True + assert response.good_for_children is True + assert response.allows_dogs is True + assert response.restroom is True + assert response.good_for_groups is True + assert response.good_for_watching_sports is True + assert response.pure_service_area_business is True + + +def test_get_place_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 = PlacesClient( + 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 = places_service.GetPlaceRequest( + name='name_value', + language_code='language_code_value', + region_code='region_code_value', + session_token='session_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_place), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_place(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == places_service.GetPlaceRequest( + name='name_value', + language_code='language_code_value', + region_code='region_code_value', + session_token='session_token_value', + ) + +def test_get_place_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = PlacesClient( + 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_place in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_place] = mock_rpc + request = {} + client.get_place(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_place(request) + + # Establish that a new wrapper 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_place_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = PlacesAsyncClient( + 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_place in client._client._transport._wrapped_methods + + # 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_place] = mock_rpc + + request = {} + await client.get_place(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_place(request) + + # Establish that a new wrapper 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_place_async(transport: str = 'grpc_asyncio', request_type=places_service.GetPlaceRequest): + client = PlacesAsyncClient( + 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_place), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(place.Place( + name='name_value', + id='id_value', + types=['types_value'], + primary_type='primary_type_value', + national_phone_number='national_phone_number_value', + international_phone_number='international_phone_number_value', + formatted_address='formatted_address_value', + short_formatted_address='short_formatted_address_value', + rating=0.645, + google_maps_uri='google_maps_uri_value', + website_uri='website_uri_value', + utc_offset_minutes=1942, + adr_format_address='adr_format_address_value', + business_status=place.Place.BusinessStatus.OPERATIONAL, + price_level=place.PriceLevel.PRICE_LEVEL_FREE, + user_rating_count=1835, + icon_mask_base_uri='icon_mask_base_uri_value', + icon_background_color='icon_background_color_value', + takeout=True, + delivery=True, + dine_in=True, + curbside_pickup=True, + reservable=True, + serves_breakfast=True, + serves_lunch=True, + serves_dinner=True, + serves_beer=True, + serves_wine=True, + serves_brunch=True, + serves_vegetarian_food=True, + outdoor_seating=True, + live_music=True, + menu_for_children=True, + serves_cocktails=True, + serves_dessert=True, + serves_coffee=True, + good_for_children=True, + allows_dogs=True, + restroom=True, + good_for_groups=True, + good_for_watching_sports=True, + pure_service_area_business=True, + )) + response = await client.get_place(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = places_service.GetPlaceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, place.Place) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.types == ['types_value'] + assert response.primary_type == 'primary_type_value' + assert response.national_phone_number == 'national_phone_number_value' + assert response.international_phone_number == 'international_phone_number_value' + assert response.formatted_address == 'formatted_address_value' + assert response.short_formatted_address == 'short_formatted_address_value' + assert math.isclose(response.rating, 0.645, rel_tol=1e-6) + assert response.google_maps_uri == 'google_maps_uri_value' + assert response.website_uri == 'website_uri_value' + assert response.utc_offset_minutes == 1942 + assert response.adr_format_address == 'adr_format_address_value' + assert response.business_status == place.Place.BusinessStatus.OPERATIONAL + assert response.price_level == place.PriceLevel.PRICE_LEVEL_FREE + assert response.user_rating_count == 1835 + assert response.icon_mask_base_uri == 'icon_mask_base_uri_value' + assert response.icon_background_color == 'icon_background_color_value' + assert response.takeout is True + assert response.delivery is True + assert response.dine_in is True + assert response.curbside_pickup is True + assert response.reservable is True + assert response.serves_breakfast is True + assert response.serves_lunch is True + assert response.serves_dinner is True + assert response.serves_beer is True + assert response.serves_wine is True + assert response.serves_brunch is True + assert response.serves_vegetarian_food is True + assert response.outdoor_seating is True + assert response.live_music is True + assert response.menu_for_children is True + assert response.serves_cocktails is True + assert response.serves_dessert is True + assert response.serves_coffee is True + assert response.good_for_children is True + assert response.allows_dogs is True + assert response.restroom is True + assert response.good_for_groups is True + assert response.good_for_watching_sports is True + assert response.pure_service_area_business is True + + +@pytest.mark.asyncio +async def test_get_place_async_from_dict(): + await test_get_place_async(request_type=dict) + +def test_get_place_field_headers(): + client = PlacesClient( + 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 = places_service.GetPlaceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_place), + '__call__') as call: + call.return_value = place.Place() + client.get_place(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_place_field_headers_async(): + client = PlacesAsyncClient( + 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 = places_service.GetPlaceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_place), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(place.Place()) + await client.get_place(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_place_flattened(): + client = PlacesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_place), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = place.Place() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_place( + 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_place_flattened_error(): + client = PlacesClient( + 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_place( + places_service.GetPlaceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_place_flattened_async(): + client = PlacesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_place), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = place.Place() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(place.Place()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_place( + 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_place_flattened_error_async(): + client = PlacesAsyncClient( + 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_place( + places_service.GetPlaceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + places_service.AutocompletePlacesRequest, + dict, +]) +def test_autocomplete_places(request_type, transport: str = 'grpc'): + client = PlacesClient( + 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.autocomplete_places), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = places_service.AutocompletePlacesResponse( + ) + response = client.autocomplete_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = places_service.AutocompletePlacesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, places_service.AutocompletePlacesResponse) + + +def test_autocomplete_places_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 = PlacesClient( + 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 = places_service.AutocompletePlacesRequest( + input='input_value', + language_code='language_code_value', + region_code='region_code_value', + session_token='session_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.autocomplete_places), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.autocomplete_places(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == places_service.AutocompletePlacesRequest( + input='input_value', + language_code='language_code_value', + region_code='region_code_value', + session_token='session_token_value', + ) + +def test_autocomplete_places_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = PlacesClient( + 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.autocomplete_places in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.autocomplete_places] = mock_rpc + request = {} + client.autocomplete_places(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.autocomplete_places(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_autocomplete_places_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = PlacesAsyncClient( + 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.autocomplete_places in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.autocomplete_places] = mock_rpc + + request = {} + await client.autocomplete_places(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.autocomplete_places(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_autocomplete_places_async(transport: str = 'grpc_asyncio', request_type=places_service.AutocompletePlacesRequest): + client = PlacesAsyncClient( + 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.autocomplete_places), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(places_service.AutocompletePlacesResponse( + )) + response = await client.autocomplete_places(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = places_service.AutocompletePlacesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, places_service.AutocompletePlacesResponse) + + +@pytest.mark.asyncio +async def test_autocomplete_places_async_from_dict(): + await test_autocomplete_places_async(request_type=dict) + + +def test_search_nearby_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 = PlacesClient( + 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.search_nearby in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.search_nearby] = mock_rpc + + request = {} + client.search_nearby(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.search_nearby(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_search_nearby_rest_required_fields(request_type=places_service.SearchNearbyRequest): + transport_class = transports.PlacesRestTransport + + 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()).search_nearby._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()).search_nearby._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = PlacesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = places_service.SearchNearbyResponse() + # 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 = places_service.SearchNearbyResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.search_nearby(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_search_nearby_rest_unset_required_fields(): + transport = transports.PlacesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.search_nearby._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("locationRestriction", ))) + + +def test_search_text_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 = PlacesClient( + 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.search_text in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.search_text] = mock_rpc + + request = {} + client.search_text(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.search_text(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_search_text_rest_required_fields(request_type=places_service.SearchTextRequest): + transport_class = transports.PlacesRestTransport + + request_init = {} + request_init["text_query"] = "" + request = 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()).search_text._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["textQuery"] = 'text_query_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).search_text._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "textQuery" in jsonified_request + assert jsonified_request["textQuery"] == 'text_query_value' + + client = PlacesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = places_service.SearchTextResponse() + # 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 = places_service.SearchTextResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.search_text(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_search_text_rest_unset_required_fields(): + transport = transports.PlacesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.search_text._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("textQuery", ))) + + +def test_get_photo_media_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 = PlacesClient( + 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_photo_media in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_photo_media] = mock_rpc + + request = {} + client.get_photo_media(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_photo_media(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_photo_media_rest_required_fields(request_type=places_service.GetPhotoMediaRequest): + transport_class = transports.PlacesRestTransport + + 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_photo_media._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_photo_media._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("max_height_px", "max_width_px", "skip_http_redirect", )) + 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 = PlacesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = places_service.PhotoMedia() + # 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 = places_service.PhotoMedia.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_photo_media(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_photo_media_rest_unset_required_fields(): + transport = transports.PlacesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_photo_media._get_unset_required_fields({}) + assert set(unset_fields) == (set(("maxHeightPx", "maxWidthPx", "skipHttpRedirect", )) & set(("name", ))) + + +def test_get_photo_media_rest_flattened(): + client = PlacesClient( + 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 = places_service.PhotoMedia() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'places/sample1/photos/sample2/media'} + + # 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 = places_service.PhotoMedia.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_photo_media(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=places/*/photos/*/media}" % client.transport._host, args[1]) + + +def test_get_photo_media_rest_flattened_error(transport: str = 'rest'): + client = PlacesClient( + 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_photo_media( + places_service.GetPhotoMediaRequest(), + name='name_value', + ) + + +def test_get_place_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 = PlacesClient( + 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_place in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_place] = mock_rpc + + request = {} + client.get_place(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_place(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_place_rest_required_fields(request_type=places_service.GetPlaceRequest): + transport_class = transports.PlacesRestTransport + + 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_place._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_place._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", "region_code", "session_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = PlacesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = place.Place() + # 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 = place.Place.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_place(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_place_rest_unset_required_fields(): + transport = transports.PlacesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_place._get_unset_required_fields({}) + assert set(unset_fields) == (set(("languageCode", "regionCode", "sessionToken", )) & set(("name", ))) + + +def test_get_place_rest_flattened(): + client = PlacesClient( + 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 = place.Place() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'places/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 = place.Place.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_place(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=places/*}" % client.transport._host, args[1]) + + +def test_get_place_rest_flattened_error(transport: str = 'rest'): + client = PlacesClient( + 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_place( + places_service.GetPlaceRequest(), + name='name_value', + ) + + +def test_autocomplete_places_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 = PlacesClient( + 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.autocomplete_places in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.autocomplete_places] = mock_rpc + + request = {} + client.autocomplete_places(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.autocomplete_places(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_autocomplete_places_rest_required_fields(request_type=places_service.AutocompletePlacesRequest): + transport_class = transports.PlacesRestTransport + + request_init = {} + request_init["input"] = "" + request = 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()).autocomplete_places._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["input"] = 'input_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).autocomplete_places._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "input" in jsonified_request + assert jsonified_request["input"] == 'input_value' + + client = PlacesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = places_service.AutocompletePlacesResponse() + # 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 = places_service.AutocompletePlacesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.autocomplete_places(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_autocomplete_places_rest_unset_required_fields(): + transport = transports.PlacesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.autocomplete_places._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("input", ))) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.PlacesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PlacesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.PlacesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PlacesClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.PlacesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = PlacesClient( + 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 = PlacesClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.PlacesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PlacesClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.PlacesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = PlacesClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.PlacesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.PlacesGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.PlacesGrpcTransport, + transports.PlacesGrpcAsyncIOTransport, + transports.PlacesRestTransport, +]) +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 = PlacesClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = PlacesClient( + 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_search_nearby_empty_call_grpc(): + client = PlacesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.search_nearby), + '__call__') as call: + call.return_value = places_service.SearchNearbyResponse() + client.search_nearby(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = places_service.SearchNearbyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_search_text_empty_call_grpc(): + client = PlacesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.search_text), + '__call__') as call: + call.return_value = places_service.SearchTextResponse() + client.search_text(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = places_service.SearchTextRequest() + + assert args[0] == request_msg + + +# This 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_photo_media_empty_call_grpc(): + client = PlacesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_photo_media), + '__call__') as call: + call.return_value = places_service.PhotoMedia() + client.get_photo_media(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = places_service.GetPhotoMediaRequest() + + assert args[0] == request_msg + + +# This 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_place_empty_call_grpc(): + client = PlacesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_place), + '__call__') as call: + call.return_value = place.Place() + client.get_place(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = places_service.GetPlaceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_autocomplete_places_empty_call_grpc(): + client = PlacesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.autocomplete_places), + '__call__') as call: + call.return_value = places_service.AutocompletePlacesResponse() + client.autocomplete_places(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = places_service.AutocompletePlacesRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = PlacesAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = PlacesAsyncClient( + 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_search_nearby_empty_call_grpc_asyncio(): + client = PlacesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.search_nearby), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(places_service.SearchNearbyResponse( + )) + await client.search_nearby(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = places_service.SearchNearbyRequest() + + assert args[0] == request_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_search_text_empty_call_grpc_asyncio(): + client = PlacesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.search_text), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(places_service.SearchTextResponse( + )) + await client.search_text(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = places_service.SearchTextRequest() + + assert args[0] == request_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_photo_media_empty_call_grpc_asyncio(): + client = PlacesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_photo_media), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(places_service.PhotoMedia( + name='name_value', + photo_uri='photo_uri_value', + )) + await client.get_photo_media(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = places_service.GetPhotoMediaRequest() + + assert args[0] == request_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_place_empty_call_grpc_asyncio(): + client = PlacesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_place), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(place.Place( + name='name_value', + id='id_value', + types=['types_value'], + primary_type='primary_type_value', + national_phone_number='national_phone_number_value', + international_phone_number='international_phone_number_value', + formatted_address='formatted_address_value', + short_formatted_address='short_formatted_address_value', + rating=0.645, + google_maps_uri='google_maps_uri_value', + website_uri='website_uri_value', + utc_offset_minutes=1942, + adr_format_address='adr_format_address_value', + business_status=place.Place.BusinessStatus.OPERATIONAL, + price_level=place.PriceLevel.PRICE_LEVEL_FREE, + user_rating_count=1835, + icon_mask_base_uri='icon_mask_base_uri_value', + icon_background_color='icon_background_color_value', + takeout=True, + delivery=True, + dine_in=True, + curbside_pickup=True, + reservable=True, + serves_breakfast=True, + serves_lunch=True, + serves_dinner=True, + serves_beer=True, + serves_wine=True, + serves_brunch=True, + serves_vegetarian_food=True, + outdoor_seating=True, + live_music=True, + menu_for_children=True, + serves_cocktails=True, + serves_dessert=True, + serves_coffee=True, + good_for_children=True, + allows_dogs=True, + restroom=True, + good_for_groups=True, + good_for_watching_sports=True, + pure_service_area_business=True, + )) + await client.get_place(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = places_service.GetPlaceRequest() + + assert args[0] == request_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_autocomplete_places_empty_call_grpc_asyncio(): + client = PlacesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.autocomplete_places), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(places_service.AutocompletePlacesResponse( + )) + await client.autocomplete_places(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = places_service.AutocompletePlacesRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = PlacesClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_search_nearby_rest_bad_request(request_type=places_service.SearchNearbyRequest): + client = PlacesClient( + 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.search_nearby(request) + + +@pytest.mark.parametrize("request_type", [ + places_service.SearchNearbyRequest, + dict, +]) +def test_search_nearby_rest_call_success(request_type): + client = PlacesClient( + 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 = places_service.SearchNearbyResponse( + ) + + # 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 = places_service.SearchNearbyResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.search_nearby(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, places_service.SearchNearbyResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_search_nearby_rest_interceptors(null_interceptor): + transport = transports.PlacesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.PlacesRestInterceptor(), + ) + client = PlacesClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.PlacesRestInterceptor, "post_search_nearby") as post, \ + mock.patch.object(transports.PlacesRestInterceptor, "pre_search_nearby") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = places_service.SearchNearbyRequest.pb(places_service.SearchNearbyRequest()) + 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 = places_service.SearchNearbyResponse.to_json(places_service.SearchNearbyResponse()) + req.return_value.content = return_value + + request = places_service.SearchNearbyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = places_service.SearchNearbyResponse() + + client.search_nearby(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_search_text_rest_bad_request(request_type=places_service.SearchTextRequest): + client = PlacesClient( + 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.search_text(request) + + +@pytest.mark.parametrize("request_type", [ + places_service.SearchTextRequest, + dict, +]) +def test_search_text_rest_call_success(request_type): + client = PlacesClient( + 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 = places_service.SearchTextResponse( + ) + + # 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 = places_service.SearchTextResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.search_text(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, places_service.SearchTextResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_search_text_rest_interceptors(null_interceptor): + transport = transports.PlacesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.PlacesRestInterceptor(), + ) + client = PlacesClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.PlacesRestInterceptor, "post_search_text") as post, \ + mock.patch.object(transports.PlacesRestInterceptor, "pre_search_text") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = places_service.SearchTextRequest.pb(places_service.SearchTextRequest()) + 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 = places_service.SearchTextResponse.to_json(places_service.SearchTextResponse()) + req.return_value.content = return_value + + request = places_service.SearchTextRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = places_service.SearchTextResponse() + + client.search_text(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_photo_media_rest_bad_request(request_type=places_service.GetPhotoMediaRequest): + client = PlacesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'places/sample1/photos/sample2/media'} + request = request_type(**request_init) + + # Mock the 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_photo_media(request) + + +@pytest.mark.parametrize("request_type", [ + places_service.GetPhotoMediaRequest, + dict, +]) +def test_get_photo_media_rest_call_success(request_type): + client = PlacesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'places/sample1/photos/sample2/media'} + request = request_type(**request_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 = places_service.PhotoMedia( + name='name_value', + photo_uri='photo_uri_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 = places_service.PhotoMedia.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_photo_media(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, places_service.PhotoMedia) + assert response.name == 'name_value' + assert response.photo_uri == 'photo_uri_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_photo_media_rest_interceptors(null_interceptor): + transport = transports.PlacesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.PlacesRestInterceptor(), + ) + client = PlacesClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.PlacesRestInterceptor, "post_get_photo_media") as post, \ + mock.patch.object(transports.PlacesRestInterceptor, "pre_get_photo_media") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = places_service.GetPhotoMediaRequest.pb(places_service.GetPhotoMediaRequest()) + 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 = places_service.PhotoMedia.to_json(places_service.PhotoMedia()) + req.return_value.content = return_value + + request = places_service.GetPhotoMediaRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = places_service.PhotoMedia() + + client.get_photo_media(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_place_rest_bad_request(request_type=places_service.GetPlaceRequest): + client = PlacesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'places/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_place(request) + + +@pytest.mark.parametrize("request_type", [ + places_service.GetPlaceRequest, + dict, +]) +def test_get_place_rest_call_success(request_type): + client = PlacesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'places/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 = place.Place( + name='name_value', + id='id_value', + types=['types_value'], + primary_type='primary_type_value', + national_phone_number='national_phone_number_value', + international_phone_number='international_phone_number_value', + formatted_address='formatted_address_value', + short_formatted_address='short_formatted_address_value', + rating=0.645, + google_maps_uri='google_maps_uri_value', + website_uri='website_uri_value', + utc_offset_minutes=1942, + adr_format_address='adr_format_address_value', + business_status=place.Place.BusinessStatus.OPERATIONAL, + price_level=place.PriceLevel.PRICE_LEVEL_FREE, + user_rating_count=1835, + icon_mask_base_uri='icon_mask_base_uri_value', + icon_background_color='icon_background_color_value', + takeout=True, + delivery=True, + dine_in=True, + curbside_pickup=True, + reservable=True, + serves_breakfast=True, + serves_lunch=True, + serves_dinner=True, + serves_beer=True, + serves_wine=True, + serves_brunch=True, + serves_vegetarian_food=True, + outdoor_seating=True, + live_music=True, + menu_for_children=True, + serves_cocktails=True, + serves_dessert=True, + serves_coffee=True, + good_for_children=True, + allows_dogs=True, + restroom=True, + good_for_groups=True, + good_for_watching_sports=True, + pure_service_area_business=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 = place.Place.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_place(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, place.Place) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.types == ['types_value'] + assert response.primary_type == 'primary_type_value' + assert response.national_phone_number == 'national_phone_number_value' + assert response.international_phone_number == 'international_phone_number_value' + assert response.formatted_address == 'formatted_address_value' + assert response.short_formatted_address == 'short_formatted_address_value' + assert math.isclose(response.rating, 0.645, rel_tol=1e-6) + assert response.google_maps_uri == 'google_maps_uri_value' + assert response.website_uri == 'website_uri_value' + assert response.utc_offset_minutes == 1942 + assert response.adr_format_address == 'adr_format_address_value' + assert response.business_status == place.Place.BusinessStatus.OPERATIONAL + assert response.price_level == place.PriceLevel.PRICE_LEVEL_FREE + assert response.user_rating_count == 1835 + assert response.icon_mask_base_uri == 'icon_mask_base_uri_value' + assert response.icon_background_color == 'icon_background_color_value' + assert response.takeout is True + assert response.delivery is True + assert response.dine_in is True + assert response.curbside_pickup is True + assert response.reservable is True + assert response.serves_breakfast is True + assert response.serves_lunch is True + assert response.serves_dinner is True + assert response.serves_beer is True + assert response.serves_wine is True + assert response.serves_brunch is True + assert response.serves_vegetarian_food is True + assert response.outdoor_seating is True + assert response.live_music is True + assert response.menu_for_children is True + assert response.serves_cocktails is True + assert response.serves_dessert is True + assert response.serves_coffee is True + assert response.good_for_children is True + assert response.allows_dogs is True + assert response.restroom is True + assert response.good_for_groups is True + assert response.good_for_watching_sports is True + assert response.pure_service_area_business is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_place_rest_interceptors(null_interceptor): + transport = transports.PlacesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.PlacesRestInterceptor(), + ) + client = PlacesClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.PlacesRestInterceptor, "post_get_place") as post, \ + mock.patch.object(transports.PlacesRestInterceptor, "pre_get_place") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = places_service.GetPlaceRequest.pb(places_service.GetPlaceRequest()) + 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 = place.Place.to_json(place.Place()) + req.return_value.content = return_value + + request = places_service.GetPlaceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = place.Place() + + client.get_place(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_autocomplete_places_rest_bad_request(request_type=places_service.AutocompletePlacesRequest): + client = PlacesClient( + 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.autocomplete_places(request) + + +@pytest.mark.parametrize("request_type", [ + places_service.AutocompletePlacesRequest, + dict, +]) +def test_autocomplete_places_rest_call_success(request_type): + client = PlacesClient( + 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 = places_service.AutocompletePlacesResponse( + ) + + # 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 = places_service.AutocompletePlacesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.autocomplete_places(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, places_service.AutocompletePlacesResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_autocomplete_places_rest_interceptors(null_interceptor): + transport = transports.PlacesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.PlacesRestInterceptor(), + ) + client = PlacesClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.PlacesRestInterceptor, "post_autocomplete_places") as post, \ + mock.patch.object(transports.PlacesRestInterceptor, "pre_autocomplete_places") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = places_service.AutocompletePlacesRequest.pb(places_service.AutocompletePlacesRequest()) + 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 = places_service.AutocompletePlacesResponse.to_json(places_service.AutocompletePlacesResponse()) + req.return_value.content = return_value + + request = places_service.AutocompletePlacesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = places_service.AutocompletePlacesResponse() + + client.autocomplete_places(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + +def test_initialize_client_w_rest(): + client = PlacesClient( + 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_search_nearby_empty_call_rest(): + client = PlacesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.search_nearby), + '__call__') as call: + client.search_nearby(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = places_service.SearchNearbyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_search_text_empty_call_rest(): + client = PlacesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.search_text), + '__call__') as call: + client.search_text(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = places_service.SearchTextRequest() + + assert args[0] == request_msg + + +# This 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_photo_media_empty_call_rest(): + client = PlacesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_photo_media), + '__call__') as call: + client.get_photo_media(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = places_service.GetPhotoMediaRequest() + + assert args[0] == request_msg + + +# This 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_place_empty_call_rest(): + client = PlacesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_place), + '__call__') as call: + client.get_place(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = places_service.GetPlaceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_autocomplete_places_empty_call_rest(): + client = PlacesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.autocomplete_places), + '__call__') as call: + client.autocomplete_places(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = places_service.AutocompletePlacesRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = PlacesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.PlacesGrpcTransport, + ) + +def test_places_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.PlacesTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_places_base_transport(): + # Instantiate the base transport. + with mock.patch('google.maps.places_v1.services.places.transports.PlacesTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.PlacesTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'search_nearby', + 'search_text', + 'get_photo_media', + 'get_place', + 'autocomplete_places', + ) + 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_places_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.maps.places_v1.services.places.transports.PlacesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PlacesTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( +), + quota_project_id="octopus", + ) + + +def test_places_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.maps.places_v1.services.places.transports.PlacesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PlacesTransport() + adc.assert_called_once() + + +def test_places_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) + PlacesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.PlacesGrpcTransport, + transports.PlacesGrpcAsyncIOTransport, + ], +) +def test_places_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=(), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.PlacesGrpcTransport, + transports.PlacesGrpcAsyncIOTransport, + transports.PlacesRestTransport, + ], +) +def test_places_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.PlacesGrpcTransport, grpc_helpers), + (transports.PlacesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_places_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( + "places.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( +), + scopes=["1", "2"], + default_host="places.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.PlacesGrpcTransport, transports.PlacesGrpcAsyncIOTransport]) +def test_places_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_places_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.PlacesRestTransport ( + 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_places_host_no_port(transport_name): + client = PlacesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='places.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'places.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://places.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_places_host_with_port(transport_name): + client = PlacesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='places.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'places.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://places.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_places_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = PlacesClient( + credentials=creds1, + transport=transport_name, + ) + client2 = PlacesClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.search_nearby._session + session2 = client2.transport.search_nearby._session + assert session1 != session2 + session1 = client1.transport.search_text._session + session2 = client2.transport.search_text._session + assert session1 != session2 + session1 = client1.transport.get_photo_media._session + session2 = client2.transport.get_photo_media._session + assert session1 != session2 + session1 = client1.transport.get_place._session + session2 = client2.transport.get_place._session + assert session1 != session2 + session1 = client1.transport.autocomplete_places._session + session2 = client2.transport.autocomplete_places._session + assert session1 != session2 +def test_places_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PlacesGrpcTransport( + 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_places_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PlacesGrpcAsyncIOTransport( + 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.PlacesGrpcTransport, transports.PlacesGrpcAsyncIOTransport]) +def test_places_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.PlacesGrpcTransport, transports.PlacesGrpcAsyncIOTransport]) +def test_places_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_photo_path(): + place = "squid" + photo = "clam" + expected = "places/{place}/photos/{photo}".format(place=place, photo=photo, ) + actual = PlacesClient.photo_path(place, photo) + assert expected == actual + + +def test_parse_photo_path(): + expected = { + "place": "whelk", + "photo": "octopus", + } + path = PlacesClient.photo_path(**expected) + + # Check that the path construction is reversible. + actual = PlacesClient.parse_photo_path(path) + assert expected == actual + +def test_photo_media_path(): + place_id = "oyster" + photo_reference = "nudibranch" + expected = "places/{place_id}/photos/{photo_reference}/media".format(place_id=place_id, photo_reference=photo_reference, ) + actual = PlacesClient.photo_media_path(place_id, photo_reference) + assert expected == actual + + +def test_parse_photo_media_path(): + expected = { + "place_id": "cuttlefish", + "photo_reference": "mussel", + } + path = PlacesClient.photo_media_path(**expected) + + # Check that the path construction is reversible. + actual = PlacesClient.parse_photo_media_path(path) + assert expected == actual + +def test_place_path(): + place_id = "winkle" + expected = "places/{place_id}".format(place_id=place_id, ) + actual = PlacesClient.place_path(place_id) + assert expected == actual + + +def test_parse_place_path(): + expected = { + "place_id": "nautilus", + } + path = PlacesClient.place_path(**expected) + + # Check that the path construction is reversible. + actual = PlacesClient.parse_place_path(path) + assert expected == actual + +def test_review_path(): + place = "scallop" + review = "abalone" + expected = "places/{place}/reviews/{review}".format(place=place, review=review, ) + actual = PlacesClient.review_path(place, review) + assert expected == actual + + +def test_parse_review_path(): + expected = { + "place": "squid", + "review": "clam", + } + path = PlacesClient.review_path(**expected) + + # Check that the path construction is reversible. + actual = PlacesClient.parse_review_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = PlacesClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = PlacesClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = PlacesClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = PlacesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = PlacesClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = PlacesClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = PlacesClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = PlacesClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = PlacesClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = PlacesClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = PlacesClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = PlacesClient.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 = PlacesClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = PlacesClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = PlacesClient.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.PlacesTransport, '_prep_wrapped_messages') as prep: + client = PlacesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.PlacesTransport, '_prep_wrapped_messages') as prep: + transport_class = PlacesClient.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 = PlacesClient( + 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 = PlacesAsyncClient( + 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 = PlacesClient( + 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 = PlacesClient( + 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", [ + (PlacesClient, transports.PlacesGrpcTransport), + (PlacesAsyncClient, transports.PlacesGrpcAsyncIOTransport), +]) +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-maps-routeoptimization/v1/.coveragerc b/owl-bot-staging/google-maps-routeoptimization/v1/.coveragerc new file mode 100644 index 000000000000..aa5ba4d9b1f4 --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/maps/routeoptimization/__init__.py + google/maps/routeoptimization/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-maps-routeoptimization/v1/.flake8 b/owl-bot-staging/google-maps-routeoptimization/v1/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/MANIFEST.in b/owl-bot-staging/google-maps-routeoptimization/v1/MANIFEST.in new file mode 100644 index 000000000000..f7956876a038 --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/maps/routeoptimization *.py +recursive-include google/maps/routeoptimization_v1 *.py diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/README.rst b/owl-bot-staging/google-maps-routeoptimization/v1/README.rst new file mode 100644 index 000000000000..5873f7a73b0e --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Maps Routeoptimization 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 Maps Routeoptimization 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 diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/docs/_static/custom.css b/owl-bot-staging/google-maps-routeoptimization/v1/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/docs/conf.py b/owl-bot-staging/google-maps-routeoptimization/v1/docs/conf.py new file mode 100644 index 000000000000..0e46cb236e24 --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-maps-routeoptimization 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("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# 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.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +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-maps-routeoptimization" +copyright = u"2023, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# 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 = 'en' + +# 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"] + +# 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 Maps Client Libraries for Python", + "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-maps-routeoptimization-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-maps-routeoptimization.tex", + u"google-maps-routeoptimization 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-maps-routeoptimization", + u"Google Maps Routeoptimization 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-maps-routeoptimization", + u"google-maps-routeoptimization Documentation", + author, + "google-maps-routeoptimization", + "GAPIC library for Google Maps Routeoptimization API", + "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": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", 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-maps-routeoptimization/v1/docs/index.rst b/owl-bot-staging/google-maps-routeoptimization/v1/docs/index.rst new file mode 100644 index 000000000000..382cf6284865 --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + routeoptimization_v1/services_ + routeoptimization_v1/types_ diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/docs/routeoptimization_v1/route_optimization.rst b/owl-bot-staging/google-maps-routeoptimization/v1/docs/routeoptimization_v1/route_optimization.rst new file mode 100644 index 000000000000..17445dae6122 --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/docs/routeoptimization_v1/route_optimization.rst @@ -0,0 +1,6 @@ +RouteOptimization +----------------------------------- + +.. automodule:: google.maps.routeoptimization_v1.services.route_optimization + :members: + :inherited-members: diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/docs/routeoptimization_v1/services_.rst b/owl-bot-staging/google-maps-routeoptimization/v1/docs/routeoptimization_v1/services_.rst new file mode 100644 index 000000000000..818250f8aa4b --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/docs/routeoptimization_v1/services_.rst @@ -0,0 +1,6 @@ +Services for Google Maps Routeoptimization v1 API +================================================= +.. toctree:: + :maxdepth: 2 + + route_optimization diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/docs/routeoptimization_v1/types_.rst b/owl-bot-staging/google-maps-routeoptimization/v1/docs/routeoptimization_v1/types_.rst new file mode 100644 index 000000000000..44fe4e6164f4 --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/docs/routeoptimization_v1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Maps Routeoptimization v1 API +============================================== + +.. automodule:: google.maps.routeoptimization_v1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization/__init__.py b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization/__init__.py new file mode 100644 index 000000000000..589f845e0fb1 --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization/__init__.py @@ -0,0 +1,81 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.routeoptimization import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.maps.routeoptimization_v1.services.route_optimization.client import RouteOptimizationClient +from google.maps.routeoptimization_v1.services.route_optimization.async_client import RouteOptimizationAsyncClient + +from google.maps.routeoptimization_v1.types.route_optimization_service import AggregatedMetrics +from google.maps.routeoptimization_v1.types.route_optimization_service import BatchOptimizeToursMetadata +from google.maps.routeoptimization_v1.types.route_optimization_service import BatchOptimizeToursRequest +from google.maps.routeoptimization_v1.types.route_optimization_service import BatchOptimizeToursResponse +from google.maps.routeoptimization_v1.types.route_optimization_service import BreakRule +from google.maps.routeoptimization_v1.types.route_optimization_service import DistanceLimit +from google.maps.routeoptimization_v1.types.route_optimization_service import GcsDestination +from google.maps.routeoptimization_v1.types.route_optimization_service import GcsSource +from google.maps.routeoptimization_v1.types.route_optimization_service import InjectedSolutionConstraint +from google.maps.routeoptimization_v1.types.route_optimization_service import InputConfig +from google.maps.routeoptimization_v1.types.route_optimization_service import Location +from google.maps.routeoptimization_v1.types.route_optimization_service import OptimizeToursRequest +from google.maps.routeoptimization_v1.types.route_optimization_service import OptimizeToursResponse +from google.maps.routeoptimization_v1.types.route_optimization_service import OptimizeToursValidationError +from google.maps.routeoptimization_v1.types.route_optimization_service import OutputConfig +from google.maps.routeoptimization_v1.types.route_optimization_service import RouteModifiers +from google.maps.routeoptimization_v1.types.route_optimization_service import Shipment +from google.maps.routeoptimization_v1.types.route_optimization_service import ShipmentModel +from google.maps.routeoptimization_v1.types.route_optimization_service import ShipmentRoute +from google.maps.routeoptimization_v1.types.route_optimization_service import ShipmentTypeIncompatibility +from google.maps.routeoptimization_v1.types.route_optimization_service import ShipmentTypeRequirement +from google.maps.routeoptimization_v1.types.route_optimization_service import SkippedShipment +from google.maps.routeoptimization_v1.types.route_optimization_service import TimeWindow +from google.maps.routeoptimization_v1.types.route_optimization_service import TransitionAttributes +from google.maps.routeoptimization_v1.types.route_optimization_service import Vehicle +from google.maps.routeoptimization_v1.types.route_optimization_service import Waypoint +from google.maps.routeoptimization_v1.types.route_optimization_service import DataFormat + +__all__ = ('RouteOptimizationClient', + 'RouteOptimizationAsyncClient', + 'AggregatedMetrics', + 'BatchOptimizeToursMetadata', + 'BatchOptimizeToursRequest', + 'BatchOptimizeToursResponse', + 'BreakRule', + 'DistanceLimit', + 'GcsDestination', + 'GcsSource', + 'InjectedSolutionConstraint', + 'InputConfig', + 'Location', + 'OptimizeToursRequest', + 'OptimizeToursResponse', + 'OptimizeToursValidationError', + 'OutputConfig', + 'RouteModifiers', + 'Shipment', + 'ShipmentModel', + 'ShipmentRoute', + 'ShipmentTypeIncompatibility', + 'ShipmentTypeRequirement', + 'SkippedShipment', + 'TimeWindow', + 'TransitionAttributes', + 'Vehicle', + 'Waypoint', + 'DataFormat', +) diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization/gapic_version.py b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-maps-routeoptimization/v1/google/maps/routeoptimization/py.typed b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization/py.typed new file mode 100644 index 000000000000..9471c714bbf3 --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-maps-routeoptimization package uses inline types. diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/__init__.py b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/__init__.py new file mode 100644 index 000000000000..0ab14fee353e --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/__init__.py @@ -0,0 +1,82 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.routeoptimization_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.route_optimization import RouteOptimizationClient +from .services.route_optimization import RouteOptimizationAsyncClient + +from .types.route_optimization_service import AggregatedMetrics +from .types.route_optimization_service import BatchOptimizeToursMetadata +from .types.route_optimization_service import BatchOptimizeToursRequest +from .types.route_optimization_service import BatchOptimizeToursResponse +from .types.route_optimization_service import BreakRule +from .types.route_optimization_service import DistanceLimit +from .types.route_optimization_service import GcsDestination +from .types.route_optimization_service import GcsSource +from .types.route_optimization_service import InjectedSolutionConstraint +from .types.route_optimization_service import InputConfig +from .types.route_optimization_service import Location +from .types.route_optimization_service import OptimizeToursRequest +from .types.route_optimization_service import OptimizeToursResponse +from .types.route_optimization_service import OptimizeToursValidationError +from .types.route_optimization_service import OutputConfig +from .types.route_optimization_service import RouteModifiers +from .types.route_optimization_service import Shipment +from .types.route_optimization_service import ShipmentModel +from .types.route_optimization_service import ShipmentRoute +from .types.route_optimization_service import ShipmentTypeIncompatibility +from .types.route_optimization_service import ShipmentTypeRequirement +from .types.route_optimization_service import SkippedShipment +from .types.route_optimization_service import TimeWindow +from .types.route_optimization_service import TransitionAttributes +from .types.route_optimization_service import Vehicle +from .types.route_optimization_service import Waypoint +from .types.route_optimization_service import DataFormat + +__all__ = ( + 'RouteOptimizationAsyncClient', +'AggregatedMetrics', +'BatchOptimizeToursMetadata', +'BatchOptimizeToursRequest', +'BatchOptimizeToursResponse', +'BreakRule', +'DataFormat', +'DistanceLimit', +'GcsDestination', +'GcsSource', +'InjectedSolutionConstraint', +'InputConfig', +'Location', +'OptimizeToursRequest', +'OptimizeToursResponse', +'OptimizeToursValidationError', +'OutputConfig', +'RouteModifiers', +'RouteOptimizationClient', +'Shipment', +'ShipmentModel', +'ShipmentRoute', +'ShipmentTypeIncompatibility', +'ShipmentTypeRequirement', +'SkippedShipment', +'TimeWindow', +'TransitionAttributes', +'Vehicle', +'Waypoint', +) diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/gapic_metadata.json b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/gapic_metadata.json new file mode 100644 index 000000000000..386551edc86c --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/gapic_metadata.json @@ -0,0 +1,58 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.maps.routeoptimization_v1", + "protoPackage": "google.maps.routeoptimization.v1", + "schema": "1.0", + "services": { + "RouteOptimization": { + "clients": { + "grpc": { + "libraryClient": "RouteOptimizationClient", + "rpcs": { + "BatchOptimizeTours": { + "methods": [ + "batch_optimize_tours" + ] + }, + "OptimizeTours": { + "methods": [ + "optimize_tours" + ] + } + } + }, + "grpc-async": { + "libraryClient": "RouteOptimizationAsyncClient", + "rpcs": { + "BatchOptimizeTours": { + "methods": [ + "batch_optimize_tours" + ] + }, + "OptimizeTours": { + "methods": [ + "optimize_tours" + ] + } + } + }, + "rest": { + "libraryClient": "RouteOptimizationClient", + "rpcs": { + "BatchOptimizeTours": { + "methods": [ + "batch_optimize_tours" + ] + }, + "OptimizeTours": { + "methods": [ + "optimize_tours" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/gapic_version.py b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-maps-routeoptimization/v1/google/maps/routeoptimization_v1/py.typed b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/py.typed new file mode 100644 index 000000000000..9471c714bbf3 --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-maps-routeoptimization package uses inline types. diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/__init__.py b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/__init__.py b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/__init__.py new file mode 100644 index 000000000000..6f2dd114cb2d --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 RouteOptimizationClient +from .async_client import RouteOptimizationAsyncClient + +__all__ = ( + 'RouteOptimizationClient', + 'RouteOptimizationAsyncClient', +) diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/async_client.py b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/async_client.py new file mode 100644 index 000000000000..ef9c48e09537 --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/async_client.py @@ -0,0 +1,576 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.routeoptimization_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 + + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.maps.routeoptimization_v1.types import route_optimization_service +from .transports.base import RouteOptimizationTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import RouteOptimizationGrpcAsyncIOTransport +from .client import RouteOptimizationClient + +try: + from google.api_core import client_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 RouteOptimizationAsyncClient: + """A service for optimizing vehicle tours. + + Validity of certain types of fields: + + - ``google.protobuf.Timestamp`` + + - Times are in Unix time: seconds since + 1970-01-01T00:00:00+00:00. + - seconds must be in [0, 253402300799], i.e. in + [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. + - nanos must be unset or set to 0. + + - ``google.protobuf.Duration`` + + - seconds must be in [0, 253402300799], i.e. in + [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. + - nanos must be unset or set to 0. + + - ``google.type.LatLng`` + + - latitude must be in [-90.0, 90.0]. + - longitude must be in [-180.0, 180.0]. + - at least one of latitude and longitude must be non-zero. + """ + + _client: RouteOptimizationClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = RouteOptimizationClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = RouteOptimizationClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = RouteOptimizationClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = RouteOptimizationClient._DEFAULT_UNIVERSE + + common_billing_account_path = staticmethod(RouteOptimizationClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(RouteOptimizationClient.parse_common_billing_account_path) + common_folder_path = staticmethod(RouteOptimizationClient.common_folder_path) + parse_common_folder_path = staticmethod(RouteOptimizationClient.parse_common_folder_path) + common_organization_path = staticmethod(RouteOptimizationClient.common_organization_path) + parse_common_organization_path = staticmethod(RouteOptimizationClient.parse_common_organization_path) + common_project_path = staticmethod(RouteOptimizationClient.common_project_path) + parse_common_project_path = staticmethod(RouteOptimizationClient.parse_common_project_path) + common_location_path = staticmethod(RouteOptimizationClient.common_location_path) + parse_common_location_path = staticmethod(RouteOptimizationClient.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: + RouteOptimizationAsyncClient: The constructed client. + """ + return RouteOptimizationClient.from_service_account_info.__func__(RouteOptimizationAsyncClient, 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: + RouteOptimizationAsyncClient: The constructed client. + """ + return RouteOptimizationClient.from_service_account_file.__func__(RouteOptimizationAsyncClient, 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 RouteOptimizationClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> RouteOptimizationTransport: + """Returns the transport used by the client instance. + + Returns: + RouteOptimizationTransport: 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 = RouteOptimizationClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, RouteOptimizationTransport, Callable[..., RouteOptimizationTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the route optimization 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,RouteOptimizationTransport,Callable[..., RouteOptimizationTransport]]]): + 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 RouteOptimizationTransport 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 = RouteOptimizationClient( + 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.maps.routeoptimization_v1.RouteOptimizationAsyncClient`.", + extra = { + "serviceName": "google.maps.routeoptimization.v1.RouteOptimization", + "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.maps.routeoptimization.v1.RouteOptimization", + "credentialsType": None, + } + ) + + async def optimize_tours(self, + request: Optional[Union[route_optimization_service.OptimizeToursRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> route_optimization_service.OptimizeToursResponse: + r"""Sends an ``OptimizeToursRequest`` containing a ``ShipmentModel`` + and returns an ``OptimizeToursResponse`` containing + ``ShipmentRoute``\ s, which are a set of routes to be performed + by vehicles minimizing the overall cost. + + A ``ShipmentModel`` model consists mainly of ``Shipment``\ s + that need to be carried out and ``Vehicle``\ s that can be used + to transport the ``Shipment``\ s. The ``ShipmentRoute``\ s + assign ``Shipment``\ s to ``Vehicle``\ s. More specifically, + they assign a series of ``Visit``\ s to each vehicle, where a + ``Visit`` corresponds to a ``VisitRequest``, which is a pickup + or delivery for a ``Shipment``. + + The goal is to provide an assignment of ``ShipmentRoute``\ s to + ``Vehicle``\ s that minimizes the total cost where cost has many + components defined in the ``ShipmentModel``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import routeoptimization_v1 + + async def sample_optimize_tours(): + # Create a client + client = routeoptimization_v1.RouteOptimizationAsyncClient() + + # Initialize request argument(s) + request = routeoptimization_v1.OptimizeToursRequest( + parent="parent_value", + ) + + # Make the request + response = await client.optimize_tours(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.routeoptimization_v1.types.OptimizeToursRequest, dict]]): + The request object. Request to be given to a tour + optimization solver which defines the + shipment model to solve as well as + optimization parameters. + 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.maps.routeoptimization_v1.types.OptimizeToursResponse: + Response after solving a tour + optimization problem containing the + routes followed by each vehicle, the + shipments which have been skipped and + the overall cost of the solution. + + """ + # 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, route_optimization_service.OptimizeToursRequest): + request = route_optimization_service.OptimizeToursRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.optimize_tours] + + # Certain 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 batch_optimize_tours(self, + request: Optional[Union[route_optimization_service.BatchOptimizeToursRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Optimizes vehicle tours for one or more ``OptimizeToursRequest`` + messages as a batch. + + This method is a Long Running Operation (LRO). The inputs for + optimization (``OptimizeToursRequest`` messages) and outputs + (``OptimizeToursResponse`` messages) are read from and written + to Cloud Storage in user-specified format. Like the + ``OptimizeTours`` method, each ``OptimizeToursRequest`` contains + a ``ShipmentModel`` and returns an ``OptimizeToursResponse`` + containing ``ShipmentRoute`` fields, which are a set of routes + to be performed by vehicles minimizing the overall cost. + + The user can poll ``operations.get`` to check the status of the + LRO: + + If the LRO ``done`` field is false, then at least one request is + still being processed. Other requests may have completed + successfully and their results are available in Cloud Storage. + + If the LRO's ``done`` field is true, then all requests have been + processed. Any successfully processed requests will have their + results available in Cloud Storage. Any requests that failed + will not have their results available in Cloud Storage. If the + LRO's ``error`` field is set, then it contains the error from + one of the failed requests. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import routeoptimization_v1 + + async def sample_batch_optimize_tours(): + # Create a client + client = routeoptimization_v1.RouteOptimizationAsyncClient() + + # Initialize request argument(s) + model_configs = routeoptimization_v1.AsyncModelConfig() + model_configs.input_config.gcs_source.uri = "uri_value" + model_configs.input_config.data_format = "PROTO_TEXT" + model_configs.output_config.gcs_destination.uri = "uri_value" + model_configs.output_config.data_format = "PROTO_TEXT" + + request = routeoptimization_v1.BatchOptimizeToursRequest( + parent="parent_value", + model_configs=model_configs, + ) + + # Make the request + operation = client.batch_optimize_tours(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.routeoptimization_v1.types.BatchOptimizeToursRequest, dict]]): + The request object. Request to batch optimize tours as an asynchronous + operation. Each input file should contain one + ``OptimizeToursRequest``, and each output file will + contain one ``OptimizeToursResponse``. The request + contains information to read/write and parse the files. + All the input and output files should be under the same + project. + 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.maps.routeoptimization_v1.types.BatchOptimizeToursResponse` Response to a BatchOptimizeToursRequest. This is returned in + the Long Running Operation after the operation is + complete. + + """ + # 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, route_optimization_service.BatchOptimizeToursRequest): + request = route_optimization_service.BatchOptimizeToursRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.batch_optimize_tours] + + # Certain 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + route_optimization_service.BatchOptimizeToursResponse, + metadata_type=route_optimization_service.BatchOptimizeToursMetadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` 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: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # 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) -> "RouteOptimizationAsyncClient": + 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__) + + +__all__ = ( + "RouteOptimizationAsyncClient", +) diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/client.py b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/client.py new file mode 100644 index 000000000000..cc69d1cd24de --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/client.py @@ -0,0 +1,905 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +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.maps.routeoptimization_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 + +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.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.maps.routeoptimization_v1.types import route_optimization_service +from .transports.base import RouteOptimizationTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import RouteOptimizationGrpcTransport +from .transports.grpc_asyncio import RouteOptimizationGrpcAsyncIOTransport +from .transports.rest import RouteOptimizationRestTransport + + +class RouteOptimizationClientMeta(type): + """Metaclass for the RouteOptimization 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[RouteOptimizationTransport]] + _transport_registry["grpc"] = RouteOptimizationGrpcTransport + _transport_registry["grpc_asyncio"] = RouteOptimizationGrpcAsyncIOTransport + _transport_registry["rest"] = RouteOptimizationRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[RouteOptimizationTransport]: + """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 RouteOptimizationClient(metaclass=RouteOptimizationClientMeta): + """A service for optimizing vehicle tours. + + Validity of certain types of fields: + + - ``google.protobuf.Timestamp`` + + - Times are in Unix time: seconds since + 1970-01-01T00:00:00+00:00. + - seconds must be in [0, 253402300799], i.e. in + [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. + - nanos must be unset or set to 0. + + - ``google.protobuf.Duration`` + + - seconds must be in [0, 253402300799], i.e. in + [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. + - nanos must be unset or set to 0. + + - ``google.type.LatLng`` + + - latitude must be in [-90.0, 90.0]. + - longitude must be in [-180.0, 180.0]. + - at least one of latitude and longitude must be non-zero. + """ + + @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 = "routeoptimization.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "routeoptimization.{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: + RouteOptimizationClient: 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: + RouteOptimizationClient: 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) -> RouteOptimizationTransport: + """Returns the transport used by the client instance. + + Returns: + RouteOptimizationTransport: The transport used by the client + instance. + """ + return self._transport + + @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 = RouteOptimizationClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = RouteOptimizationClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = RouteOptimizationClient._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 = RouteOptimizationClient._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 + + @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, RouteOptimizationTransport, Callable[..., RouteOptimizationTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the route optimization 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,RouteOptimizationTransport,Callable[..., RouteOptimizationTransport]]]): + 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 RouteOptimizationTransport 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 = RouteOptimizationClient._read_environment_variables() + self._client_cert_source = RouteOptimizationClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = RouteOptimizationClient._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, RouteOptimizationTransport) + if transport_provided: + # transport is a RouteOptimizationTransport 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(RouteOptimizationTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + RouteOptimizationClient._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[RouteOptimizationTransport], Callable[..., RouteOptimizationTransport]] = ( + RouteOptimizationClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., RouteOptimizationTransport], 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.maps.routeoptimization_v1.RouteOptimizationClient`.", + extra = { + "serviceName": "google.maps.routeoptimization.v1.RouteOptimization", + "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.maps.routeoptimization.v1.RouteOptimization", + "credentialsType": None, + } + ) + + def optimize_tours(self, + request: Optional[Union[route_optimization_service.OptimizeToursRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> route_optimization_service.OptimizeToursResponse: + r"""Sends an ``OptimizeToursRequest`` containing a ``ShipmentModel`` + and returns an ``OptimizeToursResponse`` containing + ``ShipmentRoute``\ s, which are a set of routes to be performed + by vehicles minimizing the overall cost. + + A ``ShipmentModel`` model consists mainly of ``Shipment``\ s + that need to be carried out and ``Vehicle``\ s that can be used + to transport the ``Shipment``\ s. The ``ShipmentRoute``\ s + assign ``Shipment``\ s to ``Vehicle``\ s. More specifically, + they assign a series of ``Visit``\ s to each vehicle, where a + ``Visit`` corresponds to a ``VisitRequest``, which is a pickup + or delivery for a ``Shipment``. + + The goal is to provide an assignment of ``ShipmentRoute``\ s to + ``Vehicle``\ s that minimizes the total cost where cost has many + components defined in the ``ShipmentModel``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import routeoptimization_v1 + + def sample_optimize_tours(): + # Create a client + client = routeoptimization_v1.RouteOptimizationClient() + + # Initialize request argument(s) + request = routeoptimization_v1.OptimizeToursRequest( + parent="parent_value", + ) + + # Make the request + response = client.optimize_tours(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.routeoptimization_v1.types.OptimizeToursRequest, dict]): + The request object. Request to be given to a tour + optimization solver which defines the + shipment model to solve as well as + optimization parameters. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.maps.routeoptimization_v1.types.OptimizeToursResponse: + Response after solving a tour + optimization problem containing the + routes followed by each vehicle, the + shipments which have been skipped and + the overall cost of the solution. + + """ + # 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, route_optimization_service.OptimizeToursRequest): + request = route_optimization_service.OptimizeToursRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.optimize_tours] + + # Certain 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 batch_optimize_tours(self, + request: Optional[Union[route_optimization_service.BatchOptimizeToursRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Optimizes vehicle tours for one or more ``OptimizeToursRequest`` + messages as a batch. + + This method is a Long Running Operation (LRO). The inputs for + optimization (``OptimizeToursRequest`` messages) and outputs + (``OptimizeToursResponse`` messages) are read from and written + to Cloud Storage in user-specified format. Like the + ``OptimizeTours`` method, each ``OptimizeToursRequest`` contains + a ``ShipmentModel`` and returns an ``OptimizeToursResponse`` + containing ``ShipmentRoute`` fields, which are a set of routes + to be performed by vehicles minimizing the overall cost. + + The user can poll ``operations.get`` to check the status of the + LRO: + + If the LRO ``done`` field is false, then at least one request is + still being processed. Other requests may have completed + successfully and their results are available in Cloud Storage. + + If the LRO's ``done`` field is true, then all requests have been + processed. Any successfully processed requests will have their + results available in Cloud Storage. Any requests that failed + will not have their results available in Cloud Storage. If the + LRO's ``error`` field is set, then it contains the error from + one of the failed requests. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import routeoptimization_v1 + + def sample_batch_optimize_tours(): + # Create a client + client = routeoptimization_v1.RouteOptimizationClient() + + # Initialize request argument(s) + model_configs = routeoptimization_v1.AsyncModelConfig() + model_configs.input_config.gcs_source.uri = "uri_value" + model_configs.input_config.data_format = "PROTO_TEXT" + model_configs.output_config.gcs_destination.uri = "uri_value" + model_configs.output_config.data_format = "PROTO_TEXT" + + request = routeoptimization_v1.BatchOptimizeToursRequest( + parent="parent_value", + model_configs=model_configs, + ) + + # Make the request + operation = client.batch_optimize_tours(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.maps.routeoptimization_v1.types.BatchOptimizeToursRequest, dict]): + The request object. Request to batch optimize tours as an asynchronous + operation. Each input file should contain one + ``OptimizeToursRequest``, and each output file will + contain one ``OptimizeToursResponse``. The request + contains information to read/write and parse the files. + All the input and output files should be under the same + project. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.maps.routeoptimization_v1.types.BatchOptimizeToursResponse` Response to a BatchOptimizeToursRequest. This is returned in + the Long Running Operation after the operation is + complete. + + """ + # 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, route_optimization_service.BatchOptimizeToursRequest): + request = route_optimization_service.BatchOptimizeToursRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_optimize_tours] + + # Certain 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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + route_optimization_service.BatchOptimizeToursResponse, + metadata_type=route_optimization_service.BatchOptimizeToursMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "RouteOptimizationClient": + 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() + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # 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 + + + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "RouteOptimizationClient", +) diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/README.rst b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/README.rst new file mode 100644 index 000000000000..777c90bfd2dd --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`RouteOptimizationTransport` is the ABC for all transports. +- public child `RouteOptimizationGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `RouteOptimizationGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseRouteOptimizationRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `RouteOptimizationRestTransport` 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-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/__init__.py b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/__init__.py new file mode 100644 index 000000000000..c8b6f8c69432 --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 RouteOptimizationTransport +from .grpc import RouteOptimizationGrpcTransport +from .grpc_asyncio import RouteOptimizationGrpcAsyncIOTransport +from .rest import RouteOptimizationRestTransport +from .rest import RouteOptimizationRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[RouteOptimizationTransport]] +_transport_registry['grpc'] = RouteOptimizationGrpcTransport +_transport_registry['grpc_asyncio'] = RouteOptimizationGrpcAsyncIOTransport +_transport_registry['rest'] = RouteOptimizationRestTransport + +__all__ = ( + 'RouteOptimizationTransport', + 'RouteOptimizationGrpcTransport', + 'RouteOptimizationGrpcAsyncIOTransport', + 'RouteOptimizationRestTransport', + 'RouteOptimizationRestInterceptor', +) diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/base.py b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/base.py new file mode 100644 index 000000000000..2ff60f79e53d --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/base.py @@ -0,0 +1,198 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.routeoptimization_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.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.longrunning import operations_pb2 # type: ignore +from google.maps.routeoptimization_v1.types import route_optimization_service + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class RouteOptimizationTransport(abc.ABC): + """Abstract transport class for RouteOptimization.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'routeoptimization.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: 'routeoptimization.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to 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.optimize_tours: gapic_v1.method.wrap_method( + self.optimize_tours, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=3600.0, + ), + default_timeout=3600.0, + client_info=client_info, + ), + self.batch_optimize_tours: gapic_v1.method.wrap_method( + self.batch_optimize_tours, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + 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 operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def optimize_tours(self) -> Callable[ + [route_optimization_service.OptimizeToursRequest], + Union[ + route_optimization_service.OptimizeToursResponse, + Awaitable[route_optimization_service.OptimizeToursResponse] + ]]: + raise NotImplementedError() + + @property + def batch_optimize_tours(self) -> Callable[ + [route_optimization_service.BatchOptimizeToursRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'RouteOptimizationTransport', +) diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/grpc.py b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/grpc.py new file mode 100644 index 000000000000..28739646e9bf --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/grpc.py @@ -0,0 +1,471 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message + +import grpc # type: ignore +import proto # type: ignore + +from google.longrunning import operations_pb2 # type: ignore +from google.maps.routeoptimization_v1.types import route_optimization_service +from .base import RouteOptimizationTransport, 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.maps.routeoptimization.v1.RouteOptimization", + "rpcName": 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.maps.routeoptimization.v1.RouteOptimization", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class RouteOptimizationGrpcTransport(RouteOptimizationTransport): + """gRPC backend transport for RouteOptimization. + + A service for optimizing vehicle tours. + + Validity of certain types of fields: + + - ``google.protobuf.Timestamp`` + + - Times are in Unix time: seconds since + 1970-01-01T00:00:00+00:00. + - seconds must be in [0, 253402300799], i.e. in + [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. + - nanos must be unset or set to 0. + + - ``google.protobuf.Duration`` + + - seconds must be in [0, 253402300799], i.e. in + [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. + - nanos must be unset or set to 0. + + - ``google.type.LatLng`` + + - latitude must be in [-90.0, 90.0]. + - longitude must be in [-180.0, 180.0]. + - at least one of latitude and longitude must be non-zero. + + This 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 = 'routeoptimization.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: 'routeoptimization.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to 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] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + 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 = 'routeoptimization.googleapis.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 operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def optimize_tours(self) -> Callable[ + [route_optimization_service.OptimizeToursRequest], + route_optimization_service.OptimizeToursResponse]: + r"""Return a callable for the optimize tours method over gRPC. + + Sends an ``OptimizeToursRequest`` containing a ``ShipmentModel`` + and returns an ``OptimizeToursResponse`` containing + ``ShipmentRoute``\ s, which are a set of routes to be performed + by vehicles minimizing the overall cost. + + A ``ShipmentModel`` model consists mainly of ``Shipment``\ s + that need to be carried out and ``Vehicle``\ s that can be used + to transport the ``Shipment``\ s. The ``ShipmentRoute``\ s + assign ``Shipment``\ s to ``Vehicle``\ s. More specifically, + they assign a series of ``Visit``\ s to each vehicle, where a + ``Visit`` corresponds to a ``VisitRequest``, which is a pickup + or delivery for a ``Shipment``. + + The goal is to provide an assignment of ``ShipmentRoute``\ s to + ``Vehicle``\ s that minimizes the total cost where cost has many + components defined in the ``ShipmentModel``. + + Returns: + Callable[[~.OptimizeToursRequest], + ~.OptimizeToursResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'optimize_tours' not in self._stubs: + self._stubs['optimize_tours'] = self._logged_channel.unary_unary( + '/google.maps.routeoptimization.v1.RouteOptimization/OptimizeTours', + request_serializer=route_optimization_service.OptimizeToursRequest.serialize, + response_deserializer=route_optimization_service.OptimizeToursResponse.deserialize, + ) + return self._stubs['optimize_tours'] + + @property + def batch_optimize_tours(self) -> Callable[ + [route_optimization_service.BatchOptimizeToursRequest], + operations_pb2.Operation]: + r"""Return a callable for the batch optimize tours method over gRPC. + + Optimizes vehicle tours for one or more ``OptimizeToursRequest`` + messages as a batch. + + This method is a Long Running Operation (LRO). The inputs for + optimization (``OptimizeToursRequest`` messages) and outputs + (``OptimizeToursResponse`` messages) are read from and written + to Cloud Storage in user-specified format. Like the + ``OptimizeTours`` method, each ``OptimizeToursRequest`` contains + a ``ShipmentModel`` and returns an ``OptimizeToursResponse`` + containing ``ShipmentRoute`` fields, which are a set of routes + to be performed by vehicles minimizing the overall cost. + + The user can poll ``operations.get`` to check the status of the + LRO: + + If the LRO ``done`` field is false, then at least one request is + still being processed. Other requests may have completed + successfully and their results are available in Cloud Storage. + + If the LRO's ``done`` field is true, then all requests have been + processed. Any successfully processed requests will have their + results available in Cloud Storage. Any requests that failed + will not have their results available in Cloud Storage. If the + LRO's ``error`` field is set, then it contains the error from + one of the failed requests. + + Returns: + Callable[[~.BatchOptimizeToursRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_optimize_tours' not in self._stubs: + self._stubs['batch_optimize_tours'] = self._logged_channel.unary_unary( + '/google.maps.routeoptimization.v1.RouteOptimization/BatchOptimizeTours', + request_serializer=route_optimization_service.BatchOptimizeToursRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_optimize_tours'] + + def close(self): + self._logged_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'RouteOptimizationGrpcTransport', +) diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/grpc_asyncio.py b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/grpc_asyncio.py new file mode 100644 index 000000000000..ae4a0e4f207d --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/grpc_asyncio.py @@ -0,0 +1,510 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.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.longrunning import operations_pb2 # type: ignore +from google.maps.routeoptimization_v1.types import route_optimization_service +from .base import RouteOptimizationTransport, DEFAULT_CLIENT_INFO +from .grpc import RouteOptimizationGrpcTransport + +try: + from google.api_core import client_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.maps.routeoptimization.v1.RouteOptimization", + "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.maps.routeoptimization.v1.RouteOptimization", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class RouteOptimizationGrpcAsyncIOTransport(RouteOptimizationTransport): + """gRPC AsyncIO backend transport for RouteOptimization. + + A service for optimizing vehicle tours. + + Validity of certain types of fields: + + - ``google.protobuf.Timestamp`` + + - Times are in Unix time: seconds since + 1970-01-01T00:00:00+00:00. + - seconds must be in [0, 253402300799], i.e. in + [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. + - nanos must be unset or set to 0. + + - ``google.protobuf.Duration`` + + - seconds must be in [0, 253402300799], i.e. in + [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. + - nanos must be unset or set to 0. + + - ``google.type.LatLng`` + + - latitude must be in [-90.0, 90.0]. + - longitude must be in [-180.0, 180.0]. + - at least one of latitude and longitude must be non-zero. + + This 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 = 'routeoptimization.googleapis.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 = 'routeoptimization.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: 'routeoptimization.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to 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] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + 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 operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def optimize_tours(self) -> Callable[ + [route_optimization_service.OptimizeToursRequest], + Awaitable[route_optimization_service.OptimizeToursResponse]]: + r"""Return a callable for the optimize tours method over gRPC. + + Sends an ``OptimizeToursRequest`` containing a ``ShipmentModel`` + and returns an ``OptimizeToursResponse`` containing + ``ShipmentRoute``\ s, which are a set of routes to be performed + by vehicles minimizing the overall cost. + + A ``ShipmentModel`` model consists mainly of ``Shipment``\ s + that need to be carried out and ``Vehicle``\ s that can be used + to transport the ``Shipment``\ s. The ``ShipmentRoute``\ s + assign ``Shipment``\ s to ``Vehicle``\ s. More specifically, + they assign a series of ``Visit``\ s to each vehicle, where a + ``Visit`` corresponds to a ``VisitRequest``, which is a pickup + or delivery for a ``Shipment``. + + The goal is to provide an assignment of ``ShipmentRoute``\ s to + ``Vehicle``\ s that minimizes the total cost where cost has many + components defined in the ``ShipmentModel``. + + Returns: + Callable[[~.OptimizeToursRequest], + Awaitable[~.OptimizeToursResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'optimize_tours' not in self._stubs: + self._stubs['optimize_tours'] = self._logged_channel.unary_unary( + '/google.maps.routeoptimization.v1.RouteOptimization/OptimizeTours', + request_serializer=route_optimization_service.OptimizeToursRequest.serialize, + response_deserializer=route_optimization_service.OptimizeToursResponse.deserialize, + ) + return self._stubs['optimize_tours'] + + @property + def batch_optimize_tours(self) -> Callable[ + [route_optimization_service.BatchOptimizeToursRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the batch optimize tours method over gRPC. + + Optimizes vehicle tours for one or more ``OptimizeToursRequest`` + messages as a batch. + + This method is a Long Running Operation (LRO). The inputs for + optimization (``OptimizeToursRequest`` messages) and outputs + (``OptimizeToursResponse`` messages) are read from and written + to Cloud Storage in user-specified format. Like the + ``OptimizeTours`` method, each ``OptimizeToursRequest`` contains + a ``ShipmentModel`` and returns an ``OptimizeToursResponse`` + containing ``ShipmentRoute`` fields, which are a set of routes + to be performed by vehicles minimizing the overall cost. + + The user can poll ``operations.get`` to check the status of the + LRO: + + If the LRO ``done`` field is false, then at least one request is + still being processed. Other requests may have completed + successfully and their results are available in Cloud Storage. + + If the LRO's ``done`` field is true, then all requests have been + processed. Any successfully processed requests will have their + results available in Cloud Storage. Any requests that failed + will not have their results available in Cloud Storage. If the + LRO's ``error`` field is set, then it contains the error from + one of the failed requests. + + Returns: + Callable[[~.BatchOptimizeToursRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_optimize_tours' not in self._stubs: + self._stubs['batch_optimize_tours'] = self._logged_channel.unary_unary( + '/google.maps.routeoptimization.v1.RouteOptimization/BatchOptimizeTours', + request_serializer=route_optimization_service.BatchOptimizeToursRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_optimize_tours'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.optimize_tours: self._wrap_method( + self.optimize_tours, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=3600.0, + ), + default_timeout=3600.0, + client_info=client_info, + ), + self.batch_optimize_tours: self._wrap_method( + self.batch_optimize_tours, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + 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" + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + +__all__ = ( + 'RouteOptimizationGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/rest.py b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/rest.py new file mode 100644 index 000000000000..40fc33e37335 --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/rest.py @@ -0,0 +1,692 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +from google.protobuf import json_format +from google.api_core import operations_v1 + +from requests import __version__ as requests_version +import dataclasses +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + + +from google.maps.routeoptimization_v1.types import route_optimization_service +from google.longrunning import operations_pb2 # type: ignore + + +from .rest_base import _BaseRouteOptimizationRestTransport +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}", +) + + +class RouteOptimizationRestInterceptor: + """Interceptor for RouteOptimization. + + 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 RouteOptimizationRestTransport. + + .. code-block:: python + class MyCustomRouteOptimizationInterceptor(RouteOptimizationRestInterceptor): + def pre_batch_optimize_tours(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_optimize_tours(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_optimize_tours(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_optimize_tours(self, response): + logging.log(f"Received response: {response}") + return response + + transport = RouteOptimizationRestTransport(interceptor=MyCustomRouteOptimizationInterceptor()) + client = RouteOptimizationClient(transport=transport) + + + """ + def pre_batch_optimize_tours(self, request: route_optimization_service.BatchOptimizeToursRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[route_optimization_service.BatchOptimizeToursRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for batch_optimize_tours + + Override in a subclass to manipulate the request or metadata + before they are sent to the RouteOptimization server. + """ + return request, metadata + + def post_batch_optimize_tours(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for batch_optimize_tours + + Override in a subclass to manipulate the response + after it is returned by the RouteOptimization server but before + it is returned to user code. + """ + return response + + def pre_optimize_tours(self, request: route_optimization_service.OptimizeToursRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[route_optimization_service.OptimizeToursRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for optimize_tours + + Override in a subclass to manipulate the request or metadata + before they are sent to the RouteOptimization server. + """ + return request, metadata + + def post_optimize_tours(self, response: route_optimization_service.OptimizeToursResponse) -> route_optimization_service.OptimizeToursResponse: + """Post-rpc interceptor for optimize_tours + + Override in a subclass to manipulate the response + after it is returned by the RouteOptimization server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the RouteOptimization server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the RouteOptimization server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class RouteOptimizationRestStub: + _session: AuthorizedSession + _host: str + _interceptor: RouteOptimizationRestInterceptor + + +class RouteOptimizationRestTransport(_BaseRouteOptimizationRestTransport): + """REST backend synchronous transport for RouteOptimization. + + A service for optimizing vehicle tours. + + Validity of certain types of fields: + + - ``google.protobuf.Timestamp`` + + - Times are in Unix time: seconds since + 1970-01-01T00:00:00+00:00. + - seconds must be in [0, 253402300799], i.e. in + [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. + - nanos must be unset or set to 0. + + - ``google.protobuf.Duration`` + + - seconds must be in [0, 253402300799], i.e. in + [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. + - nanos must be unset or set to 0. + + - ``google.type.LatLng`` + + - latitude must be in [-90.0, 90.0]. + - longitude must be in [-180.0, 180.0]. + - at least one of latitude and longitude must be non-zero. + + This 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 = 'routeoptimization.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[RouteOptimizationRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'routeoptimization.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to 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) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or RouteOptimizationRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _BatchOptimizeTours(_BaseRouteOptimizationRestTransport._BaseBatchOptimizeTours, RouteOptimizationRestStub): + def __hash__(self): + return hash("RouteOptimizationRestTransport.BatchOptimizeTours") + + @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: route_optimization_service.BatchOptimizeToursRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the batch optimize tours method over HTTP. + + Args: + request (~.route_optimization_service.BatchOptimizeToursRequest): + The request object. Request to batch optimize tours as an asynchronous + operation. Each input file should contain one + ``OptimizeToursRequest``, and each output file will + contain one ``OptimizeToursResponse``. The request + contains information to read/write and parse the files. + All the input and output files should be under the same + project. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseRouteOptimizationRestTransport._BaseBatchOptimizeTours._get_http_options() + + request, metadata = self._interceptor.pre_batch_optimize_tours(request, metadata) + transcoded_request = _BaseRouteOptimizationRestTransport._BaseBatchOptimizeTours._get_transcoded_request(http_options, request) + + body = _BaseRouteOptimizationRestTransport._BaseBatchOptimizeTours._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseRouteOptimizationRestTransport._BaseBatchOptimizeTours._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(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.maps.routeoptimization_v1.RouteOptimizationClient.BatchOptimizeTours", + extra = { + "serviceName": "google.maps.routeoptimization.v1.RouteOptimization", + "rpcName": "BatchOptimizeTours", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RouteOptimizationRestTransport._BatchOptimizeTours._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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_batch_optimize_tours(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.maps.routeoptimization_v1.RouteOptimizationClient.batch_optimize_tours", + extra = { + "serviceName": "google.maps.routeoptimization.v1.RouteOptimization", + "rpcName": "BatchOptimizeTours", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _OptimizeTours(_BaseRouteOptimizationRestTransport._BaseOptimizeTours, RouteOptimizationRestStub): + def __hash__(self): + return hash("RouteOptimizationRestTransport.OptimizeTours") + + @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: route_optimization_service.OptimizeToursRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> route_optimization_service.OptimizeToursResponse: + r"""Call the optimize tours method over HTTP. + + Args: + request (~.route_optimization_service.OptimizeToursRequest): + The request object. Request to be given to a tour + optimization solver which defines the + shipment model to solve as well as + optimization parameters. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.route_optimization_service.OptimizeToursResponse: + Response after solving a tour + optimization problem containing the + routes followed by each vehicle, the + shipments which have been skipped and + the overall cost of the solution. + + """ + + http_options = _BaseRouteOptimizationRestTransport._BaseOptimizeTours._get_http_options() + + request, metadata = self._interceptor.pre_optimize_tours(request, metadata) + transcoded_request = _BaseRouteOptimizationRestTransport._BaseOptimizeTours._get_transcoded_request(http_options, request) + + body = _BaseRouteOptimizationRestTransport._BaseOptimizeTours._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseRouteOptimizationRestTransport._BaseOptimizeTours._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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.maps.routeoptimization_v1.RouteOptimizationClient.OptimizeTours", + extra = { + "serviceName": "google.maps.routeoptimization.v1.RouteOptimization", + "rpcName": "OptimizeTours", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RouteOptimizationRestTransport._OptimizeTours._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 = route_optimization_service.OptimizeToursResponse() + pb_resp = route_optimization_service.OptimizeToursResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_optimize_tours(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = route_optimization_service.OptimizeToursResponse.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.maps.routeoptimization_v1.RouteOptimizationClient.optimize_tours", + extra = { + "serviceName": "google.maps.routeoptimization.v1.RouteOptimization", + "rpcName": "OptimizeTours", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def batch_optimize_tours(self) -> Callable[ + [route_optimization_service.BatchOptimizeToursRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchOptimizeTours(self._session, self._host, self._interceptor) # type: ignore + + @property + def optimize_tours(self) -> Callable[ + [route_optimization_service.OptimizeToursRequest], + route_optimization_service.OptimizeToursResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._OptimizeTours(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(_BaseRouteOptimizationRestTransport._BaseGetOperation, RouteOptimizationRestStub): + def __hash__(self): + return hash("RouteOptimizationRestTransport.GetOperation") + + @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: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = _BaseRouteOptimizationRestTransport._BaseGetOperation._get_http_options() + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BaseRouteOptimizationRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseRouteOptimizationRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.maps.routeoptimization_v1.RouteOptimizationClient.GetOperation", + extra = { + "serviceName": "google.maps.routeoptimization.v1.RouteOptimization", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RouteOptimizationRestTransport._GetOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.maps.routeoptimization_v1.RouteOptimizationAsyncClient.GetOperation", + extra = { + "serviceName": "google.maps.routeoptimization.v1.RouteOptimization", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'RouteOptimizationRestTransport', +) diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/rest_base.py b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/rest_base.py new file mode 100644 index 000000000000..849347da5750 --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/rest_base.py @@ -0,0 +1,221 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 RouteOptimizationTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.maps.routeoptimization_v1.types import route_optimization_service +from google.longrunning import operations_pb2 # type: ignore + + +class _BaseRouteOptimizationRestTransport(RouteOptimizationTransport): + """Base REST backend transport for RouteOptimization. + + 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 = 'routeoptimization.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: 'routeoptimization.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 _BaseBatchOptimizeTours: + 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': '/v1/{parent=projects/*/locations/*}:batchOptimizeTours', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{parent=projects/*}:batchOptimizeTours', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = route_optimization_service.BatchOptimizeToursRequest.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(_BaseRouteOptimizationRestTransport._BaseBatchOptimizeTours._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseOptimizeTours: + 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': '/v1/{parent=projects/*/locations/*}:optimizeTours', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{parent=projects/*}:optimizeTours', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = route_optimization_service.OptimizeToursRequest.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(_BaseRouteOptimizationRestTransport._BaseOptimizeTours._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + 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': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + +__all__=( + '_BaseRouteOptimizationRestTransport', +) diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/types/__init__.py b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/types/__init__.py new file mode 100644 index 000000000000..a2de944fa5be --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/types/__init__.py @@ -0,0 +1,74 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .route_optimization_service import ( + AggregatedMetrics, + BatchOptimizeToursMetadata, + BatchOptimizeToursRequest, + BatchOptimizeToursResponse, + BreakRule, + DistanceLimit, + GcsDestination, + GcsSource, + InjectedSolutionConstraint, + InputConfig, + Location, + OptimizeToursRequest, + OptimizeToursResponse, + OptimizeToursValidationError, + OutputConfig, + RouteModifiers, + Shipment, + ShipmentModel, + ShipmentRoute, + ShipmentTypeIncompatibility, + ShipmentTypeRequirement, + SkippedShipment, + TimeWindow, + TransitionAttributes, + Vehicle, + Waypoint, + DataFormat, +) + +__all__ = ( + 'AggregatedMetrics', + 'BatchOptimizeToursMetadata', + 'BatchOptimizeToursRequest', + 'BatchOptimizeToursResponse', + 'BreakRule', + 'DistanceLimit', + 'GcsDestination', + 'GcsSource', + 'InjectedSolutionConstraint', + 'InputConfig', + 'Location', + 'OptimizeToursRequest', + 'OptimizeToursResponse', + 'OptimizeToursValidationError', + 'OutputConfig', + 'RouteModifiers', + 'Shipment', + 'ShipmentModel', + 'ShipmentRoute', + 'ShipmentTypeIncompatibility', + 'ShipmentTypeRequirement', + 'SkippedShipment', + 'TimeWindow', + 'TransitionAttributes', + 'Vehicle', + 'Waypoint', + 'DataFormat', +) diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/types/route_optimization_service.py b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/types/route_optimization_service.py new file mode 100644 index 000000000000..f361d0359c2a --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/types/route_optimization_service.py @@ -0,0 +1,3776 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routeoptimization.v1', + manifest={ + 'DataFormat', + 'BatchOptimizeToursRequest', + 'BatchOptimizeToursResponse', + 'BatchOptimizeToursMetadata', + 'OptimizeToursRequest', + 'OptimizeToursResponse', + 'ShipmentModel', + 'Shipment', + 'ShipmentTypeIncompatibility', + 'ShipmentTypeRequirement', + 'RouteModifiers', + 'Vehicle', + 'TimeWindow', + 'DistanceLimit', + 'TransitionAttributes', + 'Waypoint', + 'Location', + 'BreakRule', + 'ShipmentRoute', + 'SkippedShipment', + 'AggregatedMetrics', + 'InjectedSolutionConstraint', + 'OptimizeToursValidationError', + 'InputConfig', + 'OutputConfig', + 'GcsSource', + 'GcsDestination', + }, +) + + +class DataFormat(proto.Enum): + r"""Data formats for input and output files. + + Values: + DATA_FORMAT_UNSPECIFIED (0): + Invalid value, format must not be + UNSPECIFIED. + JSON (1): + JavaScript Object Notation. + PROTO_TEXT (2): + Protocol Buffers text format. See + https://protobuf.dev/reference/protobuf/textformat-spec/ + """ + DATA_FORMAT_UNSPECIFIED = 0 + JSON = 1 + PROTO_TEXT = 2 + + +class BatchOptimizeToursRequest(proto.Message): + r"""Request to batch optimize tours as an asynchronous operation. Each + input file should contain one ``OptimizeToursRequest``, and each + output file will contain one ``OptimizeToursResponse``. The request + contains information to read/write and parse the files. All the + input and output files should be under the same project. + + Attributes: + parent (str): + Required. Target project and location to make a call. + + Format: + + - ``projects/{project-id}`` + - ``projects/{project-id}/locations/{location-id}`` + + If no location is specified, a region will be chosen + automatically. + model_configs (MutableSequence[google.maps.routeoptimization_v1.types.BatchOptimizeToursRequest.AsyncModelConfig]): + Required. Input/Output information each + purchase model, such as file paths and data + formats. + """ + + class AsyncModelConfig(proto.Message): + r"""Information for solving one optimization model + asynchronously. + + Attributes: + display_name (str): + Optional. User defined model name, can be + used as alias by users to keep track of models. + input_config (google.maps.routeoptimization_v1.types.InputConfig): + Required. Information about the input model. + output_config (google.maps.routeoptimization_v1.types.OutputConfig): + Required. The desired output location + information. + """ + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + input_config: 'InputConfig' = proto.Field( + proto.MESSAGE, + number=2, + message='InputConfig', + ) + output_config: 'OutputConfig' = proto.Field( + proto.MESSAGE, + number=3, + message='OutputConfig', + ) + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + model_configs: MutableSequence[AsyncModelConfig] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=AsyncModelConfig, + ) + + +class BatchOptimizeToursResponse(proto.Message): + r"""Response to a ``BatchOptimizeToursRequest``. This is returned in the + Long Running Operation after the operation is complete. + + """ + + +class BatchOptimizeToursMetadata(proto.Message): + r"""Operation metadata for ``BatchOptimizeToursRequest`` calls. + """ + + +class OptimizeToursRequest(proto.Message): + r"""Request to be given to a tour optimization solver which + defines the shipment model to solve as well as optimization + parameters. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent (str): + Required. Target project or location to make a call. + + Format: + + - ``projects/{project-id}`` + - ``projects/{project-id}/locations/{location-id}`` + + If no location is specified, a region will be chosen + automatically. + timeout (google.protobuf.duration_pb2.Duration): + If this timeout is set, the server returns a + response before the timeout period has elapsed + or the server deadline for synchronous requests + is reached, whichever is sooner. + + For asynchronous requests, the server will + generate a solution (if possible) before the + timeout has elapsed. + model (google.maps.routeoptimization_v1.types.ShipmentModel): + Shipment model to solve. + solving_mode (google.maps.routeoptimization_v1.types.OptimizeToursRequest.SolvingMode): + By default, the solving mode is ``DEFAULT_SOLVE`` (0). + search_mode (google.maps.routeoptimization_v1.types.OptimizeToursRequest.SearchMode): + Search mode used to solve the request. + injected_first_solution_routes (MutableSequence[google.maps.routeoptimization_v1.types.ShipmentRoute]): + Guide the optimization algorithm in finding a first solution + that is similar to a previous solution. + + The model is constrained when the first solution is built. + Any shipments not performed on a route are implicitly + skipped in the first solution, but they may be performed in + successive solutions. + + The solution must satisfy some basic validity assumptions: + + - for all routes, ``vehicle_index`` must be in range and + not be duplicated. + - for all visits, ``shipment_index`` and + ``visit_request_index`` must be in range. + - a shipment may only be referenced on one route. + - the pickup of a pickup-delivery shipment must be + performed before the delivery. + - no more than one pickup alternative or delivery + alternative of a shipment may be performed. + - for all routes, times are increasing (i.e., + ``vehicle_start_time <= visits[0].start_time <= visits[1].start_time ... <= vehicle_end_time``). + - a shipment may only be performed on a vehicle that is + allowed. A vehicle is allowed if + [Shipment.allowed_vehicle_indices][google.maps.routeoptimization.v1.Shipment.allowed_vehicle_indices] + is empty or its ``vehicle_index`` is included in + [Shipment.allowed_vehicle_indices][google.maps.routeoptimization.v1.Shipment.allowed_vehicle_indices]. + + If the injected solution is not feasible, a validation error + is not necessarily returned and an error indicating + infeasibility may be returned instead. + injected_solution_constraint (google.maps.routeoptimization_v1.types.InjectedSolutionConstraint): + Constrain the optimization algorithm to find + a final solution that is similar to a previous + solution. For example, this may be used to + freeze portions of routes which have already + been completed or which are to be completed but + must not be modified. + + If the injected solution is not feasible, a + validation error is not necessarily returned and + an error indicating infeasibility may be + returned instead. + refresh_details_routes (MutableSequence[google.maps.routeoptimization_v1.types.ShipmentRoute]): + If non-empty, the given routes will be refreshed, without + modifying their underlying sequence of visits or travel + times: only other details will be updated. This does not + solve the model. + + As of 2020/11, this only populates the polylines of + non-empty routes and requires that ``populate_polylines`` is + true. + + The ``route_polyline`` fields of the passed-in routes may be + inconsistent with route ``transitions``. + + This field must not be used together with + ``injected_first_solution_routes`` or + ``injected_solution_constraint``. + + ``Shipment.ignore`` and ``Vehicle.ignore`` have no effect on + the behavior. Polylines are still populated between all + visits in all non-empty routes regardless of whether the + related shipments or vehicles are ignored. + interpret_injected_solutions_using_labels (bool): + If true: + + - uses + [ShipmentRoute.vehicle_label][google.maps.routeoptimization.v1.ShipmentRoute.vehicle_label] + instead of ``vehicle_index`` to match routes in an + injected solution with vehicles in the request; reuses + the mapping of original + [ShipmentRoute.vehicle_index][google.maps.routeoptimization.v1.ShipmentRoute.vehicle_index] + to new + [ShipmentRoute.vehicle_index][google.maps.routeoptimization.v1.ShipmentRoute.vehicle_index] + to update + [ConstraintRelaxation.vehicle_indices][google.maps.routeoptimization.v1.InjectedSolutionConstraint.ConstraintRelaxation.vehicle_indices] + if non-empty, but the mapping must be unambiguous (i.e., + multiple ``ShipmentRoute``\ s must not share the same + original ``vehicle_index``). + - uses + [ShipmentRoute.Visit.shipment_label][google.maps.routeoptimization.v1.ShipmentRoute.Visit.shipment_label] + instead of ``shipment_index`` to match visits in an + injected solution with shipments in the request; + - uses + [SkippedShipment.label][google.maps.routeoptimization.v1.SkippedShipment.label] + instead of + [SkippedShipment.index][google.maps.routeoptimization.v1.SkippedShipment.index] + to match skipped shipments in the injected solution with + request shipments. + + This interpretation applies to the + ``injected_first_solution_routes``, + ``injected_solution_constraint``, and + ``refresh_details_routes`` fields. It can be used when + shipment or vehicle indices in the request have changed + since the solution was created, perhaps because shipments or + vehicles have been removed from or added to the request. + + If true, labels in the following categories must appear at + most once in their category: + + - [Vehicle.label][google.maps.routeoptimization.v1.Vehicle.label] + in the request; + - [Shipment.label][google.maps.routeoptimization.v1.Shipment.label] + in the request; + - [ShipmentRoute.vehicle_label][google.maps.routeoptimization.v1.ShipmentRoute.vehicle_label] + in the injected solution; + - [SkippedShipment.label][google.maps.routeoptimization.v1.SkippedShipment.label] + and + [ShipmentRoute.Visit.shipment_label][google.maps.routeoptimization.v1.ShipmentRoute.Visit.shipment_label] + in the injected solution (except pickup/delivery visit + pairs, whose ``shipment_label`` must appear twice). + + If a ``vehicle_label`` in the injected solution does not + correspond to a request vehicle, the corresponding route is + removed from the solution along with its visits. If a + ``shipment_label`` in the injected solution does not + correspond to a request shipment, the corresponding visit is + removed from the solution. If a + [SkippedShipment.label][google.maps.routeoptimization.v1.SkippedShipment.label] + in the injected solution does not correspond to a request + shipment, the ``SkippedShipment`` is removed from the + solution. + + Removing route visits or entire routes from an injected + solution may have an effect on the implied constraints, + which may lead to change in solution, validation errors, or + infeasibility. + + NOTE: The caller must ensure that each + [Vehicle.label][google.maps.routeoptimization.v1.Vehicle.label] + (resp. + [Shipment.label][google.maps.routeoptimization.v1.Shipment.label]) + uniquely identifies a vehicle (resp. shipment) entity used + across the two relevant requests: the past request that + produced the ``OptimizeToursResponse`` used in the injected + solution and the current request that includes the injected + solution. The uniqueness checks described above are not + enough to guarantee this requirement. + consider_road_traffic (bool): + Consider traffic estimation in calculating ``ShipmentRoute`` + fields + [Transition.travel_duration][google.maps.routeoptimization.v1.ShipmentRoute.Transition.travel_duration], + [Visit.start_time][google.maps.routeoptimization.v1.ShipmentRoute.Visit.start_time], + and ``vehicle_end_time``; in setting the + [ShipmentRoute.has_traffic_infeasibilities][google.maps.routeoptimization.v1.ShipmentRoute.has_traffic_infeasibilities] + field, and in calculating the + [OptimizeToursResponse.total_cost][google.maps.routeoptimization.v1.OptimizeToursResponse.total_cost] + field. + populate_polylines (bool): + If true, polylines will be populated in response + ``ShipmentRoute``\ s. + populate_transition_polylines (bool): + If true, polylines and route tokens will be populated in + response + [ShipmentRoute.transitions][google.maps.routeoptimization.v1.ShipmentRoute.transitions]. + allow_large_deadline_despite_interruption_risk (bool): + If this is set, then the request can have a + deadline (see https://grpc.io/blog/deadlines) of + up to 60 minutes. Otherwise, the maximum + deadline is only 30 minutes. Note that + long-lived requests have a significantly larger + (but still small) risk of interruption. + use_geodesic_distances (bool): + If true, travel distances will be computed using geodesic + distances instead of Google Maps distances, and travel times + will be computed using geodesic distances with a speed + defined by ``geodesic_meters_per_second``. + geodesic_meters_per_second (float): + When ``use_geodesic_distances`` is true, this field must be + set and defines the speed applied to compute travel times. + Its value must be at least 1.0 meters/seconds. + + This field is a member of `oneof`_ ``_geodesic_meters_per_second``. + max_validation_errors (int): + Truncates the number of validation errors returned. These + errors are typically attached to an INVALID_ARGUMENT error + payload as a BadRequest error detail + (https://cloud.google.com/apis/design/errors#error_details), + unless solving_mode=VALIDATE_ONLY: see the + [OptimizeToursResponse.validation_errors][google.maps.routeoptimization.v1.OptimizeToursResponse.validation_errors] + field. This defaults to 100 and is capped at 10,000. + + This field is a member of `oneof`_ ``_max_validation_errors``. + label (str): + Label that may be used to identify this request, reported + back in the + [OptimizeToursResponse.request_label][google.maps.routeoptimization.v1.OptimizeToursResponse.request_label]. + """ + class SolvingMode(proto.Enum): + r"""Defines how the solver should handle the request. In all modes but + ``VALIDATE_ONLY``, if the request is invalid, you will receive an + ``INVALID_REQUEST`` error. See + [max_validation_errors][google.maps.routeoptimization.v1.OptimizeToursRequest.max_validation_errors] + to cap the number of errors returned. + + Values: + DEFAULT_SOLVE (0): + Solve the model. Warnings may be issued in + [OptimizeToursResponse.validation_errors][google.cloud.optimization.v1.OptimizeToursResponse.validation_errors]. + VALIDATE_ONLY (1): + Only validates the model without solving it: populates as + many + [OptimizeToursResponse.validation_errors][google.maps.routeoptimization.v1.OptimizeToursResponse.validation_errors] + as possible. + DETECT_SOME_INFEASIBLE_SHIPMENTS (2): + Only populates + [OptimizeToursResponse.validation_errors][google.maps.routeoptimization.v1.OptimizeToursResponse.validation_errors] + or + [OptimizeToursResponse.skipped_shipments][google.maps.routeoptimization.v1.OptimizeToursResponse.skipped_shipments], + and doesn't actually solve the rest of the request + (``status`` and ``routes`` are unset in the response). If + infeasibilities in ``injected_solution_constraint`` routes + are detected they are populated in the + [OptimizeToursResponse.validation_errors][google.maps.routeoptimization.v1.OptimizeToursResponse.validation_errors] + field and + [OptimizeToursResponse.skipped_shipments][google.maps.routeoptimization.v1.OptimizeToursResponse.skipped_shipments] + is left empty. + + *IMPORTANT*: not all infeasible shipments are returned here, + but only the ones that are detected as infeasible during + preprocessing. + """ + DEFAULT_SOLVE = 0 + VALIDATE_ONLY = 1 + DETECT_SOME_INFEASIBLE_SHIPMENTS = 2 + + class SearchMode(proto.Enum): + r"""Mode defining the behavior of the search, trading off latency + versus solution quality. In all modes, the global request + deadline is enforced. + + Values: + SEARCH_MODE_UNSPECIFIED (0): + Unspecified search mode, equivalent to ``RETURN_FAST``. + RETURN_FAST (1): + Stop the search after finding the first good + solution. + CONSUME_ALL_AVAILABLE_TIME (2): + Spend all the available time to search for + better solutions. + """ + SEARCH_MODE_UNSPECIFIED = 0 + RETURN_FAST = 1 + CONSUME_ALL_AVAILABLE_TIME = 2 + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + timeout: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + model: 'ShipmentModel' = proto.Field( + proto.MESSAGE, + number=3, + message='ShipmentModel', + ) + solving_mode: SolvingMode = proto.Field( + proto.ENUM, + number=4, + enum=SolvingMode, + ) + search_mode: SearchMode = proto.Field( + proto.ENUM, + number=6, + enum=SearchMode, + ) + injected_first_solution_routes: MutableSequence['ShipmentRoute'] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message='ShipmentRoute', + ) + injected_solution_constraint: 'InjectedSolutionConstraint' = proto.Field( + proto.MESSAGE, + number=8, + message='InjectedSolutionConstraint', + ) + refresh_details_routes: MutableSequence['ShipmentRoute'] = proto.RepeatedField( + proto.MESSAGE, + number=9, + message='ShipmentRoute', + ) + interpret_injected_solutions_using_labels: bool = proto.Field( + proto.BOOL, + number=10, + ) + consider_road_traffic: bool = proto.Field( + proto.BOOL, + number=11, + ) + populate_polylines: bool = proto.Field( + proto.BOOL, + number=12, + ) + populate_transition_polylines: bool = proto.Field( + proto.BOOL, + number=13, + ) + allow_large_deadline_despite_interruption_risk: bool = proto.Field( + proto.BOOL, + number=14, + ) + use_geodesic_distances: bool = proto.Field( + proto.BOOL, + number=15, + ) + geodesic_meters_per_second: float = proto.Field( + proto.DOUBLE, + number=16, + optional=True, + ) + max_validation_errors: int = proto.Field( + proto.INT32, + number=5, + optional=True, + ) + label: str = proto.Field( + proto.STRING, + number=17, + ) + + +class OptimizeToursResponse(proto.Message): + r"""Response after solving a tour optimization problem containing + the routes followed by each vehicle, the shipments which have + been skipped and the overall cost of the solution. + + Attributes: + routes (MutableSequence[google.maps.routeoptimization_v1.types.ShipmentRoute]): + Routes computed for each vehicle; the i-th + route corresponds to the i-th vehicle in the + model. + request_label (str): + Copy of the + [OptimizeToursRequest.label][google.maps.routeoptimization.v1.OptimizeToursRequest.label], + if a label was specified in the request. + skipped_shipments (MutableSequence[google.maps.routeoptimization_v1.types.SkippedShipment]): + The list of all shipments skipped. + validation_errors (MutableSequence[google.maps.routeoptimization_v1.types.OptimizeToursValidationError]): + List of all the validation errors that we were able to + detect independently. See the "MULTIPLE ERRORS" explanation + for the + [OptimizeToursValidationError][google.maps.routeoptimization.v1.OptimizeToursValidationError] + message. Instead of errors, this will include warnings in + the case ``solving_mode`` is ``DEFAULT_SOLVE``. + metrics (google.maps.routeoptimization_v1.types.OptimizeToursResponse.Metrics): + Duration, distance and usage metrics for this + solution. + """ + + class Metrics(proto.Message): + r"""Overall metrics, aggregated over all routes. + + Attributes: + aggregated_route_metrics (google.maps.routeoptimization_v1.types.AggregatedMetrics): + Aggregated over the routes. Each metric is the sum (or max, + for loads) over all + [ShipmentRoute.metrics][google.maps.routeoptimization.v1.ShipmentRoute.metrics] + fields of the same name. + skipped_mandatory_shipment_count (int): + Number of mandatory shipments skipped. + used_vehicle_count (int): + Number of vehicles used. Note: if a vehicle route is empty + and + [Vehicle.used_if_route_is_empty][google.maps.routeoptimization.v1.Vehicle.used_if_route_is_empty] + is true, the vehicle is considered used. + earliest_vehicle_start_time (google.protobuf.timestamp_pb2.Timestamp): + The earliest start time for a used vehicle, computed as the + minimum over all used vehicles of + [ShipmentRoute.vehicle_start_time][google.maps.routeoptimization.v1.ShipmentRoute.vehicle_start_time]. + latest_vehicle_end_time (google.protobuf.timestamp_pb2.Timestamp): + The latest end time for a used vehicle, computed as the + maximum over all used vehicles of + [ShipmentRoute.vehicle_end_time][google.maps.routeoptimization.v1.ShipmentRoute.vehicle_end_time]. + costs (MutableMapping[str, float]): + Cost of the solution, broken down by cost-related request + fields. The keys are proto paths, relative to the input + OptimizeToursRequest, e.g. "model.shipments.pickups.cost", + and the values are the total cost generated by the + corresponding cost field, aggregated over the whole + solution. In other words, + costs["model.shipments.pickups.cost"] is the sum of all + pickup costs over the solution. All costs defined in the + model are reported in detail here with the exception of + costs related to TransitionAttributes that are only reported + in an aggregated way as of 2022/01. + total_cost (float): + Total cost of the solution. The sum of all + values in the costs map. + """ + + aggregated_route_metrics: 'AggregatedMetrics' = proto.Field( + proto.MESSAGE, + number=1, + message='AggregatedMetrics', + ) + skipped_mandatory_shipment_count: int = proto.Field( + proto.INT32, + number=2, + ) + used_vehicle_count: int = proto.Field( + proto.INT32, + number=3, + ) + earliest_vehicle_start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + latest_vehicle_end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + costs: MutableMapping[str, float] = proto.MapField( + proto.STRING, + proto.DOUBLE, + number=10, + ) + total_cost: float = proto.Field( + proto.DOUBLE, + number=6, + ) + + routes: MutableSequence['ShipmentRoute'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ShipmentRoute', + ) + request_label: str = proto.Field( + proto.STRING, + number=3, + ) + skipped_shipments: MutableSequence['SkippedShipment'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='SkippedShipment', + ) + validation_errors: MutableSequence['OptimizeToursValidationError'] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message='OptimizeToursValidationError', + ) + metrics: Metrics = proto.Field( + proto.MESSAGE, + number=6, + message=Metrics, + ) + + +class ShipmentModel(proto.Message): + r"""A shipment model contains a set of shipments which must be performed + by a set of vehicles, while minimizing the overall cost, which is + the sum of: + + - the cost of routing the vehicles (sum of cost per total time, + cost per travel time, and fixed cost over all vehicles). + - the unperformed shipment penalties. + - the cost of the global duration of the shipments + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + shipments (MutableSequence[google.maps.routeoptimization_v1.types.Shipment]): + Set of shipments which must be performed in + the model. + vehicles (MutableSequence[google.maps.routeoptimization_v1.types.Vehicle]): + Set of vehicles which can be used to perform + visits. + max_active_vehicles (int): + Constrains the maximum number of active + vehicles. A vehicle is active if its route + performs at least one shipment. This can be used + to limit the number of routes in the case where + there are fewer drivers than vehicles and that + the fleet of vehicles is heterogeneous. The + optimization will then select the best subset of + vehicles to use. Must be strictly positive. + + This field is a member of `oneof`_ ``_max_active_vehicles``. + global_start_time (google.protobuf.timestamp_pb2.Timestamp): + Global start and end time of the model: no times outside of + this range can be considered valid. + + The model's time span must be less than a year, i.e. the + ``global_end_time`` and the ``global_start_time`` must be + within 31536000 seconds of each other. + + When using ``cost_per_*hour`` fields, you might want to set + this window to a smaller interval to increase performance + (eg. if you model a single day, you should set the global + time limits to that day). If unset, 00:00:00 UTC, January 1, + 1970 (i.e. seconds: 0, nanos: 0) is used as default. + global_end_time (google.protobuf.timestamp_pb2.Timestamp): + If unset, 00:00:00 UTC, January 1, 1971 (i.e. + seconds: 31536000, nanos: 0) is used as default. + global_duration_cost_per_hour (float): + The "global duration" of the overall plan is the difference + between the earliest effective start time and the latest + effective end time of all vehicles. Users can assign a cost + per hour to that quantity to try and optimize for earliest + job completion, for example. This cost must be in the same + unit as + [Shipment.penalty_cost][google.maps.routeoptimization.v1.Shipment.penalty_cost]. + duration_distance_matrices (MutableSequence[google.maps.routeoptimization_v1.types.ShipmentModel.DurationDistanceMatrix]): + Specifies duration and distance matrices used in the model. + If this field is empty, Google Maps or geodesic distances + will be used instead, depending on the value of the + ``use_geodesic_distances`` field. If it is not empty, + ``use_geodesic_distances`` cannot be true and neither + ``duration_distance_matrix_src_tags`` nor + ``duration_distance_matrix_dst_tags`` can be empty. + + Usage examples: + + - There are two locations: locA and locB. + - 1 vehicle starting its route at locA and ending it at + locA. + - 1 pickup visit request at locB. + + :: + + model { + vehicles { start_tags: "locA" end_tags: "locA" } + shipments { pickups { tags: "locB" } } + duration_distance_matrix_src_tags: "locA" + duration_distance_matrix_src_tags: "locB" + duration_distance_matrix_dst_tags: "locA" + duration_distance_matrix_dst_tags: "locB" + duration_distance_matrices { + rows { # from: locA + durations { seconds: 0 } meters: 0 # to: locA + durations { seconds: 100 } meters: 1000 # to: locB + } + rows { # from: locB + durations { seconds: 102 } meters: 990 # to: locA + durations { seconds: 0 } meters: 0 # to: locB + } + } + } + + - There are three locations: locA, locB and locC. + - 1 vehicle starting its route at locA and ending it at + locB, using matrix "fast". + - 1 vehicle starting its route at locB and ending it at + locB, using matrix "slow". + - 1 vehicle starting its route at locB and ending it at + locB, using matrix "fast". + - 1 pickup visit request at locC. + + :: + + model { + vehicles { start_tags: "locA" end_tags: "locB" start_tags: "fast" } + vehicles { start_tags: "locB" end_tags: "locB" start_tags: "slow" } + vehicles { start_tags: "locB" end_tags: "locB" start_tags: "fast" } + shipments { pickups { tags: "locC" } } + duration_distance_matrix_src_tags: "locA" + duration_distance_matrix_src_tags: "locB" + duration_distance_matrix_src_tags: "locC" + duration_distance_matrix_dst_tags: "locB" + duration_distance_matrix_dst_tags: "locC" + duration_distance_matrices { + vehicle_start_tag: "fast" + rows { # from: locA + durations { seconds: 1000 } meters: 2000 # to: locB + durations { seconds: 600 } meters: 1000 # to: locC + } + rows { # from: locB + durations { seconds: 0 } meters: 0 # to: locB + durations { seconds: 700 } meters: 1200 # to: locC + } + rows { # from: locC + durations { seconds: 702 } meters: 1190 # to: locB + durations { seconds: 0 } meters: 0 # to: locC + } + } + duration_distance_matrices { + vehicle_start_tag: "slow" + rows { # from: locA + durations { seconds: 1800 } meters: 2001 # to: locB + durations { seconds: 900 } meters: 1002 # to: locC + } + rows { # from: locB + durations { seconds: 0 } meters: 0 # to: locB + durations { seconds: 1000 } meters: 1202 # to: locC + } + rows { # from: locC + durations { seconds: 1001 } meters: 1195 # to: locB + durations { seconds: 0 } meters: 0 # to: locC + } + } + } + duration_distance_matrix_src_tags (MutableSequence[str]): + Tags defining the sources of the duration and distance + matrices; ``duration_distance_matrices(i).rows(j)`` defines + durations and distances from visits with tag + ``duration_distance_matrix_src_tags(j)`` to other visits in + matrix i. + + Tags correspond to + [VisitRequest.tags][google.maps.routeoptimization.v1.Shipment.VisitRequest.tags] + or + [Vehicle.start_tags][google.maps.routeoptimization.v1.Vehicle.start_tags]. + A given ``VisitRequest`` or ``Vehicle`` must match exactly + one tag in this field. Note that a ``Vehicle``'s source, + destination and matrix tags may be the same; similarly a + ``VisitRequest``'s source and destination tags may be the + same. All tags must be different and cannot be empty + strings. If this field is not empty, then + ``duration_distance_matrices`` must not be empty. + duration_distance_matrix_dst_tags (MutableSequence[str]): + Tags defining the destinations of the duration and distance + matrices; + ``duration_distance_matrices(i).rows(j).durations(k)`` + (resp. ``duration_distance_matrices(i).rows(j).meters(k))`` + defines the duration (resp. the distance) of the travel from + visits with tag ``duration_distance_matrix_src_tags(j)`` to + visits with tag ``duration_distance_matrix_dst_tags(k)`` in + matrix i. + + Tags correspond to + [VisitRequest.tags][google.maps.routeoptimization.v1.Shipment.VisitRequest.tags] + or + [Vehicle.start_tags][google.maps.routeoptimization.v1.Vehicle.start_tags]. + A given ``VisitRequest`` or ``Vehicle`` must match exactly + one tag in this field. Note that a ``Vehicle``'s source, + destination and matrix tags may be the same; similarly a + ``VisitRequest``'s source and destination tags may be the + same. All tags must be different and cannot be empty + strings. If this field is not empty, then + ``duration_distance_matrices`` must not be empty. + transition_attributes (MutableSequence[google.maps.routeoptimization_v1.types.TransitionAttributes]): + Transition attributes added to the model. + shipment_type_incompatibilities (MutableSequence[google.maps.routeoptimization_v1.types.ShipmentTypeIncompatibility]): + Sets of incompatible shipment_types (see + ``ShipmentTypeIncompatibility``). + shipment_type_requirements (MutableSequence[google.maps.routeoptimization_v1.types.ShipmentTypeRequirement]): + Sets of ``shipment_type`` requirements (see + ``ShipmentTypeRequirement``). + precedence_rules (MutableSequence[google.maps.routeoptimization_v1.types.ShipmentModel.PrecedenceRule]): + Set of precedence rules which must be + enforced in the model. + """ + + class DurationDistanceMatrix(proto.Message): + r"""Specifies a duration and distance matrix from visit and + vehicle start locations to visit and vehicle end locations. + + Attributes: + rows (MutableSequence[google.maps.routeoptimization_v1.types.ShipmentModel.DurationDistanceMatrix.Row]): + Specifies the rows of the duration and distance matrix. It + must have as many elements as + [ShipmentModel.duration_distance_matrix_src_tags][google.maps.routeoptimization.v1.ShipmentModel.duration_distance_matrix_src_tags]. + vehicle_start_tag (str): + Tag defining to which vehicles this duration and distance + matrix applies. If empty, this applies to all vehicles, and + there can only be a single matrix. + + Each vehicle start must match exactly one matrix, i.e. + exactly one of their ``start_tags`` field must match the + ``vehicle_start_tag`` of a matrix (and of that matrix only). + + All matrices must have a different ``vehicle_start_tag``. + """ + + class Row(proto.Message): + r"""Specifies a row of the duration and distance matrix. + + Attributes: + durations (MutableSequence[google.protobuf.duration_pb2.Duration]): + Duration values for a given row. It must have as many + elements as + [ShipmentModel.duration_distance_matrix_dst_tags][google.maps.routeoptimization.v1.ShipmentModel.duration_distance_matrix_dst_tags]. + meters (MutableSequence[float]): + Distance values for a given row. If no costs or constraints + refer to distances in the model, this can be left empty; + otherwise it must have as many elements as ``durations``. + """ + + durations: MutableSequence[duration_pb2.Duration] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + meters: MutableSequence[float] = proto.RepeatedField( + proto.DOUBLE, + number=2, + ) + + rows: MutableSequence['ShipmentModel.DurationDistanceMatrix.Row'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ShipmentModel.DurationDistanceMatrix.Row', + ) + vehicle_start_tag: str = proto.Field( + proto.STRING, + number=2, + ) + + class PrecedenceRule(proto.Message): + r"""A precedence rule between two events (each event is the pickup or + the delivery of a shipment): the "second" event has to start at + least ``offset_duration`` after "first" has started. + + Several precedences can refer to the same (or related) events, e.g., + "pickup of B happens after delivery of A" and "pickup of C happens + after pickup of B". + + Furthermore, precedences only apply when both shipments are + performed and are otherwise ignored. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + first_index (int): + Shipment index of the "first" event. This + field must be specified. + + This field is a member of `oneof`_ ``_first_index``. + first_is_delivery (bool): + Indicates if the "first" event is a delivery. + second_index (int): + Shipment index of the "second" event. This + field must be specified. + + This field is a member of `oneof`_ ``_second_index``. + second_is_delivery (bool): + Indicates if the "second" event is a + delivery. + offset_duration (google.protobuf.duration_pb2.Duration): + The offset between the "first" and "second" + event. It can be negative. + """ + + first_index: int = proto.Field( + proto.INT32, + number=1, + optional=True, + ) + first_is_delivery: bool = proto.Field( + proto.BOOL, + number=3, + ) + second_index: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + second_is_delivery: bool = proto.Field( + proto.BOOL, + number=4, + ) + offset_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + + shipments: MutableSequence['Shipment'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Shipment', + ) + vehicles: MutableSequence['Vehicle'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Vehicle', + ) + max_active_vehicles: int = proto.Field( + proto.INT32, + number=4, + optional=True, + ) + global_start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + global_end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + global_duration_cost_per_hour: float = proto.Field( + proto.DOUBLE, + number=7, + ) + duration_distance_matrices: MutableSequence[DurationDistanceMatrix] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message=DurationDistanceMatrix, + ) + duration_distance_matrix_src_tags: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=9, + ) + duration_distance_matrix_dst_tags: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=10, + ) + transition_attributes: MutableSequence['TransitionAttributes'] = proto.RepeatedField( + proto.MESSAGE, + number=11, + message='TransitionAttributes', + ) + shipment_type_incompatibilities: MutableSequence['ShipmentTypeIncompatibility'] = proto.RepeatedField( + proto.MESSAGE, + number=12, + message='ShipmentTypeIncompatibility', + ) + shipment_type_requirements: MutableSequence['ShipmentTypeRequirement'] = proto.RepeatedField( + proto.MESSAGE, + number=13, + message='ShipmentTypeRequirement', + ) + precedence_rules: MutableSequence[PrecedenceRule] = proto.RepeatedField( + proto.MESSAGE, + number=14, + message=PrecedenceRule, + ) + + +class Shipment(proto.Message): + r"""The shipment of a single item, from one of its pickups to one + of its deliveries. For the shipment to be considered as + performed, a unique vehicle must visit one of its pickup + locations (and decrease its spare capacities accordingly), then + visit one of its delivery locations later on (and therefore + re-increase its spare capacities accordingly). + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + display_name (str): + The user-defined display name of the + shipment. It can be up to 63 characters long and + may use UTF-8 characters. + pickups (MutableSequence[google.maps.routeoptimization_v1.types.Shipment.VisitRequest]): + Set of pickup alternatives associated to the + shipment. If not specified, the vehicle only + needs to visit a location corresponding to the + deliveries. + deliveries (MutableSequence[google.maps.routeoptimization_v1.types.Shipment.VisitRequest]): + Set of delivery alternatives associated to + the shipment. If not specified, the vehicle only + needs to visit a location corresponding to the + pickups. + load_demands (MutableMapping[str, google.maps.routeoptimization_v1.types.Shipment.Load]): + Load demands of the shipment (for example weight, volume, + number of pallets etc). The keys in the map should be + identifiers describing the type of the corresponding load, + ideally also including the units. For example: "weight_kg", + "volume_gallons", "pallet_count", etc. If a given key does + not appear in the map, the corresponding load is considered + as null. + penalty_cost (float): + If the shipment is not completed, this penalty is added to + the overall cost of the routes. A shipment is considered + completed if one of its pickup and delivery alternatives is + visited. The cost may be expressed in the same unit used for + all other cost-related fields in the model and must be + positive. + + *IMPORTANT*: If this penalty is not specified, it is + considered infinite, i.e. the shipment must be completed. + + This field is a member of `oneof`_ ``_penalty_cost``. + allowed_vehicle_indices (MutableSequence[int]): + The set of vehicles that may perform this shipment. If + empty, all vehicles may perform it. Vehicles are given by + their index in the ``ShipmentModel``'s ``vehicles`` list. + costs_per_vehicle (MutableSequence[float]): + Specifies the cost that is incurred when this shipment is + delivered by each vehicle. If specified, it must have + EITHER: + + - the same number of elements as + ``costs_per_vehicle_indices``. ``costs_per_vehicle[i]`` + corresponds to vehicle ``costs_per_vehicle_indices[i]`` + of the model. + - the same number of elements as there are vehicles in the + model. The i-th element corresponds to vehicle #i of the + model. + + These costs must be in the same unit as ``penalty_cost`` and + must not be negative. Leave this field empty, if there are + no such costs. + costs_per_vehicle_indices (MutableSequence[int]): + Indices of the vehicles to which ``costs_per_vehicle`` + applies. If non-empty, it must have the same number of + elements as ``costs_per_vehicle``. A vehicle index may not + be specified more than once. If a vehicle is excluded from + ``costs_per_vehicle_indices``, its cost is zero. + pickup_to_delivery_relative_detour_limit (float): + Specifies the maximum relative detour time compared to the + shortest path from pickup to delivery. If specified, it must + be nonnegative, and the shipment must contain at least a + pickup and a delivery. + + For example, let t be the shortest time taken to go from the + selected pickup alternative directly to the selected + delivery alternative. Then setting + ``pickup_to_delivery_relative_detour_limit`` enforces: + + :: + + start_time(delivery) - start_time(pickup) <= + std::ceil(t * (1.0 + pickup_to_delivery_relative_detour_limit)) + + If both relative and absolute limits are specified on the + same shipment, the more constraining limit is used for each + possible pickup/delivery pair. As of 2017/10, detours are + only supported when travel durations do not depend on + vehicles. + + This field is a member of `oneof`_ ``_pickup_to_delivery_relative_detour_limit``. + pickup_to_delivery_absolute_detour_limit (google.protobuf.duration_pb2.Duration): + Specifies the maximum absolute detour time compared to the + shortest path from pickup to delivery. If specified, it must + be nonnegative, and the shipment must contain at least a + pickup and a delivery. + + For example, let t be the shortest time taken to go from the + selected pickup alternative directly to the selected + delivery alternative. Then setting + ``pickup_to_delivery_absolute_detour_limit`` enforces: + + :: + + start_time(delivery) - start_time(pickup) <= + t + pickup_to_delivery_absolute_detour_limit + + If both relative and absolute limits are specified on the + same shipment, the more constraining limit is used for each + possible pickup/delivery pair. As of 2017/10, detours are + only supported when travel durations do not depend on + vehicles. + pickup_to_delivery_time_limit (google.protobuf.duration_pb2.Duration): + Specifies the maximum duration from start of + pickup to start of delivery of a shipment. If + specified, it must be nonnegative, and the + shipment must contain at least a pickup and a + delivery. This does not depend on which + alternatives are selected for pickup and + delivery, nor on vehicle speed. This can be + specified alongside maximum detour constraints: + the solution will respect both specifications. + shipment_type (str): + Non-empty string specifying a "type" for this shipment. This + feature can be used to define incompatibilities or + requirements between ``shipment_types`` (see + ``shipment_type_incompatibilities`` and + ``shipment_type_requirements`` in ``ShipmentModel``). + + Differs from ``visit_types`` which is specified for a single + visit: All pickup/deliveries belonging to the same shipment + share the same ``shipment_type``. + label (str): + Specifies a label for this shipment. This label is reported + in the response in the ``shipment_label`` of the + corresponding + [ShipmentRoute.Visit][google.maps.routeoptimization.v1.ShipmentRoute.Visit]. + ignore (bool): + If true, skip this shipment, but don't apply a + ``penalty_cost``. + + Ignoring a shipment results in a validation error when there + are any ``shipment_type_requirements`` in the model. + + Ignoring a shipment that is performed in + ``injected_first_solution_routes`` or + ``injected_solution_constraint`` is permitted; the solver + removes the related pickup/delivery visits from the + performing route. ``precedence_rules`` that reference + ignored shipments will also be ignored. + """ + + class VisitRequest(proto.Message): + r"""Request for a visit which can be done by a vehicle: it has a + geo-location (or two, see below), opening and closing times + represented by time windows, and a service duration time (time + spent by the vehicle once it has arrived to pickup or drop off + goods). + + Attributes: + arrival_location (google.type.latlng_pb2.LatLng): + The geo-location where the vehicle arrives when performing + this ``VisitRequest``. If the shipment model has duration + distance matrices, ``arrival_location`` must not be + specified. + arrival_waypoint (google.maps.routeoptimization_v1.types.Waypoint): + The waypoint where the vehicle arrives when performing this + ``VisitRequest``. If the shipment model has duration + distance matrices, ``arrival_waypoint`` must not be + specified. + departure_location (google.type.latlng_pb2.LatLng): + The geo-location where the vehicle departs after completing + this ``VisitRequest``. Can be omitted if it is the same as + ``arrival_location``. If the shipment model has duration + distance matrices, ``departure_location`` must not be + specified. + departure_waypoint (google.maps.routeoptimization_v1.types.Waypoint): + The waypoint where the vehicle departs after completing this + ``VisitRequest``. Can be omitted if it is the same as + ``arrival_waypoint``. If the shipment model has duration + distance matrices, ``departure_waypoint`` must not be + specified. + tags (MutableSequence[str]): + Specifies tags attached to the visit request. + Empty or duplicate strings are not allowed. + time_windows (MutableSequence[google.maps.routeoptimization_v1.types.TimeWindow]): + Time windows which constrain the arrival time at a visit. + Note that a vehicle may depart outside of the arrival time + window, i.e. arrival time + duration do not need to be + inside a time window. This can result in waiting time if the + vehicle arrives before + [TimeWindow.start_time][google.maps.routeoptimization.v1.TimeWindow.start_time]. + + The absence of ``TimeWindow`` means that the vehicle can + perform this visit at any time. + + Time windows must be disjoint, i.e. no time window must + overlap with or be adjacent to another, and they must be in + increasing order. + + ``cost_per_hour_after_soft_end_time`` and ``soft_end_time`` + can only be set if there is a single time window. + duration (google.protobuf.duration_pb2.Duration): + Duration of the visit, i.e. time spent by the vehicle + between arrival and departure (to be added to the possible + waiting time; see ``time_windows``). + cost (float): + Cost to service this visit request on a vehicle route. This + can be used to pay different costs for each alternative + pickup or delivery of a shipment. This cost must be in the + same unit as ``Shipment.penalty_cost`` and must not be + negative. + load_demands (MutableMapping[str, google.maps.routeoptimization_v1.types.Shipment.Load]): + Load demands of this visit request. This is just like + [Shipment.load_demands][google.maps.routeoptimization.v1.Shipment.load_demands] + field, except that it only applies to this + [VisitRequest][google.maps.routeoptimization.v1.Shipment.VisitRequest] + instead of the whole + [Shipment][google.maps.routeoptimization.v1.Shipment]. The + demands listed here are added to the demands listed in + [Shipment.load_demands][google.maps.routeoptimization.v1.Shipment.load_demands]. + visit_types (MutableSequence[str]): + Specifies the types of the visit. This may be used to + allocate additional time required for a vehicle to complete + this visit (see + [Vehicle.extra_visit_duration_for_visit_type][google.maps.routeoptimization.v1.Vehicle.extra_visit_duration_for_visit_type]). + + A type can only appear once. + label (str): + Specifies a label for this ``VisitRequest``. This label is + reported in the response as ``visit_label`` in the + corresponding + [ShipmentRoute.Visit][google.maps.routeoptimization.v1.ShipmentRoute.Visit]. + """ + + arrival_location: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=1, + message=latlng_pb2.LatLng, + ) + arrival_waypoint: 'Waypoint' = proto.Field( + proto.MESSAGE, + number=2, + message='Waypoint', + ) + departure_location: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=3, + message=latlng_pb2.LatLng, + ) + departure_waypoint: 'Waypoint' = proto.Field( + proto.MESSAGE, + number=4, + message='Waypoint', + ) + tags: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + time_windows: MutableSequence['TimeWindow'] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='TimeWindow', + ) + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=7, + message=duration_pb2.Duration, + ) + cost: float = proto.Field( + proto.DOUBLE, + number=8, + ) + load_demands: MutableMapping[str, 'Shipment.Load'] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=12, + message='Shipment.Load', + ) + visit_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=10, + ) + label: str = proto.Field( + proto.STRING, + number=11, + ) + + class Load(proto.Message): + r"""When performing a visit, a predefined amount may be added to the + vehicle load if it's a pickup, or subtracted if it's a delivery. + This message defines such amount. See + [load_demands][google.maps.routeoptimization.v1.Shipment.load_demands]. + + Attributes: + amount (int): + The amount by which the load of the vehicle + performing the corresponding visit will vary. + Since it is an integer, users are advised to + choose an appropriate unit to avoid loss of + precision. Must be ≥ 0. + """ + + amount: int = proto.Field( + proto.INT64, + number=2, + ) + + display_name: str = proto.Field( + proto.STRING, + number=16, + ) + pickups: MutableSequence[VisitRequest] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=VisitRequest, + ) + deliveries: MutableSequence[VisitRequest] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=VisitRequest, + ) + load_demands: MutableMapping[str, Load] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=14, + message=Load, + ) + penalty_cost: float = proto.Field( + proto.DOUBLE, + number=4, + optional=True, + ) + allowed_vehicle_indices: MutableSequence[int] = proto.RepeatedField( + proto.INT32, + number=5, + ) + costs_per_vehicle: MutableSequence[float] = proto.RepeatedField( + proto.DOUBLE, + number=6, + ) + costs_per_vehicle_indices: MutableSequence[int] = proto.RepeatedField( + proto.INT32, + number=7, + ) + pickup_to_delivery_relative_detour_limit: float = proto.Field( + proto.DOUBLE, + number=8, + optional=True, + ) + pickup_to_delivery_absolute_detour_limit: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=9, + message=duration_pb2.Duration, + ) + pickup_to_delivery_time_limit: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=10, + message=duration_pb2.Duration, + ) + shipment_type: str = proto.Field( + proto.STRING, + number=11, + ) + label: str = proto.Field( + proto.STRING, + number=12, + ) + ignore: bool = proto.Field( + proto.BOOL, + number=13, + ) + + +class ShipmentTypeIncompatibility(proto.Message): + r"""Specifies incompatibilties between shipments depending on their + shipment_type. The appearance of incompatible shipments on the same + route is restricted based on the incompatibility mode. + + Attributes: + types (MutableSequence[str]): + List of incompatible types. Two shipments having different + ``shipment_types`` among those listed are "incompatible". + incompatibility_mode (google.maps.routeoptimization_v1.types.ShipmentTypeIncompatibility.IncompatibilityMode): + Mode applied to the incompatibility. + """ + class IncompatibilityMode(proto.Enum): + r"""Modes defining how the appearance of incompatible shipments + are restricted on the same route. + + Values: + INCOMPATIBILITY_MODE_UNSPECIFIED (0): + Unspecified incompatibility mode. This value + should never be used. + NOT_PERFORMED_BY_SAME_VEHICLE (1): + In this mode, two shipments with incompatible + types can never share the same vehicle. + NOT_IN_SAME_VEHICLE_SIMULTANEOUSLY (2): + For two shipments with incompatible types with the + ``NOT_IN_SAME_VEHICLE_SIMULTANEOUSLY`` incompatibility mode: + + - If both are pickups only (no deliveries) or deliveries + only (no pickups), they cannot share the same vehicle at + all. + - If one of the shipments has a delivery and the other a + pickup, the two shipments can share the same vehicle iff + the former shipment is delivered before the latter is + picked up. + """ + INCOMPATIBILITY_MODE_UNSPECIFIED = 0 + NOT_PERFORMED_BY_SAME_VEHICLE = 1 + NOT_IN_SAME_VEHICLE_SIMULTANEOUSLY = 2 + + types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + incompatibility_mode: IncompatibilityMode = proto.Field( + proto.ENUM, + number=2, + enum=IncompatibilityMode, + ) + + +class ShipmentTypeRequirement(proto.Message): + r"""Specifies requirements between shipments based on their + shipment_type. The specifics of the requirement are defined by the + requirement mode. + + Attributes: + required_shipment_type_alternatives (MutableSequence[str]): + List of alternative shipment types required by the + ``dependent_shipment_types``. + dependent_shipment_types (MutableSequence[str]): + All shipments with a type in the + ``dependent_shipment_types`` field require at least one + shipment of type ``required_shipment_type_alternatives`` to + be visited on the same route. + + NOTE: Chains of requirements such that a ``shipment_type`` + depends on itself are not allowed. + requirement_mode (google.maps.routeoptimization_v1.types.ShipmentTypeRequirement.RequirementMode): + Mode applied to the requirement. + """ + class RequirementMode(proto.Enum): + r"""Modes defining the appearance of dependent shipments on a + route. + + Values: + REQUIREMENT_MODE_UNSPECIFIED (0): + Unspecified requirement mode. This value + should never be used. + PERFORMED_BY_SAME_VEHICLE (1): + In this mode, all "dependent" shipments must + share the same vehicle as at least one of their + "required" shipments. + IN_SAME_VEHICLE_AT_PICKUP_TIME (2): + With the ``IN_SAME_VEHICLE_AT_PICKUP_TIME`` mode, all + "dependent" shipments need to have at least one "required" + shipment on their vehicle at the time of their pickup. + + A "dependent" shipment pickup must therefore have either: + + - A delivery-only "required" shipment delivered on the + route after, or + - A "required" shipment picked up on the route before it, + and if the "required" shipment has a delivery, this + delivery must be performed after the "dependent" + shipment's pickup. + IN_SAME_VEHICLE_AT_DELIVERY_TIME (3): + Same as before, except the "dependent" shipments need to + have a "required" shipment on their vehicle at the time of + their *delivery*. + """ + REQUIREMENT_MODE_UNSPECIFIED = 0 + PERFORMED_BY_SAME_VEHICLE = 1 + IN_SAME_VEHICLE_AT_PICKUP_TIME = 2 + IN_SAME_VEHICLE_AT_DELIVERY_TIME = 3 + + required_shipment_type_alternatives: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + dependent_shipment_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + requirement_mode: RequirementMode = proto.Field( + proto.ENUM, + number=3, + enum=RequirementMode, + ) + + +class RouteModifiers(proto.Message): + r"""Encapsulates a set of optional conditions to satisfy when + calculating vehicle routes. This is similar to ``RouteModifiers`` in + the Google Maps Platform Routes Preferred API; see: + https://developers.google.com/maps/documentation/routes/reference/rest/v2/RouteModifiers. + + Attributes: + avoid_tolls (bool): + Specifies whether to avoid toll roads where + reasonable. Preference will be given to routes + not containing toll roads. Applies only to + motorized travel modes. + avoid_highways (bool): + Specifies whether to avoid highways where + reasonable. Preference will be given to routes + not containing highways. Applies only to + motorized travel modes. + avoid_ferries (bool): + Specifies whether to avoid ferries where + reasonable. Preference will be given to routes + not containing travel by ferries. Applies only + to motorized travel modes. + avoid_indoor (bool): + Optional. Specifies whether to avoid navigating indoors + where reasonable. Preference will be given to routes not + containing indoor navigation. Applies only to the + ``WALKING`` travel mode. + """ + + avoid_tolls: bool = proto.Field( + proto.BOOL, + number=2, + ) + avoid_highways: bool = proto.Field( + proto.BOOL, + number=3, + ) + avoid_ferries: bool = proto.Field( + proto.BOOL, + number=4, + ) + avoid_indoor: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class Vehicle(proto.Message): + r"""Models a vehicle in a shipment problem. Solving a shipment problem + will build a route starting from ``start_location`` and ending at + ``end_location`` for this vehicle. A route is a sequence of visits + (see ``ShipmentRoute``). + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + display_name (str): + The user-defined display name of the vehicle. + It can be up to 63 characters long and may use + UTF-8 characters. + travel_mode (google.maps.routeoptimization_v1.types.Vehicle.TravelMode): + The travel mode which affects the roads usable by the + vehicle and its speed. See also + ``travel_duration_multiple``. + route_modifiers (google.maps.routeoptimization_v1.types.RouteModifiers): + A set of conditions to satisfy that affect + the way routes are calculated for the given + vehicle. + start_location (google.type.latlng_pb2.LatLng): + Geographic location where the vehicle starts before picking + up any shipments. If not specified, the vehicle starts at + its first pickup. If the shipment model has duration and + distance matrices, ``start_location`` must not be specified. + start_waypoint (google.maps.routeoptimization_v1.types.Waypoint): + Waypoint representing a geographic location where the + vehicle starts before picking up any shipments. If neither + ``start_waypoint`` nor ``start_location`` is specified, the + vehicle starts at its first pickup. If the shipment model + has duration and distance matrices, ``start_waypoint`` must + not be specified. + end_location (google.type.latlng_pb2.LatLng): + Geographic location where the vehicle ends after it has + completed its last ``VisitRequest``. If not specified the + vehicle's ``ShipmentRoute`` ends immediately when it + completes its last ``VisitRequest``. If the shipment model + has duration and distance matrices, ``end_location`` must + not be specified. + end_waypoint (google.maps.routeoptimization_v1.types.Waypoint): + Waypoint representing a geographic location where the + vehicle ends after it has completed its last + ``VisitRequest``. If neither ``end_waypoint`` nor + ``end_location`` is specified, the vehicle's + ``ShipmentRoute`` ends immediately when it completes its + last ``VisitRequest``. If the shipment model has duration + and distance matrices, ``end_waypoint`` must not be + specified. + start_tags (MutableSequence[str]): + Specifies tags attached to the start of the + vehicle's route. + Empty or duplicate strings are not allowed. + end_tags (MutableSequence[str]): + Specifies tags attached to the end of the + vehicle's route. + Empty or duplicate strings are not allowed. + start_time_windows (MutableSequence[google.maps.routeoptimization_v1.types.TimeWindow]): + Time windows during which the vehicle may depart its start + location. They must be within the global time limits (see + [ShipmentModel.global_*][google.maps.routeoptimization.v1.ShipmentModel.global_start_time] + fields). If unspecified, there is no limitation besides + those global time limits. + + Time windows belonging to the same repeated field must be + disjoint, i.e. no time window can overlap with or be + adjacent to another, and they must be in chronological + order. + + ``cost_per_hour_after_soft_end_time`` and ``soft_end_time`` + can only be set if there is a single time window. + end_time_windows (MutableSequence[google.maps.routeoptimization_v1.types.TimeWindow]): + Time windows during which the vehicle may arrive at its end + location. They must be within the global time limits (see + [ShipmentModel.global_*][google.maps.routeoptimization.v1.ShipmentModel.global_start_time] + fields). If unspecified, there is no limitation besides + those global time limits. + + Time windows belonging to the same repeated field must be + disjoint, i.e. no time window can overlap with or be + adjacent to another, and they must be in chronological + order. + + ``cost_per_hour_after_soft_end_time`` and ``soft_end_time`` + can only be set if there is a single time window. + travel_duration_multiple (float): + Specifies a multiplicative factor that can be used to + increase or decrease travel times of this vehicle. For + example, setting this to 2.0 means that this vehicle is + slower and has travel times that are twice what they are for + standard vehicles. This multiple does not affect visit + durations. It does affect cost if ``cost_per_hour`` or + ``cost_per_traveled_hour`` are specified. This must be in + the range [0.001, 1000.0]. If unset, the vehicle is + standard, and this multiple is considered 1.0. + + WARNING: Travel times will be rounded to the nearest second + after this multiple is applied but before performing any + numerical operations, thus, a small multiple may result in a + loss of precision. + + See also ``extra_visit_duration_for_visit_type`` below. + + This field is a member of `oneof`_ ``_travel_duration_multiple``. + unloading_policy (google.maps.routeoptimization_v1.types.Vehicle.UnloadingPolicy): + Unloading policy enforced on the vehicle. + load_limits (MutableMapping[str, google.maps.routeoptimization_v1.types.Vehicle.LoadLimit]): + Capacities of the vehicle (weight, volume, # of pallets for + example). The keys in the map are the identifiers of the + type of load, consistent with the keys of the + [Shipment.load_demands][google.maps.routeoptimization.v1.Shipment.load_demands] + field. If a given key is absent from this map, the + corresponding capacity is considered to be limitless. + cost_per_hour (float): + Vehicle costs: all costs add up and must be in the same unit + as + [Shipment.penalty_cost][google.maps.routeoptimization.v1.Shipment.penalty_cost]. + + Cost per hour of the vehicle route. This cost is applied to + the total time taken by the route, and includes travel time, + waiting time, and visit time. Using ``cost_per_hour`` + instead of just ``cost_per_traveled_hour`` may result in + additional latency. + cost_per_traveled_hour (float): + Cost per traveled hour of the vehicle route. This cost is + applied only to travel time taken by the route (i.e., that + reported in + [ShipmentRoute.transitions][google.maps.routeoptimization.v1.ShipmentRoute.transitions]), + and excludes waiting time and visit time. + cost_per_kilometer (float): + Cost per kilometer of the vehicle route. This cost is + applied to the distance reported in the + [ShipmentRoute.transitions][google.maps.routeoptimization.v1.ShipmentRoute.transitions] + and does not apply to any distance implicitly traveled from + the ``arrival_location`` to the ``departure_location`` of a + single ``VisitRequest``. + fixed_cost (float): + Fixed cost applied if this vehicle is used to + handle a shipment. + used_if_route_is_empty (bool): + This field only applies to vehicles when their route does + not serve any shipments. It indicates if the vehicle should + be considered as used or not in this case. + + If true, the vehicle goes from its start to its end location + even if it doesn't serve any shipments, and time and + distance costs resulting from its start --> end travel are + taken into account. + + Otherwise, it doesn't travel from its start to its end + location, and no ``break_rule`` or delay (from + ``TransitionAttributes``) are scheduled for this vehicle. In + this case, the vehicle's ``ShipmentRoute`` doesn't contain + any information except for the vehicle index and label. + route_duration_limit (google.maps.routeoptimization_v1.types.Vehicle.DurationLimit): + Limit applied to the total duration of the vehicle's route. + In a given ``OptimizeToursResponse``, the route duration of + a vehicle is the difference between its ``vehicle_end_time`` + and ``vehicle_start_time``. + travel_duration_limit (google.maps.routeoptimization_v1.types.Vehicle.DurationLimit): + Limit applied to the travel duration of the vehicle's route. + In a given ``OptimizeToursResponse``, the route travel + duration is the sum of all its + [transitions.travel_duration][google.maps.routeoptimization.v1.ShipmentRoute.Transition.travel_duration]. + route_distance_limit (google.maps.routeoptimization_v1.types.DistanceLimit): + Limit applied to the total distance of the vehicle's route. + In a given ``OptimizeToursResponse``, the route distance is + the sum of all its + [transitions.travel_distance_meters][google.maps.routeoptimization.v1.ShipmentRoute.Transition.travel_distance_meters]. + extra_visit_duration_for_visit_type (MutableMapping[str, google.protobuf.duration_pb2.Duration]): + Specifies a map from visit_types strings to durations. The + duration is time in addition to + [VisitRequest.duration][google.maps.routeoptimization.v1.Shipment.VisitRequest.duration] + to be taken at visits with the specified ``visit_types``. + This extra visit duration adds cost if ``cost_per_hour`` is + specified. Keys (i.e. ``visit_types``) cannot be empty + strings. + + If a visit request has multiple types, a duration will be + added for each type in the map. + break_rule (google.maps.routeoptimization_v1.types.BreakRule): + Describes the break schedule to be enforced + on this vehicle. If empty, no breaks will be + scheduled for this vehicle. + label (str): + Specifies a label for this vehicle. This label is reported + in the response as the ``vehicle_label`` of the + corresponding + [ShipmentRoute][google.maps.routeoptimization.v1.ShipmentRoute]. + ignore (bool): + If true, ``used_if_route_is_empty`` must be false, and this + vehicle will remain unused. + + If a shipment is performed by an ignored vehicle in + ``injected_first_solution_routes``, it is skipped in the + first solution but is free to be performed in the response. + + If a shipment is performed by an ignored vehicle in + ``injected_solution_constraint`` and any related + pickup/delivery is constrained to remain on the vehicle + (i.e., not relaxed to level ``RELAX_ALL_AFTER_THRESHOLD``), + it is skipped in the response. If a shipment has a non-empty + ``allowed_vehicle_indices`` field and all of the allowed + vehicles are ignored, it is skipped in the response. + """ + class TravelMode(proto.Enum): + r"""Travel modes which can be used by vehicles. + + These should be a subset of the Google Maps Platform Routes + Preferred API travel modes, see: + https://developers.google.com/maps/documentation/routes_preferred/reference/rest/Shared.Types/RouteTravelMode. + + Values: + TRAVEL_MODE_UNSPECIFIED (0): + Unspecified travel mode, equivalent to ``DRIVING``. + DRIVING (1): + Travel mode corresponding to driving + directions (car, ...). + WALKING (2): + Travel mode corresponding to walking + directions. + """ + TRAVEL_MODE_UNSPECIFIED = 0 + DRIVING = 1 + WALKING = 2 + + class UnloadingPolicy(proto.Enum): + r"""Policy on how a vehicle can be unloaded. Applies only to shipments + having both a pickup and a delivery. + + Other shipments are free to occur anywhere on the route independent + of ``unloading_policy``. + + Values: + UNLOADING_POLICY_UNSPECIFIED (0): + Unspecified unloading policy; deliveries must + just occur after their corresponding pickups. + LAST_IN_FIRST_OUT (1): + Deliveries must occur in reverse order of + pickups + FIRST_IN_FIRST_OUT (2): + Deliveries must occur in the same order as + pickups + """ + UNLOADING_POLICY_UNSPECIFIED = 0 + LAST_IN_FIRST_OUT = 1 + FIRST_IN_FIRST_OUT = 2 + + class LoadLimit(proto.Message): + r"""Defines a load limit applying to a vehicle, e.g. "this truck may + only carry up to 3500 kg". See + [load_limits][google.maps.routeoptimization.v1.Vehicle.load_limits]. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + max_load (int): + The maximum acceptable amount of load. + + This field is a member of `oneof`_ ``_max_load``. + soft_max_load (int): + A soft limit of the load. See + [cost_per_unit_above_soft_max][google.maps.routeoptimization.v1.Vehicle.LoadLimit.cost_per_unit_above_soft_max]. + cost_per_unit_above_soft_max (float): + If the load ever exceeds + [soft_max_load][google.maps.routeoptimization.v1.Vehicle.LoadLimit.soft_max_load] + along this vehicle's route, the following cost penalty + applies (only once per vehicle): (load - + [soft_max_load][google.maps.routeoptimization.v1.Vehicle.LoadLimit.soft_max_load]) + + - [cost_per_unit_above_soft_max][google.maps.routeoptimization.v1.Vehicle.LoadLimit.cost_per_unit_above_soft_max]. + All costs add up and must be in the same unit as + [Shipment.penalty_cost][google.maps.routeoptimization.v1.Shipment.penalty_cost]. + start_load_interval (google.maps.routeoptimization_v1.types.Vehicle.LoadLimit.Interval): + The acceptable load interval of the vehicle + at the start of the route. + end_load_interval (google.maps.routeoptimization_v1.types.Vehicle.LoadLimit.Interval): + The acceptable load interval of the vehicle + at the end of the route. + """ + + class Interval(proto.Message): + r"""Interval of acceptable load amounts. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + min_ (int): + A minimum acceptable load. Must be ≥ 0. If they're both + specified, + [min][google.maps.routeoptimization.v1.Vehicle.LoadLimit.Interval.min] + must be ≤ + [max][google.maps.routeoptimization.v1.Vehicle.LoadLimit.Interval.max]. + max_ (int): + A maximum acceptable load. Must be ≥ 0. If unspecified, the + maximum load is unrestricted by this message. If they're + both specified, + [min][google.maps.routeoptimization.v1.Vehicle.LoadLimit.Interval.min] + must be ≤ + [max][google.maps.routeoptimization.v1.Vehicle.LoadLimit.Interval.max]. + + This field is a member of `oneof`_ ``_max``. + """ + + min_: int = proto.Field( + proto.INT64, + number=1, + ) + max_: int = proto.Field( + proto.INT64, + number=2, + optional=True, + ) + + max_load: int = proto.Field( + proto.INT64, + number=1, + optional=True, + ) + soft_max_load: int = proto.Field( + proto.INT64, + number=2, + ) + cost_per_unit_above_soft_max: float = proto.Field( + proto.DOUBLE, + number=3, + ) + start_load_interval: 'Vehicle.LoadLimit.Interval' = proto.Field( + proto.MESSAGE, + number=4, + message='Vehicle.LoadLimit.Interval', + ) + end_load_interval: 'Vehicle.LoadLimit.Interval' = proto.Field( + proto.MESSAGE, + number=5, + message='Vehicle.LoadLimit.Interval', + ) + + class DurationLimit(proto.Message): + r"""A limit defining a maximum duration of the route of a + vehicle. It can be either hard or soft. + + When a soft limit field is defined, both the soft max threshold + and its associated cost must be defined together. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + max_duration (google.protobuf.duration_pb2.Duration): + A hard limit constraining the duration to be at most + max_duration. + soft_max_duration (google.protobuf.duration_pb2.Duration): + A soft limit not enforcing a maximum duration limit, but + when violated makes the route incur a cost. This cost adds + up to other costs defined in the model, with the same unit. + + If defined, ``soft_max_duration`` must be nonnegative. If + max_duration is also defined, ``soft_max_duration`` must be + less than max_duration. + cost_per_hour_after_soft_max (float): + Cost per hour incurred if the ``soft_max_duration`` + threshold is violated. The additional cost is 0 if the + duration is under the threshold, otherwise the cost depends + on the duration as follows: + + :: + + cost_per_hour_after_soft_max * (duration - soft_max_duration) + + The cost must be nonnegative. + + This field is a member of `oneof`_ ``_cost_per_hour_after_soft_max``. + quadratic_soft_max_duration (google.protobuf.duration_pb2.Duration): + A soft limit not enforcing a maximum duration limit, but + when violated makes the route incur a cost, quadratic in the + duration. This cost adds up to other costs defined in the + model, with the same unit. + + If defined, ``quadratic_soft_max_duration`` must be + nonnegative. If ``max_duration`` is also defined, + ``quadratic_soft_max_duration`` must be less than + ``max_duration``, and the difference must be no larger than + one day: + + :: + + `max_duration - quadratic_soft_max_duration <= 86400 seconds` + cost_per_square_hour_after_quadratic_soft_max (float): + Cost per square hour incurred if the + ``quadratic_soft_max_duration`` threshold is violated. + + The additional cost is 0 if the duration is under the + threshold, otherwise the cost depends on the duration as + follows: + + :: + + cost_per_square_hour_after_quadratic_soft_max * + (duration - quadratic_soft_max_duration)^2 + + The cost must be nonnegative. + + This field is a member of `oneof`_ ``_cost_per_square_hour_after_quadratic_soft_max``. + """ + + max_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + soft_max_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + cost_per_hour_after_soft_max: float = proto.Field( + proto.DOUBLE, + number=3, + optional=True, + ) + quadratic_soft_max_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + cost_per_square_hour_after_quadratic_soft_max: float = proto.Field( + proto.DOUBLE, + number=5, + optional=True, + ) + + display_name: str = proto.Field( + proto.STRING, + number=32, + ) + travel_mode: TravelMode = proto.Field( + proto.ENUM, + number=1, + enum=TravelMode, + ) + route_modifiers: 'RouteModifiers' = proto.Field( + proto.MESSAGE, + number=2, + message='RouteModifiers', + ) + start_location: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=3, + message=latlng_pb2.LatLng, + ) + start_waypoint: 'Waypoint' = proto.Field( + proto.MESSAGE, + number=4, + message='Waypoint', + ) + end_location: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=5, + message=latlng_pb2.LatLng, + ) + end_waypoint: 'Waypoint' = proto.Field( + proto.MESSAGE, + number=6, + message='Waypoint', + ) + start_tags: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + end_tags: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=8, + ) + start_time_windows: MutableSequence['TimeWindow'] = proto.RepeatedField( + proto.MESSAGE, + number=9, + message='TimeWindow', + ) + end_time_windows: MutableSequence['TimeWindow'] = proto.RepeatedField( + proto.MESSAGE, + number=10, + message='TimeWindow', + ) + travel_duration_multiple: float = proto.Field( + proto.DOUBLE, + number=11, + optional=True, + ) + unloading_policy: UnloadingPolicy = proto.Field( + proto.ENUM, + number=12, + enum=UnloadingPolicy, + ) + load_limits: MutableMapping[str, LoadLimit] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=30, + message=LoadLimit, + ) + cost_per_hour: float = proto.Field( + proto.DOUBLE, + number=16, + ) + cost_per_traveled_hour: float = proto.Field( + proto.DOUBLE, + number=17, + ) + cost_per_kilometer: float = proto.Field( + proto.DOUBLE, + number=18, + ) + fixed_cost: float = proto.Field( + proto.DOUBLE, + number=19, + ) + used_if_route_is_empty: bool = proto.Field( + proto.BOOL, + number=20, + ) + route_duration_limit: DurationLimit = proto.Field( + proto.MESSAGE, + number=21, + message=DurationLimit, + ) + travel_duration_limit: DurationLimit = proto.Field( + proto.MESSAGE, + number=22, + message=DurationLimit, + ) + route_distance_limit: 'DistanceLimit' = proto.Field( + proto.MESSAGE, + number=23, + message='DistanceLimit', + ) + extra_visit_duration_for_visit_type: MutableMapping[str, duration_pb2.Duration] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=24, + message=duration_pb2.Duration, + ) + break_rule: 'BreakRule' = proto.Field( + proto.MESSAGE, + number=25, + message='BreakRule', + ) + label: str = proto.Field( + proto.STRING, + number=27, + ) + ignore: bool = proto.Field( + proto.BOOL, + number=28, + ) + + +class TimeWindow(proto.Message): + r"""Time windows constrain the time of an event, such as the arrival + time at a visit, or the start and end time of a vehicle. + + Hard time window bounds, ``start_time`` and ``end_time``, enforce + the earliest and latest time of the event, such that + ``start_time <= event_time <= end_time``. The soft time window lower + bound, ``soft_start_time``, expresses a preference for the event to + happen at or after ``soft_start_time`` by incurring a cost + proportional to how long before soft_start_time the event occurs. + The soft time window upper bound, ``soft_end_time``, expresses a + preference for the event to happen at or before ``soft_end_time`` by + incurring a cost proportional to how long after ``soft_end_time`` + the event occurs. ``start_time``, ``end_time``, ``soft_start_time`` + and ``soft_end_time`` should be within the global time limits (see + [ShipmentModel.global_start_time][google.maps.routeoptimization.v1.ShipmentModel.global_start_time] + and + [ShipmentModel.global_end_time][google.maps.routeoptimization.v1.ShipmentModel.global_end_time]) + and should respect: + + :: + + 0 <= `start_time` <= `end_time` and + 0 <= `start_time` <= `soft_start_time` and + 0 <= `soft_end_time` <= `end_time`. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + start_time (google.protobuf.timestamp_pb2.Timestamp): + The hard time window start time. If unspecified it will be + set to ``ShipmentModel.global_start_time``. + end_time (google.protobuf.timestamp_pb2.Timestamp): + The hard time window end time. If unspecified it will be set + to ``ShipmentModel.global_end_time``. + soft_start_time (google.protobuf.timestamp_pb2.Timestamp): + The soft start time of the time window. + soft_end_time (google.protobuf.timestamp_pb2.Timestamp): + The soft end time of the time window. + cost_per_hour_before_soft_start_time (float): + A cost per hour added to other costs in the model if the + event occurs before soft_start_time, computed as: + + :: + + max(0, soft_start_time - t.seconds) + * cost_per_hour_before_soft_start_time / 3600, + t being the time of the event. + + This cost must be positive, and the field can only be set if + soft_start_time has been set. + + This field is a member of `oneof`_ ``_cost_per_hour_before_soft_start_time``. + cost_per_hour_after_soft_end_time (float): + A cost per hour added to other costs in the model if the + event occurs after ``soft_end_time``, computed as: + + :: + + max(0, t.seconds - soft_end_time.seconds) + * cost_per_hour_after_soft_end_time / 3600, + t being the time of the event. + + This cost must be positive, and the field can only be set if + ``soft_end_time`` has been set. + + This field is a member of `oneof`_ ``_cost_per_hour_after_soft_end_time``. + """ + + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + soft_start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + soft_end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + cost_per_hour_before_soft_start_time: float = proto.Field( + proto.DOUBLE, + number=5, + optional=True, + ) + cost_per_hour_after_soft_end_time: float = proto.Field( + proto.DOUBLE, + number=6, + optional=True, + ) + + +class DistanceLimit(proto.Message): + r"""A limit defining a maximum distance which can be traveled. It can be + either hard or soft. + + If a soft limit is defined, both ``soft_max_meters`` and + ``cost_per_kilometer_above_soft_max`` must be defined and be + nonnegative. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + max_meters (int): + A hard limit constraining the distance to be at most + max_meters. The limit must be nonnegative. + + This field is a member of `oneof`_ ``_max_meters``. + soft_max_meters (int): + A soft limit not enforcing a maximum distance limit, but + when violated results in a cost which adds up to other costs + defined in the model, with the same unit. + + If defined soft_max_meters must be less than max_meters and + must be nonnegative. + + This field is a member of `oneof`_ ``_soft_max_meters``. + cost_per_kilometer_below_soft_max (float): + Cost per kilometer incurred, increasing up to + ``soft_max_meters``, with formula: + + :: + + min(distance_meters, soft_max_meters) / 1000.0 * + cost_per_kilometer_below_soft_max. + + This cost is not supported in ``route_distance_limit``. + + This field is a member of `oneof`_ ``_cost_per_kilometer_below_soft_max``. + cost_per_kilometer_above_soft_max (float): + Cost per kilometer incurred if distance is above + ``soft_max_meters`` limit. The additional cost is 0 if the + distance is under the limit, otherwise the formula used to + compute the cost is the following: + + :: + + (distance_meters - soft_max_meters) / 1000.0 * + cost_per_kilometer_above_soft_max. + + The cost must be nonnegative. + + This field is a member of `oneof`_ ``_cost_per_kilometer_above_soft_max``. + """ + + max_meters: int = proto.Field( + proto.INT64, + number=1, + optional=True, + ) + soft_max_meters: int = proto.Field( + proto.INT64, + number=2, + optional=True, + ) + cost_per_kilometer_below_soft_max: float = proto.Field( + proto.DOUBLE, + number=4, + optional=True, + ) + cost_per_kilometer_above_soft_max: float = proto.Field( + proto.DOUBLE, + number=3, + optional=True, + ) + + +class TransitionAttributes(proto.Message): + r"""Specifies attributes of transitions between two consecutive visits + on a route. Several ``TransitionAttributes`` may apply to the same + transition: in that case, all extra costs add up and the strictest + constraint or limit applies (following natural "AND" semantics). + + Attributes: + src_tag (str): + Tags defining the set of (src->dst) transitions these + attributes apply to. + + A source visit or vehicle start matches iff its + [VisitRequest.tags][google.maps.routeoptimization.v1.Shipment.VisitRequest.tags] + or + [Vehicle.start_tags][google.maps.routeoptimization.v1.Vehicle.start_tags] + either contains ``src_tag`` or does not contain + ``excluded_src_tag`` (depending on which of these two fields + is non-empty). + excluded_src_tag (str): + See ``src_tag``. Exactly one of ``src_tag`` and + ``excluded_src_tag`` must be non-empty. + dst_tag (str): + A destination visit or vehicle end matches iff its + [VisitRequest.tags][google.maps.routeoptimization.v1.Shipment.VisitRequest.tags] + or + [Vehicle.end_tags][google.maps.routeoptimization.v1.Vehicle.end_tags] + either contains ``dst_tag`` or does not contain + ``excluded_dst_tag`` (depending on which of these two fields + is non-empty). + excluded_dst_tag (str): + See ``dst_tag``. Exactly one of ``dst_tag`` and + ``excluded_dst_tag`` must be non-empty. + cost (float): + Specifies a cost for performing this + transition. This is in the same unit as all + other costs in the model and must not be + negative. It is applied on top of all other + existing costs. + cost_per_kilometer (float): + Specifies a cost per kilometer applied to the distance + traveled while performing this transition. It adds up to any + [Vehicle.cost_per_kilometer][google.maps.routeoptimization.v1.Vehicle.cost_per_kilometer] + specified on vehicles. + distance_limit (google.maps.routeoptimization_v1.types.DistanceLimit): + Specifies a limit on the distance traveled + while performing this transition. + + As of 2021/06, only soft limits are supported. + delay (google.protobuf.duration_pb2.Duration): + Specifies a delay incurred when performing this transition. + + This delay always occurs *after* finishing the source visit + and *before* starting the destination visit. + """ + + src_tag: str = proto.Field( + proto.STRING, + number=1, + ) + excluded_src_tag: str = proto.Field( + proto.STRING, + number=2, + ) + dst_tag: str = proto.Field( + proto.STRING, + number=3, + ) + excluded_dst_tag: str = proto.Field( + proto.STRING, + number=4, + ) + cost: float = proto.Field( + proto.DOUBLE, + number=5, + ) + cost_per_kilometer: float = proto.Field( + proto.DOUBLE, + number=6, + ) + distance_limit: 'DistanceLimit' = proto.Field( + proto.MESSAGE, + number=7, + message='DistanceLimit', + ) + delay: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=8, + message=duration_pb2.Duration, + ) + + +class Waypoint(proto.Message): + r"""Encapsulates a waypoint. Waypoints mark arrival and departure + locations of VisitRequests, and start and end locations of + Vehicles. + + 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 (google.maps.routeoptimization_v1.types.Location): + A point specified using geographic + coordinates, including an optional heading. + + This field is a member of `oneof`_ ``location_type``. + place_id (str): + The POI Place ID associated with the + waypoint. + + This field is a member of `oneof`_ ``location_type``. + side_of_road (bool): + Optional. Indicates that the location of this + waypoint is meant to have a preference for the + vehicle to stop at a particular side of road. + When you set this value, the route will pass + through the location so that the vehicle can + stop at the side of road that the location is + biased towards from the center of the road. This + option doesn't work for the 'WALKING' travel + mode. + """ + + location: 'Location' = proto.Field( + proto.MESSAGE, + number=1, + oneof='location_type', + message='Location', + ) + place_id: str = proto.Field( + proto.STRING, + number=2, + oneof='location_type', + ) + side_of_road: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class Location(proto.Message): + r"""Encapsulates a location (a geographic point, and an optional + heading). + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + lat_lng (google.type.latlng_pb2.LatLng): + The waypoint's geographic coordinates. + heading (int): + The compass heading associated with the + direction of the flow of traffic. This value is + used to specify the side of the road to use for + pickup and drop-off. Heading values can be from + 0 to 360, where 0 specifies a heading of due + North, 90 specifies a heading of due East, etc. + + This field is a member of `oneof`_ ``_heading``. + """ + + lat_lng: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=1, + message=latlng_pb2.LatLng, + ) + heading: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + + +class BreakRule(proto.Message): + r"""Rules to generate time breaks for a vehicle (e.g. lunch breaks). A + break is a contiguous period of time during which the vehicle + remains idle at its current position and cannot perform any visit. A + break may occur: + + - during the travel between two visits (which includes the time + right before or right after a visit, but not in the middle of a + visit), in which case it extends the corresponding transit time + between the visits, + - or before the vehicle start (the vehicle may not start in the + middle of a break), in which case it does not affect the vehicle + start time. + - or after the vehicle end (ditto, with the vehicle end time). + + Attributes: + break_requests (MutableSequence[google.maps.routeoptimization_v1.types.BreakRule.BreakRequest]): + Sequence of breaks. See the ``BreakRequest`` message. + frequency_constraints (MutableSequence[google.maps.routeoptimization_v1.types.BreakRule.FrequencyConstraint]): + Several ``FrequencyConstraint`` may apply. They must all be + satisfied by the ``BreakRequest``\ s of this ``BreakRule``. + See ``FrequencyConstraint``. + """ + + class BreakRequest(proto.Message): + r"""The sequence of breaks (i.e. their number and order) that apply to + each vehicle must be known beforehand. The repeated + ``BreakRequest``\ s define that sequence, in the order in which they + must occur. Their time windows (``earliest_start_time`` / + ``latest_start_time``) may overlap, but they must be compatible with + the order (this is checked). + + Attributes: + earliest_start_time (google.protobuf.timestamp_pb2.Timestamp): + Required. Lower bound (inclusive) on the + start of the break. + latest_start_time (google.protobuf.timestamp_pb2.Timestamp): + Required. Upper bound (inclusive) on the + start of the break. + min_duration (google.protobuf.duration_pb2.Duration): + Required. Minimum duration of the break. Must + be positive. + """ + + earliest_start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + latest_start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + min_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) + + class FrequencyConstraint(proto.Message): + r"""One may further constrain the frequency and duration of the breaks + specified above, by enforcing a minimum break frequency, such as + "There must be a break of at least 1 hour every 12 hours". Assuming + that this can be interpreted as "Within any sliding time window of + 12h, there must be at least one break of at least one hour", that + example would translate to the following ``FrequencyConstraint``: + + :: + + { + min_break_duration { seconds: 3600 } # 1 hour. + max_inter_break_duration { seconds: 39600 } # 11 hours (12 - 1 = 11). + } + + The timing and duration of the breaks in the solution will respect + all such constraints, in addition to the time windows and minimum + durations already specified in the ``BreakRequest``. + + A ``FrequencyConstraint`` may in practice apply to non-consecutive + breaks. For example, the following schedule honors the "1h every + 12h" example: + + :: + + 04:00 vehicle start + .. performing travel and visits .. + 09:00 1 hour break + 10:00 end of the break + .. performing travel and visits .. + 12:00 20-min lunch break + 12:20 end of the break + .. performing travel and visits .. + 21:00 1 hour break + 22:00 end of the break + .. performing travel and visits .. + 23:59 vehicle end + + Attributes: + min_break_duration (google.protobuf.duration_pb2.Duration): + Required. Minimum break duration for this constraint. + Nonnegative. See description of ``FrequencyConstraint``. + max_inter_break_duration (google.protobuf.duration_pb2.Duration): + Required. Maximum allowed span of any interval of time in + the route that does not include at least partially a break + of ``duration >= min_break_duration``. Must be positive. + """ + + min_break_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + max_inter_break_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + break_requests: MutableSequence[BreakRequest] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=BreakRequest, + ) + frequency_constraints: MutableSequence[FrequencyConstraint] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=FrequencyConstraint, + ) + + +class ShipmentRoute(proto.Message): + r"""A vehicle's route can be decomposed, along the time axis, like this + (we assume there are n visits): + + :: + + | | | | | T[2], | | | + | Transition | Visit #0 | | | V[2], | | | + | #0 | aka | T[1] | V[1] | ... | V[n-1] | T[n] | + | aka T[0] | V[0] | | | V[n-2],| | | + | | | | | T[n-1] | | | + ^ ^ ^ ^ ^ ^ ^ ^ + vehicle V[0].start V[0].end V[1]. V[1]. V[n]. V[n]. vehicle + start (arrival) (departure) start end start end end + + Note that we make a difference between: + + - "punctual events", such as the vehicle start and end and each + visit's start and end (aka arrival and departure). They happen at + a given second. + - "time intervals", such as the visits themselves, and the + transition between visits. Though time intervals can sometimes + have zero duration, i.e. start and end at the same second, they + often have a positive duration. + + Invariants: + + - If there are n visits, there are n+1 transitions. + - A visit is always surrounded by a transition before it (same + index) and a transition after it (index + 1). + - The vehicle start is always followed by transition #0. + - The vehicle end is always preceded by transition #n. + + Zooming in, here is what happens during a ``Transition`` and a + ``Visit``: + + :: + + ---+-------------------------------------+-----------------------------+--> + | TRANSITION[i] | VISIT[i] | + | | | + | * TRAVEL: the vehicle moves from | PERFORM the visit: | + | VISIT[i-1].departure_location to | | + | VISIT[i].arrival_location, which | * Spend some time: | + | takes a given travel duration | the "visit duration". | + | and distance | | + | | * Load or unload | + | * BREAKS: the driver may have | some quantities from the | + | breaks (e.g. lunch break). | vehicle: the "demand". | + | | | + | * WAIT: the driver/vehicle does | | + | nothing. This can happen for | | + | many reasons, for example when | | + | the vehicle reaches the next | | + | event's destination before the | | + | start of its time window | | + | | | + | * DELAY: *right before* the next | | + | arrival. E.g. the vehicle and/or | | + | driver spends time unloading. | | + | | | + ---+-------------------------------------+-----------------------------+--> + ^ ^ ^ + V[i-1].end V[i].start V[i].end + + Lastly, here is how the TRAVEL, BREAKS, DELAY and WAIT can be + arranged during a transition. + + - They don't overlap. + - The DELAY is unique and *must* be a contiguous period of time + right before the next visit (or vehicle end). Thus, it suffice to + know the delay duration to know its start and end time. + - The BREAKS are contiguous, non-overlapping periods of time. The + response specifies the start time and duration of each break. + - TRAVEL and WAIT are "preemptable": they can be interrupted + several times during this transition. Clients can assume that + travel happens "as soon as possible" and that "wait" fills the + remaining time. + + A (complex) example: + + :: + + TRANSITION[i] + --++-----+-----------------------------------------------------------++--> + || | | | | | | || + || T | B | T | | B | | D || + || r | r | r | W | r | W | e || + || a | e | a | a | e | a | l || + || v | a | v | i | a | i | a || + || e | k | e | t | k | t | y || + || l | | l | | | | || + || | | | | | | || + --++-----------------------------------------------------------------++--> + + Attributes: + vehicle_index (int): + Vehicle performing the route, identified by its index in the + source ``ShipmentModel``. + vehicle_label (str): + Label of the vehicle performing this route, equal to + ``ShipmentModel.vehicles(vehicle_index).label``, if + specified. + vehicle_start_time (google.protobuf.timestamp_pb2.Timestamp): + Time at which the vehicle starts its route. + vehicle_end_time (google.protobuf.timestamp_pb2.Timestamp): + Time at which the vehicle finishes its route. + visits (MutableSequence[google.maps.routeoptimization_v1.types.ShipmentRoute.Visit]): + Ordered sequence of visits representing a route. visits[i] + is the i-th visit in the route. If this field is empty, the + vehicle is considered as unused. + transitions (MutableSequence[google.maps.routeoptimization_v1.types.ShipmentRoute.Transition]): + Ordered list of transitions for the route. + has_traffic_infeasibilities (bool): + When + [OptimizeToursRequest.consider_road_traffic][google.maps.routeoptimization.v1.OptimizeToursRequest.consider_road_traffic], + is set to true, this field indicates that inconsistencies in + route timings are predicted using traffic-based travel + duration estimates. There may be insufficient time to + complete traffic-adjusted travel, delays, and breaks between + visits, before the first visit, or after the last visit, + while still satisfying the visit and vehicle time windows. + For example, + + :: + + start_time(previous_visit) + duration(previous_visit) + + travel_duration(previous_visit, next_visit) > start_time(next_visit) + + Arrival at next_visit will likely happen later than its + current time window due the increased estimate of travel + time ``travel_duration(previous_visit, next_visit)`` due to + traffic. Also, a break may be forced to overlap with a visit + due to an increase in travel time estimates and visit or + break time window restrictions. + route_polyline (google.maps.routeoptimization_v1.types.ShipmentRoute.EncodedPolyline): + The encoded polyline representation of the route. This field + is only populated if + [OptimizeToursRequest.populate_polylines][google.maps.routeoptimization.v1.OptimizeToursRequest.populate_polylines] + is set to true. + breaks (MutableSequence[google.maps.routeoptimization_v1.types.ShipmentRoute.Break]): + Breaks scheduled for the vehicle performing this route. The + ``breaks`` sequence represents time intervals, each starting + at the corresponding ``start_time`` and lasting ``duration`` + seconds. + metrics (google.maps.routeoptimization_v1.types.AggregatedMetrics): + Duration, distance and load metrics for this route. The + fields of + [AggregatedMetrics][google.maps.routeoptimization.v1.AggregatedMetrics] + are summed over all + [ShipmentRoute.transitions][google.maps.routeoptimization.v1.ShipmentRoute.transitions] + or + [ShipmentRoute.visits][google.maps.routeoptimization.v1.ShipmentRoute.visits], + depending on the context. + route_costs (MutableMapping[str, float]): + Cost of the route, broken down by cost-related request + fields. The keys are proto paths, relative to the input + OptimizeToursRequest, e.g. "model.shipments.pickups.cost", + and the values are the total cost generated by the + corresponding cost field, aggregated over the whole route. + In other words, costs["model.shipments.pickups.cost"] is the + sum of all pickup costs over the route. All costs defined in + the model are reported in detail here with the exception of + costs related to TransitionAttributes that are only reported + in an aggregated way as of 2022/01. + route_total_cost (float): + Total cost of the route. The sum of all costs + in the cost map. + """ + + class Visit(proto.Message): + r"""A visit performed during a route. This visit corresponds to a pickup + or a delivery of a ``Shipment``. + + Attributes: + shipment_index (int): + Index of the ``shipments`` field in the source + [ShipmentModel][google.maps.routeoptimization.v1.ShipmentModel]. + is_pickup (bool): + If true the visit corresponds to a pickup of a ``Shipment``. + Otherwise, it corresponds to a delivery. + visit_request_index (int): + Index of ``VisitRequest`` in either the pickup or delivery + field of the ``Shipment`` (see ``is_pickup``). + start_time (google.protobuf.timestamp_pb2.Timestamp): + Time at which the visit starts. Note that the vehicle may + arrive earlier than this at the visit location. Times are + consistent with the ``ShipmentModel``. + load_demands (MutableMapping[str, google.maps.routeoptimization_v1.types.Shipment.Load]): + Total visit load demand as the sum of the shipment and the + visit request ``load_demands``. The values are negative if + the visit is a delivery. Demands are reported for the same + types as the + [Transition.loads][google.maps.routeoptimization.v1.ShipmentRoute.Transition] + (see this field). + detour (google.protobuf.duration_pb2.Duration): + Extra detour time due to the shipments visited on the route + before the visit and to the potential waiting time induced + by time windows. If the visit is a delivery, the detour is + computed from the corresponding pickup visit and is equal + to: + + :: + + start_time(delivery) - start_time(pickup) + - (duration(pickup) + travel duration from the pickup location + to the delivery location). + + Otherwise, it is computed from the vehicle + ``start_location`` and is equal to: + + :: + + start_time - vehicle_start_time - travel duration from + the vehicle's `start_location` to the visit. + shipment_label (str): + Copy of the corresponding ``Shipment.label``, if specified + in the ``Shipment``. + visit_label (str): + Copy of the corresponding + [VisitRequest.label][google.maps.routeoptimization.v1.Shipment.VisitRequest.label], + if specified in the ``VisitRequest``. + """ + + shipment_index: int = proto.Field( + proto.INT32, + number=1, + ) + is_pickup: bool = proto.Field( + proto.BOOL, + number=2, + ) + visit_request_index: int = proto.Field( + proto.INT32, + number=3, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + load_demands: MutableMapping[str, 'Shipment.Load'] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=11, + message='Shipment.Load', + ) + detour: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=6, + message=duration_pb2.Duration, + ) + shipment_label: str = proto.Field( + proto.STRING, + number=7, + ) + visit_label: str = proto.Field( + proto.STRING, + number=8, + ) + + class Transition(proto.Message): + r"""Transition between two events on the route. See the description of + [ShipmentRoute][google.maps.routeoptimization.v1.ShipmentRoute]. + + If the vehicle does not have a ``start_location`` and/or + ``end_location``, the corresponding travel metrics are 0. + + Attributes: + travel_duration (google.protobuf.duration_pb2.Duration): + Travel duration during this transition. + travel_distance_meters (float): + Distance traveled during the transition. + traffic_info_unavailable (bool): + When traffic is requested via + [OptimizeToursRequest.consider_road_traffic] + [google.maps.routeoptimization.v1.OptimizeToursRequest.consider_road_traffic], + and the traffic info couldn't be retrieved for a + ``Transition``, this boolean is set to true. This may be + temporary (rare hiccup in the realtime traffic servers) or + permanent (no data for this location). + delay_duration (google.protobuf.duration_pb2.Duration): + Sum of the delay durations applied to this transition. If + any, the delay starts exactly ``delay_duration`` seconds + before the next event (visit or vehicle end). See + [TransitionAttributes.delay][google.maps.routeoptimization.v1.TransitionAttributes.delay]. + break_duration (google.protobuf.duration_pb2.Duration): + Sum of the duration of the breaks occurring during this + transition, if any. Details about each break's start time + and duration are stored in + [ShipmentRoute.breaks][google.maps.routeoptimization.v1.ShipmentRoute.breaks]. + wait_duration (google.protobuf.duration_pb2.Duration): + Time spent waiting during this transition. + Wait duration corresponds to idle time and does + not include break time. Also note that this wait + time may be split into several non-contiguous + intervals. + total_duration (google.protobuf.duration_pb2.Duration): + Total duration of the transition, provided for convenience. + It is equal to: + + - next visit ``start_time`` (or ``vehicle_end_time`` if + this is the last transition) - this transition's + ``start_time``; + - if ``ShipmentRoute.has_traffic_infeasibilities`` is + false, the following additionally holds: \`total_duration + = travel_duration + delay_duration + + - break_duration + wait_duration`. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Start time of this transition. + route_polyline (google.maps.routeoptimization_v1.types.ShipmentRoute.EncodedPolyline): + The encoded polyline representation of the route followed + during the transition. This field is only populated if + [populate_transition_polylines] + [google.maps.routeoptimization.v1.OptimizeToursRequest.populate_transition_polylines] + is set to true. + route_token (str): + Output only. An opaque token that can be passed to + `Navigation + SDK `__ + to reconstruct the route during navigation, and, in the + event of rerouting, honor the original intention when the + route was created. Treat this token as an opaque blob. Don't + compare its value across requests as its value may change + even if the service returns the exact same route. This field + is only populated if [populate_transition_polylines] + [google.maps.routeoptimization.v1.OptimizeToursRequest.populate_transition_polylines] + is set to true. + vehicle_loads (MutableMapping[str, google.maps.routeoptimization_v1.types.ShipmentRoute.VehicleLoad]): + Vehicle loads during this transition, for each type that + either appears in this vehicle's + [Vehicle.load_limits][google.maps.routeoptimization.v1.Vehicle.load_limits], + or that have non-zero + [Shipment.load_demands][google.maps.routeoptimization.v1.Shipment.load_demands] + on some shipment performed on this route. + + The loads during the first transition are the starting loads + of the vehicle route. Then, after each visit, the visit's + ``load_demands`` are either added or subtracted to get the + next transition's loads, depending on whether the visit was + a pickup or a delivery. + """ + + travel_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + travel_distance_meters: float = proto.Field( + proto.DOUBLE, + number=2, + ) + traffic_info_unavailable: bool = proto.Field( + proto.BOOL, + number=3, + ) + delay_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + break_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + wait_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=6, + message=duration_pb2.Duration, + ) + total_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=7, + message=duration_pb2.Duration, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + route_polyline: 'ShipmentRoute.EncodedPolyline' = proto.Field( + proto.MESSAGE, + number=9, + message='ShipmentRoute.EncodedPolyline', + ) + route_token: str = proto.Field( + proto.STRING, + number=12, + ) + vehicle_loads: MutableMapping[str, 'ShipmentRoute.VehicleLoad'] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=11, + message='ShipmentRoute.VehicleLoad', + ) + + class VehicleLoad(proto.Message): + r"""Reports the actual load of the vehicle at some point along the + route, for a given type (see + [Transition.vehicle_loads][google.maps.routeoptimization.v1.ShipmentRoute.Transition.vehicle_loads]). + + Attributes: + amount (int): + The amount of load on the vehicle, for the given type. The + unit of load is usually indicated by the type. See + [Transition.vehicle_loads][google.maps.routeoptimization.v1.ShipmentRoute.Transition.vehicle_loads]. + """ + + amount: int = proto.Field( + proto.INT64, + number=1, + ) + + class EncodedPolyline(proto.Message): + r"""The encoded representation of a polyline. More information on + polyline encoding can be found here: + + https://developers.google.com/maps/documentation/utilities/polylinealgorithm + https://developers.google.com/maps/documentation/javascript/reference/geometry#encoding. + + Attributes: + points (str): + String representing encoded points of the + polyline. + """ + + points: str = proto.Field( + proto.STRING, + number=1, + ) + + class Break(proto.Message): + r"""Data representing the execution of a break. + + Attributes: + start_time (google.protobuf.timestamp_pb2.Timestamp): + Start time of a break. + duration (google.protobuf.duration_pb2.Duration): + Duration of a break. + """ + + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + vehicle_index: int = proto.Field( + proto.INT32, + number=1, + ) + vehicle_label: str = proto.Field( + proto.STRING, + number=2, + ) + vehicle_start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + vehicle_end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + visits: MutableSequence[Visit] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=Visit, + ) + transitions: MutableSequence[Transition] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message=Transition, + ) + has_traffic_infeasibilities: bool = proto.Field( + proto.BOOL, + number=9, + ) + route_polyline: EncodedPolyline = proto.Field( + proto.MESSAGE, + number=10, + message=EncodedPolyline, + ) + breaks: MutableSequence[Break] = proto.RepeatedField( + proto.MESSAGE, + number=11, + message=Break, + ) + metrics: 'AggregatedMetrics' = proto.Field( + proto.MESSAGE, + number=12, + message='AggregatedMetrics', + ) + route_costs: MutableMapping[str, float] = proto.MapField( + proto.STRING, + proto.DOUBLE, + number=17, + ) + route_total_cost: float = proto.Field( + proto.DOUBLE, + number=18, + ) + + +class SkippedShipment(proto.Message): + r"""Specifies details of unperformed shipments in a solution. For + trivial cases and/or if we are able to identify the cause for + skipping, we report the reason here. + + Attributes: + index (int): + The index corresponds to the index of the shipment in the + source ``ShipmentModel``. + label (str): + Copy of the corresponding + [Shipment.label][google.maps.routeoptimization.v1.Shipment.label], + if specified in the ``Shipment``. + reasons (MutableSequence[google.maps.routeoptimization_v1.types.SkippedShipment.Reason]): + A list of reasons that explain why the shipment was skipped. + See comment above ``Reason``. If we are unable to understand + why a shipment was skipped, reasons will not be set. + """ + + class Reason(proto.Message): + r"""If we can explain why the shipment was skipped, reasons will be + listed here. If the reason is not the same for all vehicles, + ``reason`` will have more than 1 element. A skipped shipment cannot + have duplicate reasons, i.e. where all fields are the same except + for ``example_vehicle_index``. Example: + + :: + + reasons { + code: DEMAND_EXCEEDS_VEHICLE_CAPACITY + example_vehicle_index: 1 + example_exceeded_capacity_type: "Apples" + } + reasons { + code: DEMAND_EXCEEDS_VEHICLE_CAPACITY + example_vehicle_index: 3 + example_exceeded_capacity_type: "Pears" + } + reasons { + code: CANNOT_BE_PERFORMED_WITHIN_VEHICLE_DISTANCE_LIMIT + example_vehicle_index: 1 + } + + The skipped shipment is incompatible with all vehicles. The reasons + may be different for all vehicles but at least one vehicle's + "Apples" capacity would be exceeded (including vehicle 1), at least + one vehicle's "Pears" capacity would be exceeded (including vehicle + 3) and at least one vehicle's distance limit would be exceeded + (including vehicle 1). + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + code (google.maps.routeoptimization_v1.types.SkippedShipment.Reason.Code): + Refer to the comments of Code. + example_vehicle_index (int): + If the reason is related to a + shipment-vehicle incompatibility, this field + provides the index of one relevant vehicle. + + This field is a member of `oneof`_ ``_example_vehicle_index``. + example_exceeded_capacity_type (str): + If the reason code is ``DEMAND_EXCEEDS_VEHICLE_CAPACITY``, + documents one capacity type that is exceeded. + """ + class Code(proto.Enum): + r"""Code identifying the reason type. The order here is + meaningless. In particular, it gives no indication of whether a + given reason will appear before another in the solution, if both + apply. + + Values: + CODE_UNSPECIFIED (0): + This should never be used. + NO_VEHICLE (1): + There is no vehicle in the model making all + shipments infeasible. + DEMAND_EXCEEDS_VEHICLE_CAPACITY (2): + The demand of the shipment exceeds a vehicle's capacity for + some capacity types, one of which is + ``example_exceeded_capacity_type``. + CANNOT_BE_PERFORMED_WITHIN_VEHICLE_DISTANCE_LIMIT (3): + The minimum distance necessary to perform this shipment, + i.e. from the vehicle's ``start_location`` to the shipment's + pickup and/or delivery locations and to the vehicle's end + location exceeds the vehicle's ``route_distance_limit``. + + Note that for this computation we use the geodesic + distances. + CANNOT_BE_PERFORMED_WITHIN_VEHICLE_DURATION_LIMIT (4): + The minimum time necessary to perform this shipment, + including travel time, wait time and service time exceeds + the vehicle's ``route_duration_limit``. + + Note: travel time is computed in the best-case scenario, + namely as geodesic distance x 36 m/s (roughly 130 km/hour). + CANNOT_BE_PERFORMED_WITHIN_VEHICLE_TRAVEL_DURATION_LIMIT (5): + Same as above but we only compare minimum travel time and + the vehicle's ``travel_duration_limit``. + CANNOT_BE_PERFORMED_WITHIN_VEHICLE_TIME_WINDOWS (6): + The vehicle cannot perform this shipment in the best-case + scenario (see + ``CANNOT_BE_PERFORMED_WITHIN_VEHICLE_DURATION_LIMIT`` for + time computation) if it starts at its earliest start time: + the total time would make the vehicle end after its latest + end time. + VEHICLE_NOT_ALLOWED (7): + The ``allowed_vehicle_indices`` field of the shipment is not + empty and this vehicle does not belong to it. + """ + CODE_UNSPECIFIED = 0 + NO_VEHICLE = 1 + DEMAND_EXCEEDS_VEHICLE_CAPACITY = 2 + CANNOT_BE_PERFORMED_WITHIN_VEHICLE_DISTANCE_LIMIT = 3 + CANNOT_BE_PERFORMED_WITHIN_VEHICLE_DURATION_LIMIT = 4 + CANNOT_BE_PERFORMED_WITHIN_VEHICLE_TRAVEL_DURATION_LIMIT = 5 + CANNOT_BE_PERFORMED_WITHIN_VEHICLE_TIME_WINDOWS = 6 + VEHICLE_NOT_ALLOWED = 7 + + code: 'SkippedShipment.Reason.Code' = proto.Field( + proto.ENUM, + number=1, + enum='SkippedShipment.Reason.Code', + ) + example_vehicle_index: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + example_exceeded_capacity_type: str = proto.Field( + proto.STRING, + number=3, + ) + + index: int = proto.Field( + proto.INT32, + number=1, + ) + label: str = proto.Field( + proto.STRING, + number=2, + ) + reasons: MutableSequence[Reason] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=Reason, + ) + + +class AggregatedMetrics(proto.Message): + r"""Aggregated metrics for + [ShipmentRoute][google.maps.routeoptimization.v1.ShipmentRoute] + (resp. for + [OptimizeToursResponse][google.maps.routeoptimization.v1.OptimizeToursResponse] + over all + [Transition][google.maps.routeoptimization.v1.ShipmentRoute.Transition] + and/or [Visit][google.maps.routeoptimization.v1.ShipmentRoute.Visit] + (resp. over all + [ShipmentRoute][google.maps.routeoptimization.v1.ShipmentRoute]) + elements. + + Attributes: + performed_shipment_count (int): + Number of shipments performed. Note that a + pickup and delivery pair only counts once. + travel_duration (google.protobuf.duration_pb2.Duration): + Total travel duration for a route or a + solution. + wait_duration (google.protobuf.duration_pb2.Duration): + Total wait duration for a route or a + solution. + delay_duration (google.protobuf.duration_pb2.Duration): + Total delay duration for a route or a + solution. + break_duration (google.protobuf.duration_pb2.Duration): + Total break duration for a route or a + solution. + visit_duration (google.protobuf.duration_pb2.Duration): + Total visit duration for a route or a + solution. + total_duration (google.protobuf.duration_pb2.Duration): + The total duration should be equal to the sum of all + durations above. For routes, it also corresponds to: + + :: + + [ShipmentRoute.vehicle_end_time][google.maps.routeoptimization.v1.ShipmentRoute.vehicle_end_time] + - + [ShipmentRoute.vehicle_start_time][google.maps.routeoptimization.v1.ShipmentRoute.vehicle_start_time] + travel_distance_meters (float): + Total travel distance for a route or a + solution. + max_loads (MutableMapping[str, google.maps.routeoptimization_v1.types.ShipmentRoute.VehicleLoad]): + Maximum load achieved over the entire route (resp. + solution), for each of the quantities on this route (resp. + solution), computed as the maximum over all + [Transition.vehicle_loads][google.maps.routeoptimization.v1.ShipmentRoute.Transition.vehicle_loads] + (resp. + [ShipmentRoute.metrics.max_loads][google.maps.routeoptimization.v1.AggregatedMetrics.max_loads]. + """ + + performed_shipment_count: int = proto.Field( + proto.INT32, + number=1, + ) + travel_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + wait_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) + delay_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + break_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + visit_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=6, + message=duration_pb2.Duration, + ) + total_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=7, + message=duration_pb2.Duration, + ) + travel_distance_meters: float = proto.Field( + proto.DOUBLE, + number=8, + ) + max_loads: MutableMapping[str, 'ShipmentRoute.VehicleLoad'] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=9, + message='ShipmentRoute.VehicleLoad', + ) + + +class InjectedSolutionConstraint(proto.Message): + r"""Solution injected in the request including information about + which visits must be constrained and how they must be + constrained. + + Attributes: + routes (MutableSequence[google.maps.routeoptimization_v1.types.ShipmentRoute]): + Routes of the solution to inject. Some routes may be omitted + from the original solution. The routes and skipped shipments + must satisfy the basic validity assumptions listed for + ``injected_first_solution_routes``. + skipped_shipments (MutableSequence[google.maps.routeoptimization_v1.types.SkippedShipment]): + Skipped shipments of the solution to inject. Some may be + omitted from the original solution. See the ``routes`` + field. + constraint_relaxations (MutableSequence[google.maps.routeoptimization_v1.types.InjectedSolutionConstraint.ConstraintRelaxation]): + For zero or more groups of vehicles, + specifies when and how much to relax + constraints. If this field is empty, all + non-empty vehicle routes are fully constrained. + """ + + class ConstraintRelaxation(proto.Message): + r"""For a group of vehicles, specifies at what threshold(s) constraints + on visits will be relaxed and to which level. Shipments listed in + the ``skipped_shipment`` field are constrained to be skipped; i.e., + they cannot be performed. + + Attributes: + relaxations (MutableSequence[google.maps.routeoptimization_v1.types.InjectedSolutionConstraint.ConstraintRelaxation.Relaxation]): + All the visit constraint relaxations that will apply to + visits on routes with vehicles in ``vehicle_indices``. + vehicle_indices (MutableSequence[int]): + Specifies the vehicle indices to which the visit constraint + ``relaxations`` apply. If empty, this is considered the + default and the ``relaxations`` apply to all vehicles that + are not specified in other ``constraint_relaxations``. There + can be at most one default, i.e., at most one constraint + relaxation field is allowed empty ``vehicle_indices``. A + vehicle index can only be listed once, even within several + ``constraint_relaxations``. + + A vehicle index is mapped the same as + [ShipmentRoute.vehicle_index][google.maps.routeoptimization.v1.ShipmentRoute.vehicle_index], + if ``interpret_injected_solutions_using_labels`` is true + (see ``fields`` comment). + """ + + class Relaxation(proto.Message): + r"""If ``relaxations`` is empty, the start time and sequence of all + visits on ``routes`` are fully constrained and no new visits may be + inserted or added to those routes. Also, a vehicle's start and end + time in ``routes`` is fully constrained, unless the vehicle is empty + (i.e., has no visits and has ``used_if_route_is_empty`` set to false + in the model). + + ``relaxations(i).level`` specifies the constraint relaxation level + applied to a visit #j that satisfies: + + - ``route.visits(j).start_time >= relaxations(i).threshold_time`` + AND + - ``j + 1 >= relaxations(i).threshold_visit_count`` + + Similarly, the vehicle start is relaxed to ``relaxations(i).level`` + if it satisfies: + + - ``vehicle_start_time >= relaxations(i).threshold_time`` AND + - ``relaxations(i).threshold_visit_count == 0`` and the vehicle end + is relaxed to ``relaxations(i).level`` if it satisfies: + - ``vehicle_end_time >= relaxations(i).threshold_time`` AND + - ``route.visits_size() + 1 >= relaxations(i).threshold_visit_count`` + + To apply a relaxation level if a visit meets the + ``threshold_visit_count`` OR the ``threshold_time`` add two + ``relaxations`` with the same ``level``: one with only + ``threshold_visit_count`` set and the other with only + ``threshold_time`` set. If a visit satisfies the conditions of + multiple ``relaxations``, the most relaxed level applies. As a + result, from the vehicle start through the route visits in order to + the vehicle end, the relaxation level becomes more relaxed: i.e., + the relaxation level is non-decreasing as the route progresses. + + The timing and sequence of route visits that do not satisfy the + threshold conditions of any ``relaxations`` are fully constrained + and no visits may be inserted into these sequences. Also, if a + vehicle start or end does not satisfy the conditions of any + relaxation the time is fixed, unless the vehicle is empty. + + Attributes: + level (google.maps.routeoptimization_v1.types.InjectedSolutionConstraint.ConstraintRelaxation.Relaxation.Level): + The constraint relaxation level that applies when the + conditions at or after ``threshold_time`` AND at least + ``threshold_visit_count`` are satisfied. + threshold_time (google.protobuf.timestamp_pb2.Timestamp): + The time at or after which the relaxation ``level`` may be + applied. + threshold_visit_count (int): + The number of visits at or after which the relaxation + ``level`` may be applied. If ``threshold_visit_count`` is 0 + (or unset), the ``level`` may be applied directly at the + vehicle start. + + If it is ``route.visits_size() + 1``, the ``level`` may only + be applied to the vehicle end. If it is more than + ``route.visits_size() + 1``, ``level`` is not applied at all + for that route. + """ + class Level(proto.Enum): + r"""Expresses the different constraint relaxation levels, which + are applied for a visit and those that follow when it satisfies + the threshold conditions. + + The enumeration below is in order of increasing relaxation. + + Values: + LEVEL_UNSPECIFIED (0): + Implicit default relaxation level: no constraints are + relaxed, i.e., all visits are fully constrained. + + This value must not be explicitly used in ``level``. + RELAX_VISIT_TIMES_AFTER_THRESHOLD (1): + Visit start times and vehicle start/end times + will be relaxed, but each visit remains bound to + the same vehicle and the visit sequence must be + observed: no visit can be inserted between them + or before them. + RELAX_VISIT_TIMES_AND_SEQUENCE_AFTER_THRESHOLD (2): + Same as ``RELAX_VISIT_TIMES_AFTER_THRESHOLD``, but the visit + sequence is also relaxed: visits can only be performed by + this vehicle, but can potentially become unperformed. + RELAX_ALL_AFTER_THRESHOLD (3): + Same as ``RELAX_VISIT_TIMES_AND_SEQUENCE_AFTER_THRESHOLD``, + but the vehicle is also relaxed: visits are completely free + at or after the threshold time and can potentially become + unperformed. + """ + LEVEL_UNSPECIFIED = 0 + RELAX_VISIT_TIMES_AFTER_THRESHOLD = 1 + RELAX_VISIT_TIMES_AND_SEQUENCE_AFTER_THRESHOLD = 2 + RELAX_ALL_AFTER_THRESHOLD = 3 + + level: 'InjectedSolutionConstraint.ConstraintRelaxation.Relaxation.Level' = proto.Field( + proto.ENUM, + number=1, + enum='InjectedSolutionConstraint.ConstraintRelaxation.Relaxation.Level', + ) + threshold_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + threshold_visit_count: int = proto.Field( + proto.INT32, + number=3, + ) + + relaxations: MutableSequence['InjectedSolutionConstraint.ConstraintRelaxation.Relaxation'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='InjectedSolutionConstraint.ConstraintRelaxation.Relaxation', + ) + vehicle_indices: MutableSequence[int] = proto.RepeatedField( + proto.INT32, + number=2, + ) + + routes: MutableSequence['ShipmentRoute'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ShipmentRoute', + ) + skipped_shipments: MutableSequence['SkippedShipment'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='SkippedShipment', + ) + constraint_relaxations: MutableSequence[ConstraintRelaxation] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=ConstraintRelaxation, + ) + + +class OptimizeToursValidationError(proto.Message): + r"""Describes an error or warning encountered when validating an + ``OptimizeToursRequest``. + + Attributes: + code (int): + A validation error is defined by the pair (``code``, + ``display_name``) which are always present. + + The fields following this section provide more context about + the error. + + *MULTIPLE ERRORS*: When there are multiple errors, the + validation process tries to output several of them. Much + like a compiler, this is an imperfect process. Some + validation errors will be "fatal", meaning that they stop + the entire validation process. This is the case for + ``display_name="UNSPECIFIED"`` errors, among others. Some + errors may cause the validation process to skip other + errors. + + *STABILITY*: ``code`` and ``display_name`` should be very + stable. But new codes and display names may appear over + time, which may cause a given (invalid) request to yield a + different (``code``, ``display_name``) pair because the new + error hid the old one. For example, see "MULTIPLE ERRORS". + display_name (str): + The error display name. + fields (MutableSequence[google.maps.routeoptimization_v1.types.OptimizeToursValidationError.FieldReference]): + An error context may involve 0, 1 (most of the time) or more + fields. For example, referring to vehicle #4 and shipment + #2's first pickup can be done as follows: + + :: + + fields { name: "vehicles" index: 4} + fields { name: "shipments" index: 2 sub_field {name: "pickups" index: 0} } + + Note, however, that the cardinality of ``fields`` should not + change for a given error code. + error_message (str): + Human-readable string describing the error. There is a 1:1 + mapping between ``code`` and ``error_message`` (when code != + "UNSPECIFIED"). + + *STABILITY*: Not stable: the error message associated to a + given ``code`` may change (hopefully to clarify it) over + time. Please rely on the ``display_name`` and ``code`` + instead. + offending_values (str): + May contain the value(s) of the field(s). + This is not always available. You should + absolutely not rely on it and use it only for + manual model debugging. + """ + + class FieldReference(proto.Message): + r"""Specifies a context for the validation error. A ``FieldReference`` + always refers to a given field in this file and follows the same + hierarchical structure. For example, we may specify element #2 of + ``start_time_windows`` of vehicle #5 using: + + :: + + name: "vehicles" index: 5 sub_field { name: "end_time_windows" index: 2 } + + We however omit top-level entities such as ``OptimizeToursRequest`` + or ``ShipmentModel`` to avoid crowding the message. + + 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: + name (str): + Name of the field, e.g., "vehicles". + index (int): + Index of the field if repeated. + + This field is a member of `oneof`_ ``index_or_key``. + key (str): + Key if the field is a map. + + This field is a member of `oneof`_ ``index_or_key``. + sub_field (google.maps.routeoptimization_v1.types.OptimizeToursValidationError.FieldReference): + Recursively nested sub-field, if needed. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + index: int = proto.Field( + proto.INT32, + number=2, + oneof='index_or_key', + ) + key: str = proto.Field( + proto.STRING, + number=4, + oneof='index_or_key', + ) + sub_field: 'OptimizeToursValidationError.FieldReference' = proto.Field( + proto.MESSAGE, + number=3, + message='OptimizeToursValidationError.FieldReference', + ) + + code: int = proto.Field( + proto.INT32, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + fields: MutableSequence[FieldReference] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=FieldReference, + ) + error_message: str = proto.Field( + proto.STRING, + number=4, + ) + offending_values: str = proto.Field( + proto.STRING, + number=5, + ) + + +class InputConfig(proto.Message): + r"""Specify an input for + [BatchOptimizeTours][google.maps.routeoptimization.v1.RouteOptimizationService.BatchOptimizeTours]. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gcs_source (google.maps.routeoptimization_v1.types.GcsSource): + A Google Cloud Storage location. This must be + a single object (file). + + This field is a member of `oneof`_ ``source``. + data_format (google.maps.routeoptimization_v1.types.DataFormat): + Required. The input data format. + """ + + gcs_source: 'GcsSource' = proto.Field( + proto.MESSAGE, + number=1, + oneof='source', + message='GcsSource', + ) + data_format: 'DataFormat' = proto.Field( + proto.ENUM, + number=2, + enum='DataFormat', + ) + + +class OutputConfig(proto.Message): + r"""Specify a destination for + [BatchOptimizeTours][google.maps.routeoptimization.v1.RouteOptimizationService.BatchOptimizeTours] + results. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gcs_destination (google.maps.routeoptimization_v1.types.GcsDestination): + The Google Cloud Storage location to write + the output to. + + This field is a member of `oneof`_ ``destination``. + data_format (google.maps.routeoptimization_v1.types.DataFormat): + Required. The output data format. + """ + + gcs_destination: 'GcsDestination' = proto.Field( + proto.MESSAGE, + number=1, + oneof='destination', + message='GcsDestination', + ) + data_format: 'DataFormat' = proto.Field( + proto.ENUM, + number=2, + enum='DataFormat', + ) + + +class GcsSource(proto.Message): + r"""The Google Cloud Storage location where the input file will + be read from. + + Attributes: + uri (str): + Required. URI of a Google Cloud Storage object with the + format ``gs://bucket/path/to/object``. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GcsDestination(proto.Message): + r"""The Google Cloud Storage location where the output file(s) + will be written to. + + Attributes: + uri (str): + Required. Google Cloud Storage URI. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/mypy.ini b/owl-bot-staging/google-maps-routeoptimization/v1/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/noxfile.py b/owl-bot-staging/google-maps-routeoptimization/v1/noxfile.py new file mode 100644 index 000000000000..4d8faceb4ca0 --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/noxfile.py @@ -0,0 +1,280 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = 'google-maps-routeoptimization' + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.13" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "prerelease_deps", +] + +@nox.session(python=ALL_PYTHON) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def unit(session, protobuf_implementation): + """Run the unit test suite.""" + + 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+") + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") + + # 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") + + session.run( + 'py.test', + '--quiet', + '--cov=google/maps/routeoptimization_v1/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)), + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + +@nox.session(python=ALL_PYTHON[-1]) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def prerelease_deps(session, protobuf_implementation): + """Run the unit test suite against pre-release versions of dependencies.""" + + 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 test environment dependencies + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + + # Install the package without dependencies + session.install('-e', '.', '--no-deps') + + # We test the minimum dependency versions using the minimum Python + # version so the lowest python runtime that we test has a corresponding constraints + # file, located at `testing/constraints--.txt`, which contains all of the + # 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 + ) + ] + + session.install(*constraints_deps) + + prerel_deps = [ + "googleapis-common-protos", + "google-api-core", + "google-auth", + # Exclude grpcio!=1.67.0rc1 which does not support python 3.13 + "grpcio!=1.67.0rc1", + "grpcio-status", + "protobuf", + "proto-plus", + ] + + for dep in prerel_deps: + session.install("--pre", "--no-deps", "--upgrade", dep) + + # Remaining dependencies + other_deps = [ + "requests", + ] + session.install(*other_deps) + + # Print out prerelease package versions + + session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") + session.run("python", "-c", "import google.auth; print(google.auth.__version__)") + session.run("python", "-c", "import grpc; print(grpc.__version__)") + session.run( + "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" + ) + session.run( + "python", "-c", "import proto; print(proto.__version__)" + ) + + session.run( + 'py.test', + '--quiet', + '--cov=google/maps/routeoptimization_v1/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)), + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + + +@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=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 docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==7.0.1", "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=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", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/samples/generated_samples/routeoptimization_v1_generated_route_optimization_batch_optimize_tours_async.py b/owl-bot-staging/google-maps-routeoptimization/v1/samples/generated_samples/routeoptimization_v1_generated_route_optimization_batch_optimize_tours_async.py new file mode 100644 index 000000000000..6086f976fcca --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/samples/generated_samples/routeoptimization_v1_generated_route_optimization_batch_optimize_tours_async.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchOptimizeTours +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-routeoptimization + + +# [START routeoptimization_v1_generated_RouteOptimization_BatchOptimizeTours_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.maps import routeoptimization_v1 + + +async def sample_batch_optimize_tours(): + # Create a client + client = routeoptimization_v1.RouteOptimizationAsyncClient() + + # Initialize request argument(s) + model_configs = routeoptimization_v1.AsyncModelConfig() + model_configs.input_config.gcs_source.uri = "uri_value" + model_configs.input_config.data_format = "PROTO_TEXT" + model_configs.output_config.gcs_destination.uri = "uri_value" + model_configs.output_config.data_format = "PROTO_TEXT" + + request = routeoptimization_v1.BatchOptimizeToursRequest( + parent="parent_value", + model_configs=model_configs, + ) + + # Make the request + operation = client.batch_optimize_tours(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END routeoptimization_v1_generated_RouteOptimization_BatchOptimizeTours_async] diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/samples/generated_samples/routeoptimization_v1_generated_route_optimization_batch_optimize_tours_sync.py b/owl-bot-staging/google-maps-routeoptimization/v1/samples/generated_samples/routeoptimization_v1_generated_route_optimization_batch_optimize_tours_sync.py new file mode 100644 index 000000000000..77ae2122ea29 --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/samples/generated_samples/routeoptimization_v1_generated_route_optimization_batch_optimize_tours_sync.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchOptimizeTours +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-routeoptimization + + +# [START routeoptimization_v1_generated_RouteOptimization_BatchOptimizeTours_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.maps import routeoptimization_v1 + + +def sample_batch_optimize_tours(): + # Create a client + client = routeoptimization_v1.RouteOptimizationClient() + + # Initialize request argument(s) + model_configs = routeoptimization_v1.AsyncModelConfig() + model_configs.input_config.gcs_source.uri = "uri_value" + model_configs.input_config.data_format = "PROTO_TEXT" + model_configs.output_config.gcs_destination.uri = "uri_value" + model_configs.output_config.data_format = "PROTO_TEXT" + + request = routeoptimization_v1.BatchOptimizeToursRequest( + parent="parent_value", + model_configs=model_configs, + ) + + # Make the request + operation = client.batch_optimize_tours(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END routeoptimization_v1_generated_RouteOptimization_BatchOptimizeTours_sync] diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/samples/generated_samples/routeoptimization_v1_generated_route_optimization_optimize_tours_async.py b/owl-bot-staging/google-maps-routeoptimization/v1/samples/generated_samples/routeoptimization_v1_generated_route_optimization_optimize_tours_async.py new file mode 100644 index 000000000000..e27f39d51f1e --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/samples/generated_samples/routeoptimization_v1_generated_route_optimization_optimize_tours_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for OptimizeTours +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-routeoptimization + + +# [START routeoptimization_v1_generated_RouteOptimization_OptimizeTours_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.maps import routeoptimization_v1 + + +async def sample_optimize_tours(): + # Create a client + client = routeoptimization_v1.RouteOptimizationAsyncClient() + + # Initialize request argument(s) + request = routeoptimization_v1.OptimizeToursRequest( + parent="parent_value", + ) + + # Make the request + response = await client.optimize_tours(request=request) + + # Handle the response + print(response) + +# [END routeoptimization_v1_generated_RouteOptimization_OptimizeTours_async] diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/samples/generated_samples/routeoptimization_v1_generated_route_optimization_optimize_tours_sync.py b/owl-bot-staging/google-maps-routeoptimization/v1/samples/generated_samples/routeoptimization_v1_generated_route_optimization_optimize_tours_sync.py new file mode 100644 index 000000000000..dd85447bf985 --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/samples/generated_samples/routeoptimization_v1_generated_route_optimization_optimize_tours_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for OptimizeTours +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-routeoptimization + + +# [START routeoptimization_v1_generated_RouteOptimization_OptimizeTours_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.maps import routeoptimization_v1 + + +def sample_optimize_tours(): + # Create a client + client = routeoptimization_v1.RouteOptimizationClient() + + # Initialize request argument(s) + request = routeoptimization_v1.OptimizeToursRequest( + parent="parent_value", + ) + + # Make the request + response = client.optimize_tours(request=request) + + # Handle the response + print(response) + +# [END routeoptimization_v1_generated_RouteOptimization_OptimizeTours_sync] diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/samples/generated_samples/snippet_metadata_google.maps.routeoptimization.v1.json b/owl-bot-staging/google-maps-routeoptimization/v1/samples/generated_samples/snippet_metadata_google.maps.routeoptimization.v1.json new file mode 100644 index 000000000000..fcfcf65d2f4f --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/samples/generated_samples/snippet_metadata_google.maps.routeoptimization.v1.json @@ -0,0 +1,321 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.maps.routeoptimization.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-maps-routeoptimization", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.routeoptimization_v1.RouteOptimizationAsyncClient", + "shortName": "RouteOptimizationAsyncClient" + }, + "fullName": "google.maps.routeoptimization_v1.RouteOptimizationAsyncClient.batch_optimize_tours", + "method": { + "fullName": "google.maps.routeoptimization.v1.RouteOptimization.BatchOptimizeTours", + "service": { + "fullName": "google.maps.routeoptimization.v1.RouteOptimization", + "shortName": "RouteOptimization" + }, + "shortName": "BatchOptimizeTours" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.routeoptimization_v1.types.BatchOptimizeToursRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "batch_optimize_tours" + }, + "description": "Sample for BatchOptimizeTours", + "file": "routeoptimization_v1_generated_route_optimization_batch_optimize_tours_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "routeoptimization_v1_generated_RouteOptimization_BatchOptimizeTours_async", + "segments": [ + { + "end": 62, + "start": 27, + "type": "FULL" + }, + { + "end": 62, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 52, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 59, + "start": 53, + "type": "REQUEST_EXECUTION" + }, + { + "end": 63, + "start": 60, + "type": "RESPONSE_HANDLING" + } + ], + "title": "routeoptimization_v1_generated_route_optimization_batch_optimize_tours_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.routeoptimization_v1.RouteOptimizationClient", + "shortName": "RouteOptimizationClient" + }, + "fullName": "google.maps.routeoptimization_v1.RouteOptimizationClient.batch_optimize_tours", + "method": { + "fullName": "google.maps.routeoptimization.v1.RouteOptimization.BatchOptimizeTours", + "service": { + "fullName": "google.maps.routeoptimization.v1.RouteOptimization", + "shortName": "RouteOptimization" + }, + "shortName": "BatchOptimizeTours" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.routeoptimization_v1.types.BatchOptimizeToursRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "batch_optimize_tours" + }, + "description": "Sample for BatchOptimizeTours", + "file": "routeoptimization_v1_generated_route_optimization_batch_optimize_tours_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "routeoptimization_v1_generated_RouteOptimization_BatchOptimizeTours_sync", + "segments": [ + { + "end": 62, + "start": 27, + "type": "FULL" + }, + { + "end": 62, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 52, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 59, + "start": 53, + "type": "REQUEST_EXECUTION" + }, + { + "end": 63, + "start": 60, + "type": "RESPONSE_HANDLING" + } + ], + "title": "routeoptimization_v1_generated_route_optimization_batch_optimize_tours_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.routeoptimization_v1.RouteOptimizationAsyncClient", + "shortName": "RouteOptimizationAsyncClient" + }, + "fullName": "google.maps.routeoptimization_v1.RouteOptimizationAsyncClient.optimize_tours", + "method": { + "fullName": "google.maps.routeoptimization.v1.RouteOptimization.OptimizeTours", + "service": { + "fullName": "google.maps.routeoptimization.v1.RouteOptimization", + "shortName": "RouteOptimization" + }, + "shortName": "OptimizeTours" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.routeoptimization_v1.types.OptimizeToursRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.maps.routeoptimization_v1.types.OptimizeToursResponse", + "shortName": "optimize_tours" + }, + "description": "Sample for OptimizeTours", + "file": "routeoptimization_v1_generated_route_optimization_optimize_tours_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "routeoptimization_v1_generated_RouteOptimization_OptimizeTours_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": "routeoptimization_v1_generated_route_optimization_optimize_tours_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.routeoptimization_v1.RouteOptimizationClient", + "shortName": "RouteOptimizationClient" + }, + "fullName": "google.maps.routeoptimization_v1.RouteOptimizationClient.optimize_tours", + "method": { + "fullName": "google.maps.routeoptimization.v1.RouteOptimization.OptimizeTours", + "service": { + "fullName": "google.maps.routeoptimization.v1.RouteOptimization", + "shortName": "RouteOptimization" + }, + "shortName": "OptimizeTours" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.routeoptimization_v1.types.OptimizeToursRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.maps.routeoptimization_v1.types.OptimizeToursResponse", + "shortName": "optimize_tours" + }, + "description": "Sample for OptimizeTours", + "file": "routeoptimization_v1_generated_route_optimization_optimize_tours_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "routeoptimization_v1_generated_RouteOptimization_OptimizeTours_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": "routeoptimization_v1_generated_route_optimization_optimize_tours_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/scripts/fixup_routeoptimization_v1_keywords.py b/owl-bot-staging/google-maps-routeoptimization/v1/scripts/fixup_routeoptimization_v1_keywords.py new file mode 100644 index 000000000000..fd04064542c9 --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/scripts/fixup_routeoptimization_v1_keywords.py @@ -0,0 +1,177 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 routeoptimizationCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'batch_optimize_tours': ('parent', 'model_configs', ), + 'optimize_tours': ('parent', 'timeout', 'model', 'solving_mode', 'search_mode', 'injected_first_solution_routes', 'injected_solution_constraint', 'refresh_details_routes', 'interpret_injected_solutions_using_labels', 'consider_road_traffic', 'populate_polylines', 'populate_transition_polylines', 'allow_large_deadline_despite_interruption_risk', 'use_geodesic_distances', 'geodesic_meters_per_second', 'max_validation_errors', 'label', ), + } + + 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=routeoptimizationCallTransformer(), +): + """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 routeoptimization 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-maps-routeoptimization/v1/setup.py b/owl-bot-staging/google-maps-routeoptimization/v1/setup.py new file mode 100644 index 000000000000..035a5065f208 --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/setup.py @@ -0,0 +1,98 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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-maps-routeoptimization' + + +description = "Google Maps Routeoptimization API client library" + +version = None + +with open(os.path.join(package_root, 'google/maps/routeoptimization/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.0dev,!=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.0dev,!=2.24.0,!=2.25.0", + "proto-plus >= 1.22.3, <2.0.0dev", + "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'", + "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", +] +extras = { +} +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-routeoptimization" + +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-maps-routeoptimization/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.10.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.11.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.12.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.13.txt b/owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.13.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.13.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.7.txt new file mode 100644 index 000000000000..fc812592b0ee --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.7.txt @@ -0,0 +1,10 @@ +# 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.0dev", +# 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 diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.8.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.9.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/tests/__init__.py b/owl-bot-staging/google-maps-routeoptimization/v1/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-maps-routeoptimization/v1/tests/unit/__init__.py b/owl-bot-staging/google-maps-routeoptimization/v1/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-maps-routeoptimization/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-maps-routeoptimization/v1/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-maps-routeoptimization/v1/tests/unit/gapic/routeoptimization_v1/__init__.py b/owl-bot-staging/google-maps-routeoptimization/v1/tests/unit/gapic/routeoptimization_v1/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/tests/unit/gapic/routeoptimization_v1/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-maps-routeoptimization/v1/tests/unit/gapic/routeoptimization_v1/test_route_optimization.py b/owl-bot-staging/google-maps-routeoptimization/v1/tests/unit/gapic/routeoptimization_v1/test_route_optimization.py new file mode 100644 index 000000000000..9009b4f0f73f --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/tests/unit/gapic/routeoptimization_v1/test_route_optimization.py @@ -0,0 +1,2698 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.longrunning import operations_pb2 # type: ignore +from google.maps.routeoptimization_v1.services.route_optimization import RouteOptimizationAsyncClient +from google.maps.routeoptimization_v1.services.route_optimization import RouteOptimizationClient +from google.maps.routeoptimization_v1.services.route_optimization import transports +from google.maps.routeoptimization_v1.types import route_optimization_service +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore +import google.auth + + +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 RouteOptimizationClient._get_default_mtls_endpoint(None) is None + assert RouteOptimizationClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert RouteOptimizationClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert RouteOptimizationClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert RouteOptimizationClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert RouteOptimizationClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert RouteOptimizationClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert RouteOptimizationClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert RouteOptimizationClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + RouteOptimizationClient._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 RouteOptimizationClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert RouteOptimizationClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert RouteOptimizationClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + RouteOptimizationClient._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 RouteOptimizationClient._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 RouteOptimizationClient._get_client_cert_source(None, False) is None + assert RouteOptimizationClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert RouteOptimizationClient._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 RouteOptimizationClient._get_client_cert_source(None, True) is mock_default_cert_source + assert RouteOptimizationClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(RouteOptimizationClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RouteOptimizationClient)) +@mock.patch.object(RouteOptimizationAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RouteOptimizationAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = RouteOptimizationClient._DEFAULT_UNIVERSE + default_endpoint = RouteOptimizationClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = RouteOptimizationClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert RouteOptimizationClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert RouteOptimizationClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == RouteOptimizationClient.DEFAULT_MTLS_ENDPOINT + assert RouteOptimizationClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert RouteOptimizationClient._get_api_endpoint(None, None, default_universe, "always") == RouteOptimizationClient.DEFAULT_MTLS_ENDPOINT + assert RouteOptimizationClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == RouteOptimizationClient.DEFAULT_MTLS_ENDPOINT + assert RouteOptimizationClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert RouteOptimizationClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + RouteOptimizationClient._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 RouteOptimizationClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert RouteOptimizationClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert RouteOptimizationClient._get_universe_domain(None, None) == RouteOptimizationClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + RouteOptimizationClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize("client_class,transport_name", [ + (RouteOptimizationClient, "grpc"), + (RouteOptimizationAsyncClient, "grpc_asyncio"), + (RouteOptimizationClient, "rest"), +]) +def test_route_optimization_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 == ( + 'routeoptimization.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://routeoptimization.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.RouteOptimizationGrpcTransport, "grpc"), + (transports.RouteOptimizationGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.RouteOptimizationRestTransport, "rest"), +]) +def test_route_optimization_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", [ + (RouteOptimizationClient, "grpc"), + (RouteOptimizationAsyncClient, "grpc_asyncio"), + (RouteOptimizationClient, "rest"), +]) +def test_route_optimization_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 == ( + 'routeoptimization.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://routeoptimization.googleapis.com' + ) + + +def test_route_optimization_client_get_transport_class(): + transport = RouteOptimizationClient.get_transport_class() + available_transports = [ + transports.RouteOptimizationGrpcTransport, + transports.RouteOptimizationRestTransport, + ] + assert transport in available_transports + + transport = RouteOptimizationClient.get_transport_class("grpc") + assert transport == transports.RouteOptimizationGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (RouteOptimizationClient, transports.RouteOptimizationGrpcTransport, "grpc"), + (RouteOptimizationAsyncClient, transports.RouteOptimizationGrpcAsyncIOTransport, "grpc_asyncio"), + (RouteOptimizationClient, transports.RouteOptimizationRestTransport, "rest"), +]) +@mock.patch.object(RouteOptimizationClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RouteOptimizationClient)) +@mock.patch.object(RouteOptimizationAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RouteOptimizationAsyncClient)) +def test_route_optimization_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(RouteOptimizationClient, '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(RouteOptimizationClient, '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", [ + (RouteOptimizationClient, transports.RouteOptimizationGrpcTransport, "grpc", "true"), + (RouteOptimizationAsyncClient, transports.RouteOptimizationGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (RouteOptimizationClient, transports.RouteOptimizationGrpcTransport, "grpc", "false"), + (RouteOptimizationAsyncClient, transports.RouteOptimizationGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (RouteOptimizationClient, transports.RouteOptimizationRestTransport, "rest", "true"), + (RouteOptimizationClient, transports.RouteOptimizationRestTransport, "rest", "false"), +]) +@mock.patch.object(RouteOptimizationClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RouteOptimizationClient)) +@mock.patch.object(RouteOptimizationAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RouteOptimizationAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_route_optimization_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", [ + RouteOptimizationClient, RouteOptimizationAsyncClient +]) +@mock.patch.object(RouteOptimizationClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RouteOptimizationClient)) +@mock.patch.object(RouteOptimizationAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RouteOptimizationAsyncClient)) +def test_route_optimization_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", [ + RouteOptimizationClient, RouteOptimizationAsyncClient +]) +@mock.patch.object(RouteOptimizationClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RouteOptimizationClient)) +@mock.patch.object(RouteOptimizationAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RouteOptimizationAsyncClient)) +def test_route_optimization_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = RouteOptimizationClient._DEFAULT_UNIVERSE + default_endpoint = RouteOptimizationClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = RouteOptimizationClient._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", [ + (RouteOptimizationClient, transports.RouteOptimizationGrpcTransport, "grpc"), + (RouteOptimizationAsyncClient, transports.RouteOptimizationGrpcAsyncIOTransport, "grpc_asyncio"), + (RouteOptimizationClient, transports.RouteOptimizationRestTransport, "rest"), +]) +def test_route_optimization_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", [ + (RouteOptimizationClient, transports.RouteOptimizationGrpcTransport, "grpc", grpc_helpers), + (RouteOptimizationAsyncClient, transports.RouteOptimizationGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (RouteOptimizationClient, transports.RouteOptimizationRestTransport, "rest", None), +]) +def test_route_optimization_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_route_optimization_client_client_options_from_dict(): + with mock.patch('google.maps.routeoptimization_v1.services.route_optimization.transports.RouteOptimizationGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = RouteOptimizationClient( + 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", [ + (RouteOptimizationClient, transports.RouteOptimizationGrpcTransport, "grpc", grpc_helpers), + (RouteOptimizationAsyncClient, transports.RouteOptimizationGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_route_optimization_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( + "routeoptimization.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=None, + default_host="routeoptimization.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + route_optimization_service.OptimizeToursRequest, + dict, +]) +def test_optimize_tours(request_type, transport: str = 'grpc'): + client = RouteOptimizationClient( + 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.optimize_tours), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = route_optimization_service.OptimizeToursResponse( + request_label='request_label_value', + ) + response = client.optimize_tours(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = route_optimization_service.OptimizeToursRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, route_optimization_service.OptimizeToursResponse) + assert response.request_label == 'request_label_value' + + +def test_optimize_tours_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 = RouteOptimizationClient( + 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 = route_optimization_service.OptimizeToursRequest( + parent='parent_value', + label='label_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.optimize_tours), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.optimize_tours(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == route_optimization_service.OptimizeToursRequest( + parent='parent_value', + label='label_value', + ) + +def test_optimize_tours_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RouteOptimizationClient( + 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.optimize_tours in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.optimize_tours] = mock_rpc + request = {} + client.optimize_tours(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.optimize_tours(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_optimize_tours_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = RouteOptimizationAsyncClient( + 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.optimize_tours in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.optimize_tours] = mock_rpc + + request = {} + await client.optimize_tours(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.optimize_tours(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_optimize_tours_async(transport: str = 'grpc_asyncio', request_type=route_optimization_service.OptimizeToursRequest): + client = RouteOptimizationAsyncClient( + 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.optimize_tours), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(route_optimization_service.OptimizeToursResponse( + request_label='request_label_value', + )) + response = await client.optimize_tours(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = route_optimization_service.OptimizeToursRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, route_optimization_service.OptimizeToursResponse) + assert response.request_label == 'request_label_value' + + +@pytest.mark.asyncio +async def test_optimize_tours_async_from_dict(): + await test_optimize_tours_async(request_type=dict) + +def test_optimize_tours_field_headers(): + client = RouteOptimizationClient( + 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 = route_optimization_service.OptimizeToursRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.optimize_tours), + '__call__') as call: + call.return_value = route_optimization_service.OptimizeToursResponse() + client.optimize_tours(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_optimize_tours_field_headers_async(): + client = RouteOptimizationAsyncClient( + 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 = route_optimization_service.OptimizeToursRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.optimize_tours), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(route_optimization_service.OptimizeToursResponse()) + await client.optimize_tours(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + route_optimization_service.BatchOptimizeToursRequest, + dict, +]) +def test_batch_optimize_tours(request_type, transport: str = 'grpc'): + client = RouteOptimizationClient( + 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.batch_optimize_tours), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.batch_optimize_tours(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = route_optimization_service.BatchOptimizeToursRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_batch_optimize_tours_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 = RouteOptimizationClient( + 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 = route_optimization_service.BatchOptimizeToursRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_optimize_tours), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.batch_optimize_tours(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == route_optimization_service.BatchOptimizeToursRequest( + parent='parent_value', + ) + +def test_batch_optimize_tours_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RouteOptimizationClient( + 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.batch_optimize_tours in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.batch_optimize_tours] = mock_rpc + request = {} + client.batch_optimize_tours(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.batch_optimize_tours(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_batch_optimize_tours_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = RouteOptimizationAsyncClient( + 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.batch_optimize_tours in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.batch_optimize_tours] = mock_rpc + + request = {} + await client.batch_optimize_tours(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.batch_optimize_tours(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_batch_optimize_tours_async(transport: str = 'grpc_asyncio', request_type=route_optimization_service.BatchOptimizeToursRequest): + client = RouteOptimizationAsyncClient( + 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.batch_optimize_tours), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.batch_optimize_tours(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = route_optimization_service.BatchOptimizeToursRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_batch_optimize_tours_async_from_dict(): + await test_batch_optimize_tours_async(request_type=dict) + +def test_batch_optimize_tours_field_headers(): + client = RouteOptimizationClient( + 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 = route_optimization_service.BatchOptimizeToursRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_optimize_tours), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.batch_optimize_tours(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_batch_optimize_tours_field_headers_async(): + client = RouteOptimizationAsyncClient( + 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 = route_optimization_service.BatchOptimizeToursRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_optimize_tours), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.batch_optimize_tours(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_optimize_tours_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 = RouteOptimizationClient( + 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.optimize_tours in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.optimize_tours] = mock_rpc + + request = {} + client.optimize_tours(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.optimize_tours(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_optimize_tours_rest_required_fields(request_type=route_optimization_service.OptimizeToursRequest): + transport_class = transports.RouteOptimizationRestTransport + + 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()).optimize_tours._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()).optimize_tours._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 = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = route_optimization_service.OptimizeToursResponse() + # 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 = route_optimization_service.OptimizeToursResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.optimize_tours(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_optimize_tours_rest_unset_required_fields(): + transport = transports.RouteOptimizationRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.optimize_tours._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", ))) + + +def test_batch_optimize_tours_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 = RouteOptimizationClient( + 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.batch_optimize_tours in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.batch_optimize_tours] = mock_rpc + + request = {} + client.batch_optimize_tours(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.batch_optimize_tours(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_batch_optimize_tours_rest_required_fields(request_type=route_optimization_service.BatchOptimizeToursRequest): + transport_class = transports.RouteOptimizationRestTransport + + 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()).batch_optimize_tours._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()).batch_optimize_tours._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 = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields 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 = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.batch_optimize_tours(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_batch_optimize_tours_rest_unset_required_fields(): + transport = transports.RouteOptimizationRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.batch_optimize_tours._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "modelConfigs", ))) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.RouteOptimizationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.RouteOptimizationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RouteOptimizationClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.RouteOptimizationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RouteOptimizationClient( + 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 = RouteOptimizationClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.RouteOptimizationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RouteOptimizationClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.RouteOptimizationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = RouteOptimizationClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.RouteOptimizationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.RouteOptimizationGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.RouteOptimizationGrpcTransport, + transports.RouteOptimizationGrpcAsyncIOTransport, + transports.RouteOptimizationRestTransport, +]) +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 = RouteOptimizationClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = RouteOptimizationClient( + 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_optimize_tours_empty_call_grpc(): + client = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.optimize_tours), + '__call__') as call: + call.return_value = route_optimization_service.OptimizeToursResponse() + client.optimize_tours(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = route_optimization_service.OptimizeToursRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_batch_optimize_tours_empty_call_grpc(): + client = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_optimize_tours), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.batch_optimize_tours(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = route_optimization_service.BatchOptimizeToursRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = RouteOptimizationAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = RouteOptimizationAsyncClient( + 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_optimize_tours_empty_call_grpc_asyncio(): + client = RouteOptimizationAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.optimize_tours), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(route_optimization_service.OptimizeToursResponse( + request_label='request_label_value', + )) + await client.optimize_tours(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = route_optimization_service.OptimizeToursRequest() + + assert args[0] == request_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_batch_optimize_tours_empty_call_grpc_asyncio(): + client = RouteOptimizationAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_optimize_tours), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.batch_optimize_tours(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = route_optimization_service.BatchOptimizeToursRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = RouteOptimizationClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_optimize_tours_rest_bad_request(request_type=route_optimization_service.OptimizeToursRequest): + client = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a 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.optimize_tours(request) + + +@pytest.mark.parametrize("request_type", [ + route_optimization_service.OptimizeToursRequest, + dict, +]) +def test_optimize_tours_rest_call_success(request_type): + client = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = route_optimization_service.OptimizeToursResponse( + request_label='request_label_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 = route_optimization_service.OptimizeToursResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.optimize_tours(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, route_optimization_service.OptimizeToursResponse) + assert response.request_label == 'request_label_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_optimize_tours_rest_interceptors(null_interceptor): + transport = transports.RouteOptimizationRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RouteOptimizationRestInterceptor(), + ) + client = RouteOptimizationClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RouteOptimizationRestInterceptor, "post_optimize_tours") as post, \ + mock.patch.object(transports.RouteOptimizationRestInterceptor, "pre_optimize_tours") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = route_optimization_service.OptimizeToursRequest.pb(route_optimization_service.OptimizeToursRequest()) + 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 = route_optimization_service.OptimizeToursResponse.to_json(route_optimization_service.OptimizeToursResponse()) + req.return_value.content = return_value + + request = route_optimization_service.OptimizeToursRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = route_optimization_service.OptimizeToursResponse() + + client.optimize_tours(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_batch_optimize_tours_rest_bad_request(request_type=route_optimization_service.BatchOptimizeToursRequest): + client = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a 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.batch_optimize_tours(request) + + +@pytest.mark.parametrize("request_type", [ + route_optimization_service.BatchOptimizeToursRequest, + dict, +]) +def test_batch_optimize_tours_rest_call_success(request_type): + client = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.batch_optimize_tours(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_optimize_tours_rest_interceptors(null_interceptor): + transport = transports.RouteOptimizationRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RouteOptimizationRestInterceptor(), + ) + client = RouteOptimizationClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.RouteOptimizationRestInterceptor, "post_batch_optimize_tours") as post, \ + mock.patch.object(transports.RouteOptimizationRestInterceptor, "pre_batch_optimize_tours") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = route_optimization_service.BatchOptimizeToursRequest.pb(route_optimization_service.BatchOptimizeToursRequest()) + 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 = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = route_optimization_service.BatchOptimizeToursRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.batch_optimize_tours(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_operation_rest_bad_request(request_type=operations_pb2.GetOperationRequest): + client = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_initialize_client_w_rest(): + client = RouteOptimizationClient( + 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_optimize_tours_empty_call_rest(): + client = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.optimize_tours), + '__call__') as call: + client.optimize_tours(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = route_optimization_service.OptimizeToursRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_batch_optimize_tours_empty_call_rest(): + client = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_optimize_tours), + '__call__') as call: + client.batch_optimize_tours(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = route_optimization_service.BatchOptimizeToursRequest() + + assert args[0] == request_msg + + +def test_route_optimization_rest_lro_client(): + client = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, +operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.RouteOptimizationGrpcTransport, + ) + +def test_route_optimization_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.RouteOptimizationTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_route_optimization_base_transport(): + # Instantiate the base transport. + with mock.patch('google.maps.routeoptimization_v1.services.route_optimization.transports.RouteOptimizationTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.RouteOptimizationTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'optimize_tours', + 'batch_optimize_tours', + 'get_operation', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_route_optimization_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.maps.routeoptimization_v1.services.route_optimization.transports.RouteOptimizationTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RouteOptimizationTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_route_optimization_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.maps.routeoptimization_v1.services.route_optimization.transports.RouteOptimizationTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RouteOptimizationTransport() + adc.assert_called_once() + + +def test_route_optimization_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) + RouteOptimizationClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RouteOptimizationGrpcTransport, + transports.RouteOptimizationGrpcAsyncIOTransport, + ], +) +def test_route_optimization_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RouteOptimizationGrpcTransport, + transports.RouteOptimizationGrpcAsyncIOTransport, + transports.RouteOptimizationRestTransport, + ], +) +def test_route_optimization_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.RouteOptimizationGrpcTransport, grpc_helpers), + (transports.RouteOptimizationGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_route_optimization_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( + "routeoptimization.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=["1", "2"], + default_host="routeoptimization.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.RouteOptimizationGrpcTransport, transports.RouteOptimizationGrpcAsyncIOTransport]) +def test_route_optimization_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_route_optimization_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.RouteOptimizationRestTransport ( + 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_route_optimization_host_no_port(transport_name): + client = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='routeoptimization.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'routeoptimization.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://routeoptimization.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_route_optimization_host_with_port(transport_name): + client = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='routeoptimization.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'routeoptimization.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://routeoptimization.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_route_optimization_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = RouteOptimizationClient( + credentials=creds1, + transport=transport_name, + ) + client2 = RouteOptimizationClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.optimize_tours._session + session2 = client2.transport.optimize_tours._session + assert session1 != session2 + session1 = client1.transport.batch_optimize_tours._session + session2 = client2.transport.batch_optimize_tours._session + assert session1 != session2 +def test_route_optimization_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.RouteOptimizationGrpcTransport( + 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_route_optimization_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.RouteOptimizationGrpcAsyncIOTransport( + 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.RouteOptimizationGrpcTransport, transports.RouteOptimizationGrpcAsyncIOTransport]) +def test_route_optimization_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.RouteOptimizationGrpcTransport, transports.RouteOptimizationGrpcAsyncIOTransport]) +def test_route_optimization_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_route_optimization_grpc_lro_client(): + client = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_route_optimization_grpc_lro_async_client(): + client = RouteOptimizationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = RouteOptimizationClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = RouteOptimizationClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = RouteOptimizationClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = RouteOptimizationClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = RouteOptimizationClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = RouteOptimizationClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = RouteOptimizationClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = RouteOptimizationClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = RouteOptimizationClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = RouteOptimizationClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = RouteOptimizationClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = RouteOptimizationClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = RouteOptimizationClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = RouteOptimizationClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = RouteOptimizationClient.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.RouteOptimizationTransport, '_prep_wrapped_messages') as prep: + client = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.RouteOptimizationTransport, '_prep_wrapped_messages') as prep: + transport_class = RouteOptimizationClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_get_operation(transport: str = "grpc"): + client = RouteOptimizationClient( + 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 = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(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 response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = RouteOptimizationAsyncClient( + 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 = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(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 response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_get_operation_field_headers(): + client = RouteOptimizationClient( + 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 = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(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=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = RouteOptimizationAsyncClient( + 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 = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(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=locations",) in kw["metadata"] + +def test_get_operation_from_dict(): + client = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = RouteOptimizationAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close_grpc(): + client = RouteOptimizationClient( + 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 = RouteOptimizationAsyncClient( + 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 = RouteOptimizationClient( + 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 = RouteOptimizationClient( + 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", [ + (RouteOptimizationClient, transports.RouteOptimizationGrpcTransport), + (RouteOptimizationAsyncClient, transports.RouteOptimizationGrpcAsyncIOTransport), +]) +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-maps-routing/v2/.coveragerc b/owl-bot-staging/google-maps-routing/v2/.coveragerc new file mode 100644 index 000000000000..d0ce5597b0a9 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/maps/routing/__init__.py + google/maps/routing/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-maps-routing/v2/.flake8 b/owl-bot-staging/google-maps-routing/v2/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/google-maps-routing/v2/MANIFEST.in b/owl-bot-staging/google-maps-routing/v2/MANIFEST.in new file mode 100644 index 000000000000..c5b56c111c00 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/maps/routing *.py +recursive-include google/maps/routing_v2 *.py diff --git a/owl-bot-staging/google-maps-routing/v2/README.rst b/owl-bot-staging/google-maps-routing/v2/README.rst new file mode 100644 index 000000000000..f0002366e552 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Maps Routing 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 Maps Routing 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 diff --git a/owl-bot-staging/google-maps-routing/v2/docs/_static/custom.css b/owl-bot-staging/google-maps-routing/v2/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-maps-routing/v2/docs/conf.py b/owl-bot-staging/google-maps-routing/v2/docs/conf.py new file mode 100644 index 000000000000..4b30f5a14b3e --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-maps-routing 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("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# 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.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +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-maps-routing" +copyright = u"2023, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# 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 = 'en' + +# 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"] + +# 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 Maps Client Libraries for Python", + "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-maps-routing-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-maps-routing.tex", + u"google-maps-routing 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-maps-routing", + u"Google Maps Routing 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-maps-routing", + u"google-maps-routing Documentation", + author, + "google-maps-routing", + "GAPIC library for Google Maps Routing API", + "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": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", 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-maps-routing/v2/docs/index.rst b/owl-bot-staging/google-maps-routing/v2/docs/index.rst new file mode 100644 index 000000000000..3a2d987095fc --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + routing_v2/services_ + routing_v2/types_ diff --git a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst new file mode 100644 index 000000000000..3d52309cddae --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst @@ -0,0 +1,6 @@ +Routes +------------------------ + +.. automodule:: google.maps.routing_v2.services.routes + :members: + :inherited-members: diff --git a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services_.rst b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services_.rst new file mode 100644 index 000000000000..e96568dc434c --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services_.rst @@ -0,0 +1,6 @@ +Services for Google Maps Routing v2 API +======================================= +.. toctree:: + :maxdepth: 2 + + routes diff --git a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types_.rst b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types_.rst new file mode 100644 index 000000000000..176a5a812cf8 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types_.rst @@ -0,0 +1,6 @@ +Types for Google Maps Routing v2 API +==================================== + +.. automodule:: google.maps.routing_v2.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py new file mode 100644 index 000000000000..8d0ab7a57d0d --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py @@ -0,0 +1,115 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.routing import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.maps.routing_v2.services.routes.client import RoutesClient +from google.maps.routing_v2.services.routes.async_client import RoutesAsyncClient + +from google.maps.routing_v2.types.fallback_info import FallbackInfo +from google.maps.routing_v2.types.fallback_info import FallbackReason +from google.maps.routing_v2.types.fallback_info import FallbackRoutingMode +from google.maps.routing_v2.types.geocoding_results import GeocodedWaypoint +from google.maps.routing_v2.types.geocoding_results import GeocodingResults +from google.maps.routing_v2.types.localized_time import LocalizedTime +from google.maps.routing_v2.types.location import Location +from google.maps.routing_v2.types.maneuver import Maneuver +from google.maps.routing_v2.types.navigation_instruction import NavigationInstruction +from google.maps.routing_v2.types.polyline import Polyline +from google.maps.routing_v2.types.polyline import PolylineEncoding +from google.maps.routing_v2.types.polyline import PolylineQuality +from google.maps.routing_v2.types.polyline_details import PolylineDetails +from google.maps.routing_v2.types.route import Route +from google.maps.routing_v2.types.route import RouteLeg +from google.maps.routing_v2.types.route import RouteLegStep +from google.maps.routing_v2.types.route import RouteLegStepTransitDetails +from google.maps.routing_v2.types.route import RouteLegStepTravelAdvisory +from google.maps.routing_v2.types.route import RouteLegTravelAdvisory +from google.maps.routing_v2.types.route import RouteTravelAdvisory +from google.maps.routing_v2.types.route_label import RouteLabel +from google.maps.routing_v2.types.route_modifiers import RouteModifiers +from google.maps.routing_v2.types.route_travel_mode import RouteTravelMode +from google.maps.routing_v2.types.routes_service import ComputeRouteMatrixRequest +from google.maps.routing_v2.types.routes_service import ComputeRoutesRequest +from google.maps.routing_v2.types.routes_service import ComputeRoutesResponse +from google.maps.routing_v2.types.routes_service import RouteMatrixDestination +from google.maps.routing_v2.types.routes_service import RouteMatrixElement +from google.maps.routing_v2.types.routes_service import RouteMatrixOrigin +from google.maps.routing_v2.types.routes_service import RouteMatrixElementCondition +from google.maps.routing_v2.types.routing_preference import RoutingPreference +from google.maps.routing_v2.types.speed_reading_interval import SpeedReadingInterval +from google.maps.routing_v2.types.toll_info import TollInfo +from google.maps.routing_v2.types.toll_passes import TollPass +from google.maps.routing_v2.types.traffic_model import TrafficModel +from google.maps.routing_v2.types.transit import TransitAgency +from google.maps.routing_v2.types.transit import TransitLine +from google.maps.routing_v2.types.transit import TransitStop +from google.maps.routing_v2.types.transit import TransitVehicle +from google.maps.routing_v2.types.transit_preferences import TransitPreferences +from google.maps.routing_v2.types.units import Units +from google.maps.routing_v2.types.vehicle_emission_type import VehicleEmissionType +from google.maps.routing_v2.types.vehicle_info import VehicleInfo +from google.maps.routing_v2.types.waypoint import Waypoint + +__all__ = ('RoutesClient', + 'RoutesAsyncClient', + 'FallbackInfo', + 'FallbackReason', + 'FallbackRoutingMode', + 'GeocodedWaypoint', + 'GeocodingResults', + 'LocalizedTime', + 'Location', + 'Maneuver', + 'NavigationInstruction', + 'Polyline', + 'PolylineEncoding', + 'PolylineQuality', + 'PolylineDetails', + 'Route', + 'RouteLeg', + 'RouteLegStep', + 'RouteLegStepTransitDetails', + 'RouteLegStepTravelAdvisory', + 'RouteLegTravelAdvisory', + 'RouteTravelAdvisory', + 'RouteLabel', + 'RouteModifiers', + 'RouteTravelMode', + 'ComputeRouteMatrixRequest', + 'ComputeRoutesRequest', + 'ComputeRoutesResponse', + 'RouteMatrixDestination', + 'RouteMatrixElement', + 'RouteMatrixOrigin', + 'RouteMatrixElementCondition', + 'RoutingPreference', + 'SpeedReadingInterval', + 'TollInfo', + 'TollPass', + 'TrafficModel', + 'TransitAgency', + 'TransitLine', + 'TransitStop', + 'TransitVehicle', + 'TransitPreferences', + 'Units', + 'VehicleEmissionType', + 'VehicleInfo', + 'Waypoint', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-maps-routing/v2/google/maps/routing/py.typed b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed new file mode 100644 index 000000000000..d62a4b821347 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-maps-routing package uses inline types. diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py new file mode 100644 index 000000000000..05368186e00b --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py @@ -0,0 +1,116 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.routing_v2 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.routes import RoutesClient +from .services.routes import RoutesAsyncClient + +from .types.fallback_info import FallbackInfo +from .types.fallback_info import FallbackReason +from .types.fallback_info import FallbackRoutingMode +from .types.geocoding_results import GeocodedWaypoint +from .types.geocoding_results import GeocodingResults +from .types.localized_time import LocalizedTime +from .types.location import Location +from .types.maneuver import Maneuver +from .types.navigation_instruction import NavigationInstruction +from .types.polyline import Polyline +from .types.polyline import PolylineEncoding +from .types.polyline import PolylineQuality +from .types.polyline_details import PolylineDetails +from .types.route import Route +from .types.route import RouteLeg +from .types.route import RouteLegStep +from .types.route import RouteLegStepTransitDetails +from .types.route import RouteLegStepTravelAdvisory +from .types.route import RouteLegTravelAdvisory +from .types.route import RouteTravelAdvisory +from .types.route_label import RouteLabel +from .types.route_modifiers import RouteModifiers +from .types.route_travel_mode import RouteTravelMode +from .types.routes_service import ComputeRouteMatrixRequest +from .types.routes_service import ComputeRoutesRequest +from .types.routes_service import ComputeRoutesResponse +from .types.routes_service import RouteMatrixDestination +from .types.routes_service import RouteMatrixElement +from .types.routes_service import RouteMatrixOrigin +from .types.routes_service import RouteMatrixElementCondition +from .types.routing_preference import RoutingPreference +from .types.speed_reading_interval import SpeedReadingInterval +from .types.toll_info import TollInfo +from .types.toll_passes import TollPass +from .types.traffic_model import TrafficModel +from .types.transit import TransitAgency +from .types.transit import TransitLine +from .types.transit import TransitStop +from .types.transit import TransitVehicle +from .types.transit_preferences import TransitPreferences +from .types.units import Units +from .types.vehicle_emission_type import VehicleEmissionType +from .types.vehicle_info import VehicleInfo +from .types.waypoint import Waypoint + +__all__ = ( + 'RoutesAsyncClient', +'ComputeRouteMatrixRequest', +'ComputeRoutesRequest', +'ComputeRoutesResponse', +'FallbackInfo', +'FallbackReason', +'FallbackRoutingMode', +'GeocodedWaypoint', +'GeocodingResults', +'LocalizedTime', +'Location', +'Maneuver', +'NavigationInstruction', +'Polyline', +'PolylineDetails', +'PolylineEncoding', +'PolylineQuality', +'Route', +'RouteLabel', +'RouteLeg', +'RouteLegStep', +'RouteLegStepTransitDetails', +'RouteLegStepTravelAdvisory', +'RouteLegTravelAdvisory', +'RouteMatrixDestination', +'RouteMatrixElement', +'RouteMatrixElementCondition', +'RouteMatrixOrigin', +'RouteModifiers', +'RouteTravelAdvisory', +'RouteTravelMode', +'RoutesClient', +'RoutingPreference', +'SpeedReadingInterval', +'TollInfo', +'TollPass', +'TrafficModel', +'TransitAgency', +'TransitLine', +'TransitPreferences', +'TransitStop', +'TransitVehicle', +'Units', +'VehicleEmissionType', +'VehicleInfo', +'Waypoint', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json new file mode 100644 index 000000000000..8382cea1d39a --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json @@ -0,0 +1,58 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.maps.routing_v2", + "protoPackage": "google.maps.routing.v2", + "schema": "1.0", + "services": { + "Routes": { + "clients": { + "grpc": { + "libraryClient": "RoutesClient", + "rpcs": { + "ComputeRouteMatrix": { + "methods": [ + "compute_route_matrix" + ] + }, + "ComputeRoutes": { + "methods": [ + "compute_routes" + ] + } + } + }, + "grpc-async": { + "libraryClient": "RoutesAsyncClient", + "rpcs": { + "ComputeRouteMatrix": { + "methods": [ + "compute_route_matrix" + ] + }, + "ComputeRoutes": { + "methods": [ + "compute_routes" + ] + } + } + }, + "rest": { + "libraryClient": "RoutesClient", + "rpcs": { + "ComputeRouteMatrix": { + "methods": [ + "compute_route_matrix" + ] + }, + "ComputeRoutes": { + "methods": [ + "compute_routes" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-maps-routing/v2/google/maps/routing_v2/py.typed b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed new file mode 100644 index 000000000000..d62a4b821347 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-maps-routing package uses inline types. diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py new file mode 100644 index 000000000000..1d5f9c21bfea --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 RoutesClient +from .async_client import RoutesAsyncClient + +__all__ = ( + 'RoutesClient', + 'RoutesAsyncClient', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py new file mode 100644 index 000000000000..5201b0eb6994 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py @@ -0,0 +1,486 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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, AsyncIterable, Awaitable, Sequence, Tuple, Type, Union + +from google.maps.routing_v2 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 + + +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.maps.routing_v2.types import fallback_info +from google.maps.routing_v2.types import geocoding_results +from google.maps.routing_v2.types import route +from google.maps.routing_v2.types import routes_service +from google.protobuf import duration_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from .transports.base import RoutesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import RoutesGrpcAsyncIOTransport +from .client import RoutesClient + +try: + from google.api_core import client_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 RoutesAsyncClient: + """The Routes API.""" + + _client: RoutesClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = RoutesClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = RoutesClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = RoutesClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = RoutesClient._DEFAULT_UNIVERSE + + common_billing_account_path = staticmethod(RoutesClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(RoutesClient.parse_common_billing_account_path) + common_folder_path = staticmethod(RoutesClient.common_folder_path) + parse_common_folder_path = staticmethod(RoutesClient.parse_common_folder_path) + common_organization_path = staticmethod(RoutesClient.common_organization_path) + parse_common_organization_path = staticmethod(RoutesClient.parse_common_organization_path) + common_project_path = staticmethod(RoutesClient.common_project_path) + parse_common_project_path = staticmethod(RoutesClient.parse_common_project_path) + common_location_path = staticmethod(RoutesClient.common_location_path) + parse_common_location_path = staticmethod(RoutesClient.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: + RoutesAsyncClient: The constructed client. + """ + return RoutesClient.from_service_account_info.__func__(RoutesAsyncClient, 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: + RoutesAsyncClient: The constructed client. + """ + return RoutesClient.from_service_account_file.__func__(RoutesAsyncClient, 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 RoutesClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> RoutesTransport: + """Returns the transport used by the client instance. + + Returns: + RoutesTransport: 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 = RoutesClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, RoutesTransport, Callable[..., RoutesTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the routes 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,RoutesTransport,Callable[..., RoutesTransport]]]): + 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 RoutesTransport 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 = RoutesClient( + 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.maps.routing_v2.RoutesAsyncClient`.", + extra = { + "serviceName": "google.maps.routing.v2.Routes", + "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.maps.routing.v2.Routes", + "credentialsType": None, + } + ) + + async def compute_routes(self, + request: Optional[Union[routes_service.ComputeRoutesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> routes_service.ComputeRoutesResponse: + r"""Returns the primary route along with optional alternate routes, + given a set of terminal and intermediate waypoints. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using URL parameter ``$fields`` or ``fields``, or by using an + HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL + parameters and + headers `__). + The value is a comma separated list of field paths. See detailed + documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of Route-level duration, distance, and polyline + (an example production setup): + ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` + + Google discourage the use of the wildcard (``*``) response field + mask, or specifying the field mask at the top level + (``routes``), because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import routing_v2 + + async def sample_compute_routes(): + # Create a client + client = routing_v2.RoutesAsyncClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRoutesRequest( + ) + + # Make the request + response = await client.compute_routes(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.routing_v2.types.ComputeRoutesRequest, dict]]): + The request object. ComputeRoutes request message. + 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.maps.routing_v2.types.ComputeRoutesResponse: + ComputeRoutes the response message. + """ + # 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, routes_service.ComputeRoutesRequest): + request = routes_service.ComputeRoutesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.compute_routes] + + # 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 + + def compute_route_matrix(self, + request: Optional[Union[routes_service.ComputeRouteMatrixRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> Awaitable[AsyncIterable[routes_service.RouteMatrixElement]]: + r"""Takes in a list of origins and destinations and returns a stream + containing route information for each combination of origin and + destination. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using the URL parameter ``$fields`` or ``fields``, or by using + the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available + URL parameters and + headers `__). + The value is a comma separated list of field paths. See this + detailed documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of route durations, distances, element status, + condition, and element indices (an example production setup): + ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` + + It is critical that you include ``status`` in your field mask as + otherwise all messages will appear to be OK. Google discourages + the use of the wildcard (``*``) response field mask, because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import routing_v2 + + async def sample_compute_route_matrix(): + # Create a client + client = routing_v2.RoutesAsyncClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRouteMatrixRequest( + ) + + # Make the request + stream = await client.compute_route_matrix(request=request) + + # Handle the response + async for response in stream: + print(response) + + Args: + request (Optional[Union[google.maps.routing_v2.types.ComputeRouteMatrixRequest, dict]]): + The request object. ComputeRouteMatrix request message + 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: + AsyncIterable[google.maps.routing_v2.types.RouteMatrixElement]: + Contains route information computed + for an origin/destination pair in the + ComputeRouteMatrix API. This proto can + be streamed to the client. + + """ + # 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, routes_service.ComputeRouteMatrixRequest): + request = routes_service.ComputeRouteMatrixRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.compute_route_matrix] + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "RoutesAsyncClient": + 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__) + + +__all__ = ( + "RoutesAsyncClient", +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py new file mode 100644 index 000000000000..e972dc2a27fc --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py @@ -0,0 +1,813 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +import logging as std_logging +import os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Iterable, Sequence, Tuple, Type, Union, cast +import warnings + +from google.maps.routing_v2 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 + +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.maps.routing_v2.types import fallback_info +from google.maps.routing_v2.types import geocoding_results +from google.maps.routing_v2.types import route +from google.maps.routing_v2.types import routes_service +from google.protobuf import duration_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from .transports.base import RoutesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import RoutesGrpcTransport +from .transports.grpc_asyncio import RoutesGrpcAsyncIOTransport +from .transports.rest import RoutesRestTransport + + +class RoutesClientMeta(type): + """Metaclass for the Routes 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[RoutesTransport]] + _transport_registry["grpc"] = RoutesGrpcTransport + _transport_registry["grpc_asyncio"] = RoutesGrpcAsyncIOTransport + _transport_registry["rest"] = RoutesRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[RoutesTransport]: + """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 RoutesClient(metaclass=RoutesClientMeta): + """The Routes 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 = "routes.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "routes.{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: + RoutesClient: 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: + RoutesClient: 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) -> RoutesTransport: + """Returns the transport used by the client instance. + + Returns: + RoutesTransport: The transport used by the client + instance. + """ + return self._transport + + @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 = RoutesClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = RoutesClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = RoutesClient._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 = RoutesClient._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 + + @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, RoutesTransport, Callable[..., RoutesTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the routes 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,RoutesTransport,Callable[..., RoutesTransport]]]): + 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 RoutesTransport 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 = RoutesClient._read_environment_variables() + self._client_cert_source = RoutesClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = RoutesClient._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, RoutesTransport) + if transport_provided: + # transport is a RoutesTransport 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(RoutesTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + RoutesClient._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[RoutesTransport], Callable[..., RoutesTransport]] = ( + RoutesClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., RoutesTransport], 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.maps.routing_v2.RoutesClient`.", + extra = { + "serviceName": "google.maps.routing.v2.Routes", + "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.maps.routing.v2.Routes", + "credentialsType": None, + } + ) + + def compute_routes(self, + request: Optional[Union[routes_service.ComputeRoutesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> routes_service.ComputeRoutesResponse: + r"""Returns the primary route along with optional alternate routes, + given a set of terminal and intermediate waypoints. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using URL parameter ``$fields`` or ``fields``, or by using an + HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL + parameters and + headers `__). + The value is a comma separated list of field paths. See detailed + documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of Route-level duration, distance, and polyline + (an example production setup): + ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` + + Google discourage the use of the wildcard (``*``) response field + mask, or specifying the field mask at the top level + (``routes``), because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import routing_v2 + + def sample_compute_routes(): + # Create a client + client = routing_v2.RoutesClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRoutesRequest( + ) + + # Make the request + response = client.compute_routes(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.routing_v2.types.ComputeRoutesRequest, dict]): + The request object. ComputeRoutes request message. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.maps.routing_v2.types.ComputeRoutesResponse: + ComputeRoutes the response message. + """ + # 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, routes_service.ComputeRoutesRequest): + request = routes_service.ComputeRoutesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.compute_routes] + + # 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 compute_route_matrix(self, + request: Optional[Union[routes_service.ComputeRouteMatrixRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> Iterable[routes_service.RouteMatrixElement]: + r"""Takes in a list of origins and destinations and returns a stream + containing route information for each combination of origin and + destination. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using the URL parameter ``$fields`` or ``fields``, or by using + the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available + URL parameters and + headers `__). + The value is a comma separated list of field paths. See this + detailed documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of route durations, distances, element status, + condition, and element indices (an example production setup): + ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` + + It is critical that you include ``status`` in your field mask as + otherwise all messages will appear to be OK. Google discourages + the use of the wildcard (``*``) response field mask, because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import routing_v2 + + def sample_compute_route_matrix(): + # Create a client + client = routing_v2.RoutesClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRouteMatrixRequest( + ) + + # Make the request + stream = client.compute_route_matrix(request=request) + + # Handle the response + for response in stream: + print(response) + + Args: + request (Union[google.maps.routing_v2.types.ComputeRouteMatrixRequest, dict]): + The request object. ComputeRouteMatrix request message + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + Iterable[google.maps.routing_v2.types.RouteMatrixElement]: + Contains route information computed + for an origin/destination pair in the + ComputeRouteMatrix API. This proto can + be streamed to the client. + + """ + # 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, routes_service.ComputeRouteMatrixRequest): + request = routes_service.ComputeRouteMatrixRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.compute_route_matrix] + + # 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) -> "RoutesClient": + 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__) + + +__all__ = ( + "RoutesClient", +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/README.rst b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/README.rst new file mode 100644 index 000000000000..ece3f327f1db --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`RoutesTransport` is the ABC for all transports. +- public child `RoutesGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `RoutesGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseRoutesRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `RoutesRestTransport` 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-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py new file mode 100644 index 000000000000..cac74dd752a0 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 RoutesTransport +from .grpc import RoutesGrpcTransport +from .grpc_asyncio import RoutesGrpcAsyncIOTransport +from .rest import RoutesRestTransport +from .rest import RoutesRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[RoutesTransport]] +_transport_registry['grpc'] = RoutesGrpcTransport +_transport_registry['grpc_asyncio'] = RoutesGrpcAsyncIOTransport +_transport_registry['rest'] = RoutesRestTransport + +__all__ = ( + 'RoutesTransport', + 'RoutesGrpcTransport', + 'RoutesGrpcAsyncIOTransport', + 'RoutesRestTransport', + 'RoutesRestInterceptor', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py new file mode 100644 index 000000000000..ecdfa6e5fcc0 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py @@ -0,0 +1,167 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.routing_v2 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 + +from google.maps.routing_v2.types import routes_service + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class RoutesTransport(abc.ABC): + """Abstract transport class for Routes.""" + + AUTH_SCOPES = ( + ) + + DEFAULT_HOST: str = 'routes.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: 'routes.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to 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.compute_routes: gapic_v1.method.wrap_method( + self.compute_routes, + default_timeout=None, + client_info=client_info, + ), + self.compute_route_matrix: gapic_v1.method.wrap_method( + self.compute_route_matrix, + 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 compute_routes(self) -> Callable[ + [routes_service.ComputeRoutesRequest], + Union[ + routes_service.ComputeRoutesResponse, + Awaitable[routes_service.ComputeRoutesResponse] + ]]: + raise NotImplementedError() + + @property + def compute_route_matrix(self) -> Callable[ + [routes_service.ComputeRouteMatrixRequest], + Union[ + routes_service.RouteMatrixElement, + Awaitable[routes_service.RouteMatrixElement] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'RoutesTransport', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py new file mode 100644 index 000000000000..8b2b7b6398bd --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py @@ -0,0 +1,446 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.routing_v2.types import routes_service +from .base import RoutesTransport, 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.maps.routing.v2.Routes", + "rpcName": 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.maps.routing.v2.Routes", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class RoutesGrpcTransport(RoutesTransport): + """gRPC backend transport for Routes. + + The Routes 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 = 'routes.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: 'routes.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to 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 = 'routes.googleapis.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 compute_routes(self) -> Callable[ + [routes_service.ComputeRoutesRequest], + routes_service.ComputeRoutesResponse]: + r"""Return a callable for the compute routes method over gRPC. + + Returns the primary route along with optional alternate routes, + given a set of terminal and intermediate waypoints. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using URL parameter ``$fields`` or ``fields``, or by using an + HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL + parameters and + headers `__). + The value is a comma separated list of field paths. See detailed + documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of Route-level duration, distance, and polyline + (an example production setup): + ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` + + Google discourage the use of the wildcard (``*``) response field + mask, or specifying the field mask at the top level + (``routes``), because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + Returns: + Callable[[~.ComputeRoutesRequest], + ~.ComputeRoutesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'compute_routes' not in self._stubs: + self._stubs['compute_routes'] = self._logged_channel.unary_unary( + '/google.maps.routing.v2.Routes/ComputeRoutes', + request_serializer=routes_service.ComputeRoutesRequest.serialize, + response_deserializer=routes_service.ComputeRoutesResponse.deserialize, + ) + return self._stubs['compute_routes'] + + @property + def compute_route_matrix(self) -> Callable[ + [routes_service.ComputeRouteMatrixRequest], + routes_service.RouteMatrixElement]: + r"""Return a callable for the compute route matrix method over gRPC. + + Takes in a list of origins and destinations and returns a stream + containing route information for each combination of origin and + destination. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using the URL parameter ``$fields`` or ``fields``, or by using + the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available + URL parameters and + headers `__). + The value is a comma separated list of field paths. See this + detailed documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of route durations, distances, element status, + condition, and element indices (an example production setup): + ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` + + It is critical that you include ``status`` in your field mask as + otherwise all messages will appear to be OK. Google discourages + the use of the wildcard (``*``) response field mask, because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + Returns: + Callable[[~.ComputeRouteMatrixRequest], + ~.RouteMatrixElement]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'compute_route_matrix' not in self._stubs: + self._stubs['compute_route_matrix'] = self._logged_channel.unary_stream( + '/google.maps.routing.v2.Routes/ComputeRouteMatrix', + request_serializer=routes_service.ComputeRouteMatrixRequest.serialize, + response_deserializer=routes_service.RouteMatrixElement.deserialize, + ) + return self._stubs['compute_route_matrix'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'RoutesGrpcTransport', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py new file mode 100644 index 000000000000..6f00e3511763 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py @@ -0,0 +1,471 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.routing_v2.types import routes_service +from .base import RoutesTransport, DEFAULT_CLIENT_INFO +from .grpc import RoutesGrpcTransport + +try: + from google.api_core import client_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.maps.routing.v2.Routes", + "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.maps.routing.v2.Routes", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class RoutesGrpcAsyncIOTransport(RoutesTransport): + """gRPC AsyncIO backend transport for Routes. + + The Routes 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 = 'routes.googleapis.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 = 'routes.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: 'routes.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to 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 compute_routes(self) -> Callable[ + [routes_service.ComputeRoutesRequest], + Awaitable[routes_service.ComputeRoutesResponse]]: + r"""Return a callable for the compute routes method over gRPC. + + Returns the primary route along with optional alternate routes, + given a set of terminal and intermediate waypoints. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using URL parameter ``$fields`` or ``fields``, or by using an + HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL + parameters and + headers `__). + The value is a comma separated list of field paths. See detailed + documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of Route-level duration, distance, and polyline + (an example production setup): + ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` + + Google discourage the use of the wildcard (``*``) response field + mask, or specifying the field mask at the top level + (``routes``), because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + Returns: + Callable[[~.ComputeRoutesRequest], + Awaitable[~.ComputeRoutesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'compute_routes' not in self._stubs: + self._stubs['compute_routes'] = self._logged_channel.unary_unary( + '/google.maps.routing.v2.Routes/ComputeRoutes', + request_serializer=routes_service.ComputeRoutesRequest.serialize, + response_deserializer=routes_service.ComputeRoutesResponse.deserialize, + ) + return self._stubs['compute_routes'] + + @property + def compute_route_matrix(self) -> Callable[ + [routes_service.ComputeRouteMatrixRequest], + Awaitable[routes_service.RouteMatrixElement]]: + r"""Return a callable for the compute route matrix method over gRPC. + + Takes in a list of origins and destinations and returns a stream + containing route information for each combination of origin and + destination. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using the URL parameter ``$fields`` or ``fields``, or by using + the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available + URL parameters and + headers `__). + The value is a comma separated list of field paths. See this + detailed documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of route durations, distances, element status, + condition, and element indices (an example production setup): + ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` + + It is critical that you include ``status`` in your field mask as + otherwise all messages will appear to be OK. Google discourages + the use of the wildcard (``*``) response field mask, because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + Returns: + Callable[[~.ComputeRouteMatrixRequest], + Awaitable[~.RouteMatrixElement]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'compute_route_matrix' not in self._stubs: + self._stubs['compute_route_matrix'] = self._logged_channel.unary_stream( + '/google.maps.routing.v2.Routes/ComputeRouteMatrix', + request_serializer=routes_service.ComputeRouteMatrixRequest.serialize, + response_deserializer=routes_service.RouteMatrixElement.deserialize, + ) + return self._stubs['compute_route_matrix'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.compute_routes: self._wrap_method( + self.compute_routes, + default_timeout=None, + client_info=client_info, + ), + self.compute_route_matrix: self._wrap_method( + self.compute_route_matrix, + 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__ = ( + 'RoutesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py new file mode 100644 index 000000000000..7de15a3c0755 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py @@ -0,0 +1,465 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +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.maps.routing_v2.types import routes_service + + +from .rest_base import _BaseRoutesRestTransport +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}", +) + + +class RoutesRestInterceptor: + """Interceptor for Routes. + + 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 RoutesRestTransport. + + .. code-block:: python + class MyCustomRoutesInterceptor(RoutesRestInterceptor): + def pre_compute_route_matrix(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_compute_route_matrix(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_compute_routes(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_compute_routes(self, response): + logging.log(f"Received response: {response}") + return response + + transport = RoutesRestTransport(interceptor=MyCustomRoutesInterceptor()) + client = RoutesClient(transport=transport) + + + """ + def pre_compute_route_matrix(self, request: routes_service.ComputeRouteMatrixRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[routes_service.ComputeRouteMatrixRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for compute_route_matrix + + Override in a subclass to manipulate the request or metadata + before they are sent to the Routes server. + """ + return request, metadata + + def post_compute_route_matrix(self, response: rest_streaming.ResponseIterator) -> rest_streaming.ResponseIterator: + """Post-rpc interceptor for compute_route_matrix + + Override in a subclass to manipulate the response + after it is returned by the Routes server but before + it is returned to user code. + """ + return response + + def pre_compute_routes(self, request: routes_service.ComputeRoutesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[routes_service.ComputeRoutesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for compute_routes + + Override in a subclass to manipulate the request or metadata + before they are sent to the Routes server. + """ + return request, metadata + + def post_compute_routes(self, response: routes_service.ComputeRoutesResponse) -> routes_service.ComputeRoutesResponse: + """Post-rpc interceptor for compute_routes + + Override in a subclass to manipulate the response + after it is returned by the Routes server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class RoutesRestStub: + _session: AuthorizedSession + _host: str + _interceptor: RoutesRestInterceptor + + +class RoutesRestTransport(_BaseRoutesRestTransport): + """REST backend synchronous transport for Routes. + + The Routes 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 = 'routes.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[RoutesRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'routes.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to 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 RoutesRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _ComputeRouteMatrix(_BaseRoutesRestTransport._BaseComputeRouteMatrix, RoutesRestStub): + def __hash__(self): + return hash("RoutesRestTransport.ComputeRouteMatrix") + + @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, + stream=True, + ) + return response + + def __call__(self, + request: routes_service.ComputeRouteMatrixRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> rest_streaming.ResponseIterator: + r"""Call the compute route matrix method over HTTP. + + Args: + request (~.routes_service.ComputeRouteMatrixRequest): + The request object. ComputeRouteMatrix request message + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.routes_service.RouteMatrixElement: + Contains route information computed + for an origin/destination pair in the + ComputeRouteMatrix API. This proto can + be streamed to the client. + + """ + + http_options = _BaseRoutesRestTransport._BaseComputeRouteMatrix._get_http_options() + + request, metadata = self._interceptor.pre_compute_route_matrix(request, metadata) + transcoded_request = _BaseRoutesRestTransport._BaseComputeRouteMatrix._get_transcoded_request(http_options, request) + + body = _BaseRoutesRestTransport._BaseComputeRouteMatrix._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseRoutesRestTransport._BaseComputeRouteMatrix._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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.maps.routing_v2.RoutesClient.ComputeRouteMatrix", + extra = { + "serviceName": "google.maps.routing.v2.Routes", + "rpcName": "ComputeRouteMatrix", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RoutesRestTransport._ComputeRouteMatrix._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 = rest_streaming.ResponseIterator(response, routes_service.RouteMatrixElement) + + resp = self._interceptor.post_compute_route_matrix(resp) + return resp + + class _ComputeRoutes(_BaseRoutesRestTransport._BaseComputeRoutes, RoutesRestStub): + def __hash__(self): + return hash("RoutesRestTransport.ComputeRoutes") + + @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: routes_service.ComputeRoutesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> routes_service.ComputeRoutesResponse: + r"""Call the compute routes method over HTTP. + + Args: + request (~.routes_service.ComputeRoutesRequest): + The request object. ComputeRoutes request message. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.routes_service.ComputeRoutesResponse: + ComputeRoutes the response message. + """ + + http_options = _BaseRoutesRestTransport._BaseComputeRoutes._get_http_options() + + request, metadata = self._interceptor.pre_compute_routes(request, metadata) + transcoded_request = _BaseRoutesRestTransport._BaseComputeRoutes._get_transcoded_request(http_options, request) + + body = _BaseRoutesRestTransport._BaseComputeRoutes._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseRoutesRestTransport._BaseComputeRoutes._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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.maps.routing_v2.RoutesClient.ComputeRoutes", + extra = { + "serviceName": "google.maps.routing.v2.Routes", + "rpcName": "ComputeRoutes", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RoutesRestTransport._ComputeRoutes._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 = routes_service.ComputeRoutesResponse() + pb_resp = routes_service.ComputeRoutesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_compute_routes(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = routes_service.ComputeRoutesResponse.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.maps.routing_v2.RoutesClient.compute_routes", + extra = { + "serviceName": "google.maps.routing.v2.Routes", + "rpcName": "ComputeRoutes", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def compute_route_matrix(self) -> Callable[ + [routes_service.ComputeRouteMatrixRequest], + routes_service.RouteMatrixElement]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ComputeRouteMatrix(self._session, self._host, self._interceptor) # type: ignore + + @property + def compute_routes(self) -> Callable[ + [routes_service.ComputeRoutesRequest], + routes_service.ComputeRoutesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ComputeRoutes(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'RoutesRestTransport', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest_base.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest_base.py new file mode 100644 index 000000000000..89bf86170eeb --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest_base.py @@ -0,0 +1,185 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 RoutesTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.maps.routing_v2.types import routes_service + + +class _BaseRoutesRestTransport(RoutesTransport): + """Base REST backend transport for Routes. + + 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 = 'routes.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: 'routes.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 _BaseComputeRouteMatrix: + 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': '/distanceMatrix/v2:computeRouteMatrix', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = routes_service.ComputeRouteMatrixRequest.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(_BaseRoutesRestTransport._BaseComputeRouteMatrix._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseComputeRoutes: + 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': '/directions/v2:computeRoutes', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = routes_service.ComputeRoutesRequest.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(_BaseRoutesRestTransport._BaseComputeRoutes._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseRoutesRestTransport', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py new file mode 100644 index 000000000000..e383324c9fc2 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py @@ -0,0 +1,154 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .fallback_info import ( + FallbackInfo, + FallbackReason, + FallbackRoutingMode, +) +from .geocoding_results import ( + GeocodedWaypoint, + GeocodingResults, +) +from .localized_time import ( + LocalizedTime, +) +from .location import ( + Location, +) +from .maneuver import ( + Maneuver, +) +from .navigation_instruction import ( + NavigationInstruction, +) +from .polyline import ( + Polyline, + PolylineEncoding, + PolylineQuality, +) +from .polyline_details import ( + PolylineDetails, +) +from .route import ( + Route, + RouteLeg, + RouteLegStep, + RouteLegStepTransitDetails, + RouteLegStepTravelAdvisory, + RouteLegTravelAdvisory, + RouteTravelAdvisory, +) +from .route_label import ( + RouteLabel, +) +from .route_modifiers import ( + RouteModifiers, +) +from .route_travel_mode import ( + RouteTravelMode, +) +from .routes_service import ( + ComputeRouteMatrixRequest, + ComputeRoutesRequest, + ComputeRoutesResponse, + RouteMatrixDestination, + RouteMatrixElement, + RouteMatrixOrigin, + RouteMatrixElementCondition, +) +from .routing_preference import ( + RoutingPreference, +) +from .speed_reading_interval import ( + SpeedReadingInterval, +) +from .toll_info import ( + TollInfo, +) +from .toll_passes import ( + TollPass, +) +from .traffic_model import ( + TrafficModel, +) +from .transit import ( + TransitAgency, + TransitLine, + TransitStop, + TransitVehicle, +) +from .transit_preferences import ( + TransitPreferences, +) +from .units import ( + Units, +) +from .vehicle_emission_type import ( + VehicleEmissionType, +) +from .vehicle_info import ( + VehicleInfo, +) +from .waypoint import ( + Waypoint, +) + +__all__ = ( + 'FallbackInfo', + 'FallbackReason', + 'FallbackRoutingMode', + 'GeocodedWaypoint', + 'GeocodingResults', + 'LocalizedTime', + 'Location', + 'Maneuver', + 'NavigationInstruction', + 'Polyline', + 'PolylineEncoding', + 'PolylineQuality', + 'PolylineDetails', + 'Route', + 'RouteLeg', + 'RouteLegStep', + 'RouteLegStepTransitDetails', + 'RouteLegStepTravelAdvisory', + 'RouteLegTravelAdvisory', + 'RouteTravelAdvisory', + 'RouteLabel', + 'RouteModifiers', + 'RouteTravelMode', + 'ComputeRouteMatrixRequest', + 'ComputeRoutesRequest', + 'ComputeRoutesResponse', + 'RouteMatrixDestination', + 'RouteMatrixElement', + 'RouteMatrixOrigin', + 'RouteMatrixElementCondition', + 'RoutingPreference', + 'SpeedReadingInterval', + 'TollInfo', + 'TollPass', + 'TrafficModel', + 'TransitAgency', + 'TransitLine', + 'TransitStop', + 'TransitVehicle', + 'TransitPreferences', + 'Units', + 'VehicleEmissionType', + 'VehicleInfo', + 'Waypoint', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py new file mode 100644 index 000000000000..e9c371f86902 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py @@ -0,0 +1,105 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.routing.v2', + manifest={ + 'FallbackReason', + 'FallbackRoutingMode', + 'FallbackInfo', + }, +) + + +class FallbackReason(proto.Enum): + r"""Reasons for using fallback response. + + Values: + FALLBACK_REASON_UNSPECIFIED (0): + No fallback reason specified. + SERVER_ERROR (1): + A server error happened while calculating + routes with your preferred routing mode, but we + were able to return a result calculated by an + alternative mode. + LATENCY_EXCEEDED (2): + We were not able to finish the calculation + with your preferred routing mode on time, but we + were able to return a result calculated by an + alternative mode. + """ + FALLBACK_REASON_UNSPECIFIED = 0 + SERVER_ERROR = 1 + LATENCY_EXCEEDED = 2 + + +class FallbackRoutingMode(proto.Enum): + r"""Actual routing mode used for returned fallback response. + + Values: + FALLBACK_ROUTING_MODE_UNSPECIFIED (0): + Not used. + FALLBACK_TRAFFIC_UNAWARE (1): + Indicates the ``TRAFFIC_UNAWARE`` + [``RoutingPreference``][google.maps.routing.v2.RoutingPreference] + was used to compute the response. + FALLBACK_TRAFFIC_AWARE (2): + Indicates the ``TRAFFIC_AWARE`` + [``RoutingPreference``][google.maps.routing.v2.RoutingPreference] + was used to compute the response. + """ + FALLBACK_ROUTING_MODE_UNSPECIFIED = 0 + FALLBACK_TRAFFIC_UNAWARE = 1 + FALLBACK_TRAFFIC_AWARE = 2 + + +class FallbackInfo(proto.Message): + r"""Information related to how and why a fallback result was + used. If this field is set, then it means the server used a + different routing mode from your preferred mode as fallback. + + Attributes: + routing_mode (google.maps.routing_v2.types.FallbackRoutingMode): + Routing mode used for the response. If + fallback was triggered, the mode may be + different from routing preference set in the + original client request. + reason (google.maps.routing_v2.types.FallbackReason): + The reason why fallback response was used + instead of the original response. This field is + only populated when the fallback mode is + triggered and the fallback response is returned. + """ + + routing_mode: 'FallbackRoutingMode' = proto.Field( + proto.ENUM, + number=1, + enum='FallbackRoutingMode', + ) + reason: 'FallbackReason' = proto.Field( + proto.ENUM, + number=2, + enum='FallbackReason', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py new file mode 100644 index 000000000000..e7b5ac69343c --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py @@ -0,0 +1,127 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'GeocodingResults', + 'GeocodedWaypoint', + }, +) + + +class GeocodingResults(proto.Message): + r"""Contains + [``GeocodedWaypoints``][google.maps.routing.v2.GeocodedWaypoint] for + origin, destination and intermediate waypoints. Only populated for + address waypoints. + + Attributes: + origin (google.maps.routing_v2.types.GeocodedWaypoint): + Origin geocoded waypoint. + destination (google.maps.routing_v2.types.GeocodedWaypoint): + Destination geocoded waypoint. + intermediates (MutableSequence[google.maps.routing_v2.types.GeocodedWaypoint]): + A list of intermediate geocoded waypoints + each containing an index field that corresponds + to the zero-based position of the waypoint in + the order they were specified in the request. + """ + + origin: 'GeocodedWaypoint' = proto.Field( + proto.MESSAGE, + number=1, + message='GeocodedWaypoint', + ) + destination: 'GeocodedWaypoint' = proto.Field( + proto.MESSAGE, + number=2, + message='GeocodedWaypoint', + ) + intermediates: MutableSequence['GeocodedWaypoint'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='GeocodedWaypoint', + ) + + +class GeocodedWaypoint(proto.Message): + r"""Details about the locations used as waypoints. Only populated + for address waypoints. Includes details about the geocoding + results for the purposes of determining what the address was + geocoded to. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + geocoder_status (google.rpc.status_pb2.Status): + Indicates the status code resulting from the + geocoding operation. + intermediate_waypoint_request_index (int): + The index of the corresponding intermediate + waypoint in the request. Only populated if the + corresponding waypoint is an intermediate + waypoint. + + This field is a member of `oneof`_ ``_intermediate_waypoint_request_index``. + type_ (MutableSequence[str]): + The type(s) of the result, in the form of zero or more type + tags. Supported types: `Address types and address component + types `__. + partial_match (bool): + Indicates that the geocoder did not return an + exact match for the original request, though it + was able to match part of the requested address. + You may wish to examine the original request for + misspellings and/or an incomplete address. + place_id (str): + The place ID for this result. + """ + + geocoder_status: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + intermediate_waypoint_request_index: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + type_: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + partial_match: bool = proto.Field( + proto.BOOL, + number=4, + ) + place_id: str = proto.Field( + proto.STRING, + number=5, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/localized_time.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/localized_time.py new file mode 100644 index 000000000000..cd33d5012b85 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/localized_time.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 localized_text_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'LocalizedTime', + }, +) + + +class LocalizedTime(proto.Message): + r"""Localized description of time. + + Attributes: + time (google.type.localized_text_pb2.LocalizedText): + The time specified as a string in a given + time zone. + time_zone (str): + Contains the time zone. The value is the name of the time + zone as defined in the `IANA Time Zone + Database `__, e.g. + "America/New_York". + """ + + time: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=1, + message=localized_text_pb2.LocalizedText, + ) + time_zone: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py new file mode 100644 index 000000000000..895301cea20d --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 wrappers_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'Location', + }, +) + + +class Location(proto.Message): + r"""Encapsulates a location (a geographic point, and an optional + heading). + + Attributes: + lat_lng (google.type.latlng_pb2.LatLng): + The waypoint's geographic coordinates. + heading (google.protobuf.wrappers_pb2.Int32Value): + The compass heading associated with the direction of the + flow of traffic. This value specifies the side of the road + for pickup and drop-off. Heading values can be from 0 to + 360, where 0 specifies a heading of due North, 90 specifies + a heading of due East, and so on. You can use this field + only for ``DRIVE`` and ``TWO_WHEELER`` + [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode]. + """ + + lat_lng: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=1, + message=latlng_pb2.LatLng, + ) + heading: wrappers_pb2.Int32Value = proto.Field( + proto.MESSAGE, + number=2, + message=wrappers_pb2.Int32Value, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py new file mode 100644 index 000000000000..e8275813708a --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py @@ -0,0 +1,103 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.routing.v2', + manifest={ + 'Maneuver', + }, +) + + +class Maneuver(proto.Enum): + r"""A set of values that specify the navigation action to take + for the current step (for example, turn left, merge, or + straight). + + Values: + MANEUVER_UNSPECIFIED (0): + Not used. + TURN_SLIGHT_LEFT (1): + Turn slightly to the left. + TURN_SHARP_LEFT (2): + Turn sharply to the left. + UTURN_LEFT (3): + Make a left u-turn. + TURN_LEFT (4): + Turn left. + TURN_SLIGHT_RIGHT (5): + Turn slightly to the right. + TURN_SHARP_RIGHT (6): + Turn sharply to the right. + UTURN_RIGHT (7): + Make a right u-turn. + TURN_RIGHT (8): + Turn right. + STRAIGHT (9): + Go straight. + RAMP_LEFT (10): + Take the left ramp. + RAMP_RIGHT (11): + Take the right ramp. + MERGE (12): + Merge into traffic. + FORK_LEFT (13): + Take the left fork. + FORK_RIGHT (14): + Take the right fork. + FERRY (15): + Take the ferry. + FERRY_TRAIN (16): + Take the train leading onto the ferry. + ROUNDABOUT_LEFT (17): + Turn left at the roundabout. + ROUNDABOUT_RIGHT (18): + Turn right at the roundabout. + DEPART (19): + Initial maneuver. + NAME_CHANGE (20): + Used to indicate a street name change. + """ + MANEUVER_UNSPECIFIED = 0 + TURN_SLIGHT_LEFT = 1 + TURN_SHARP_LEFT = 2 + UTURN_LEFT = 3 + TURN_LEFT = 4 + TURN_SLIGHT_RIGHT = 5 + TURN_SHARP_RIGHT = 6 + UTURN_RIGHT = 7 + TURN_RIGHT = 8 + STRAIGHT = 9 + RAMP_LEFT = 10 + RAMP_RIGHT = 11 + MERGE = 12 + FORK_LEFT = 13 + FORK_RIGHT = 14 + FERRY = 15 + FERRY_TRAIN = 16 + ROUNDABOUT_LEFT = 17 + ROUNDABOUT_RIGHT = 18 + DEPART = 19 + NAME_CHANGE = 20 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py new file mode 100644 index 000000000000..f9a930014166 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.routing_v2.types import maneuver as gmr_maneuver + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'NavigationInstruction', + }, +) + + +class NavigationInstruction(proto.Message): + r"""Encapsulates navigation instructions for a + [``RouteLegStep``][google.maps.routing.v2.RouteLegStep]. + + Attributes: + maneuver (google.maps.routing_v2.types.Maneuver): + Encapsulates the navigation instructions for + the current step (for example, turn left, merge, + or straight). This field determines which icon + to display. + instructions (str): + Instructions for navigating this step. + """ + + maneuver: gmr_maneuver.Maneuver = proto.Field( + proto.ENUM, + number=1, + enum=gmr_maneuver.Maneuver, + ) + instructions: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py new file mode 100644 index 000000000000..fe776cd21e8b --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py @@ -0,0 +1,113 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'PolylineQuality', + 'PolylineEncoding', + 'Polyline', + }, +) + + +class PolylineQuality(proto.Enum): + r"""A set of values that specify the quality of the polyline. + + Values: + POLYLINE_QUALITY_UNSPECIFIED (0): + No polyline quality preference specified. Defaults to + ``OVERVIEW``. + HIGH_QUALITY (1): + Specifies a high-quality polyline - which is composed using + more points than ``OVERVIEW``, at the cost of increased + response size. Use this value when you need more precision. + OVERVIEW (2): + Specifies an overview polyline - which is composed using a + small number of points. Use this value when displaying an + overview of the route. Using this option has a lower request + latency compared to using the ``HIGH_QUALITY`` option. + """ + POLYLINE_QUALITY_UNSPECIFIED = 0 + HIGH_QUALITY = 1 + OVERVIEW = 2 + + +class PolylineEncoding(proto.Enum): + r"""Specifies the preferred type of polyline to be returned. + + Values: + POLYLINE_ENCODING_UNSPECIFIED (0): + No polyline type preference specified. Defaults to + ``ENCODED_POLYLINE``. + ENCODED_POLYLINE (1): + Specifies a polyline encoded using the `polyline encoding + algorithm `__. + GEO_JSON_LINESTRING (2): + Specifies a polyline using the `GeoJSON LineString + format `__ + """ + POLYLINE_ENCODING_UNSPECIFIED = 0 + ENCODED_POLYLINE = 1 + GEO_JSON_LINESTRING = 2 + + +class Polyline(proto.Message): + r"""Encapsulates an encoded polyline. + + 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: + encoded_polyline (str): + The string encoding of the polyline using the `polyline + encoding + algorithm `__ + + This field is a member of `oneof`_ ``polyline_type``. + geo_json_linestring (google.protobuf.struct_pb2.Struct): + Specifies a polyline using the `GeoJSON LineString + format `__. + + This field is a member of `oneof`_ ``polyline_type``. + """ + + encoded_polyline: str = proto.Field( + proto.STRING, + number=1, + oneof='polyline_type', + ) + geo_json_linestring: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=2, + oneof='polyline_type', + message=struct_pb2.Struct, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline_details.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline_details.py new file mode 100644 index 000000000000..7d7db2480849 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline_details.py @@ -0,0 +1,150 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.routing.v2', + manifest={ + 'PolylineDetails', + }, +) + + +class PolylineDetails(proto.Message): + r"""Details corresponding to a given index or contiguous segment of a + polyline. Given a polyline with points P_0, P_1, ... , P_N + (zero-based index), the ``PolylineDetails`` defines an interval and + associated metadata. + + Attributes: + flyover_info (MutableSequence[google.maps.routing_v2.types.PolylineDetails.FlyoverInfo]): + Flyover details along the polyline. + narrow_road_info (MutableSequence[google.maps.routing_v2.types.PolylineDetails.NarrowRoadInfo]): + Narrow road details along the polyline. + """ + class RoadFeatureState(proto.Enum): + r"""Encapsulates the states of road features along a stretch of + polyline. + + Values: + ROAD_FEATURE_STATE_UNSPECIFIED (0): + The road feature's state was not computed + (default value). + EXISTS (1): + The road feature exists. + DOES_NOT_EXIST (2): + The road feature does not exist. + """ + ROAD_FEATURE_STATE_UNSPECIFIED = 0 + EXISTS = 1 + DOES_NOT_EXIST = 2 + + class PolylinePointIndex(proto.Message): + r"""Encapsulates the start and end indexes for a polyline detail. For + instances where the data corresponds to a single point, + ``start_index`` and ``end_index`` will be equal. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + start_index (int): + The start index of this detail in the + polyline. + + This field is a member of `oneof`_ ``_start_index``. + end_index (int): + The end index of this detail in the polyline. + + This field is a member of `oneof`_ ``_end_index``. + """ + + start_index: int = proto.Field( + proto.INT32, + number=1, + optional=True, + ) + end_index: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + + class FlyoverInfo(proto.Message): + r"""Encapsulates information about flyovers along the polyline. + + Attributes: + flyover_presence (google.maps.routing_v2.types.PolylineDetails.RoadFeatureState): + Output only. Denotes whether a flyover exists + for a given stretch of the polyline. + polyline_point_index (google.maps.routing_v2.types.PolylineDetails.PolylinePointIndex): + The location of flyover related information + along the polyline. + """ + + flyover_presence: 'PolylineDetails.RoadFeatureState' = proto.Field( + proto.ENUM, + number=1, + enum='PolylineDetails.RoadFeatureState', + ) + polyline_point_index: 'PolylineDetails.PolylinePointIndex' = proto.Field( + proto.MESSAGE, + number=2, + message='PolylineDetails.PolylinePointIndex', + ) + + class NarrowRoadInfo(proto.Message): + r"""Encapsulates information about narrow roads along the + polyline. + + Attributes: + narrow_road_presence (google.maps.routing_v2.types.PolylineDetails.RoadFeatureState): + Output only. Denotes whether a narrow road + exists for a given stretch of the polyline. + polyline_point_index (google.maps.routing_v2.types.PolylineDetails.PolylinePointIndex): + The location of narrow road related + information along the polyline. + """ + + narrow_road_presence: 'PolylineDetails.RoadFeatureState' = proto.Field( + proto.ENUM, + number=1, + enum='PolylineDetails.RoadFeatureState', + ) + polyline_point_index: 'PolylineDetails.PolylinePointIndex' = proto.Field( + proto.MESSAGE, + number=2, + message='PolylineDetails.PolylinePointIndex', + ) + + flyover_info: MutableSequence[FlyoverInfo] = proto.RepeatedField( + proto.MESSAGE, + number=12, + message=FlyoverInfo, + ) + narrow_road_info: MutableSequence[NarrowRoadInfo] = proto.RepeatedField( + proto.MESSAGE, + number=13, + message=NarrowRoadInfo, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py new file mode 100644 index 000000000000..facf38d5452e --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py @@ -0,0 +1,799 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.geo.type.types import viewport as ggt_viewport +from google.maps.routing_v2.types import localized_time +from google.maps.routing_v2.types import location +from google.maps.routing_v2.types import navigation_instruction as gmr_navigation_instruction +from google.maps.routing_v2.types import polyline as gmr_polyline +from google.maps.routing_v2.types import polyline_details as gmr_polyline_details +from google.maps.routing_v2.types import route_label +from google.maps.routing_v2.types import route_travel_mode +from google.maps.routing_v2.types import speed_reading_interval +from google.maps.routing_v2.types import toll_info as gmr_toll_info +from google.maps.routing_v2.types import transit +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import localized_text_pb2 # type: ignore +from google.type import money_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'Route', + 'RouteTravelAdvisory', + 'RouteLegTravelAdvisory', + 'RouteLegStepTravelAdvisory', + 'RouteLeg', + 'RouteLegStep', + 'RouteLegStepTransitDetails', + }, +) + + +class Route(proto.Message): + r"""Contains a route, which consists of a series of connected + road segments that join beginning, ending, and intermediate + waypoints. + + Attributes: + route_labels (MutableSequence[google.maps.routing_v2.types.RouteLabel]): + Labels for the ``Route`` that are useful to identify + specific properties of the route to compare against others. + legs (MutableSequence[google.maps.routing_v2.types.RouteLeg]): + A collection of legs (path segments between waypoints) that + make up the route. Each leg corresponds to the trip between + two non-\ ``via`` + [``Waypoints``][google.maps.routing.v2.Waypoint]. For + example, a route with no intermediate waypoints has only one + leg. A route that includes one non-\ ``via`` intermediate + waypoint has two legs. A route that includes one ``via`` + intermediate waypoint has one leg. The order of the legs + matches the order of waypoints from ``origin`` to + ``intermediates`` to ``destination``. + distance_meters (int): + The travel distance of the route, in meters. + duration (google.protobuf.duration_pb2.Duration): + The length of time needed to navigate the route. If you set + the ``routing_preference`` to ``TRAFFIC_UNAWARE``, then this + value is the same as ``static_duration``. If you set the + ``routing_preference`` to either ``TRAFFIC_AWARE`` or + ``TRAFFIC_AWARE_OPTIMAL``, then this value is calculated + taking traffic conditions into account. + static_duration (google.protobuf.duration_pb2.Duration): + The duration of travel through the route + without taking traffic conditions into + consideration. + polyline (google.maps.routing_v2.types.Polyline): + The overall route polyline. This polyline is the combined + polyline of all ``legs``. + description (str): + A description of the route. + warnings (MutableSequence[str]): + An array of warnings to show when displaying + the route. + viewport (google.geo.type.types.Viewport): + The viewport bounding box of the polyline. + travel_advisory (google.maps.routing_v2.types.RouteTravelAdvisory): + Additional information about the route. + optimized_intermediate_waypoint_index (MutableSequence[int]): + If you set + [``optimize_waypoint_order``][google.maps.routing.v2.ComputeRoutesRequest.optimize_waypoint_order] + to true, this field contains the optimized ordering of + intermediate waypoints. Otherwise, this field is empty. For + example, if you give an input of Origin: LA; Intermediate + waypoints: Dallas, Bangor, Phoenix; Destination: New York; + and the optimized intermediate waypoint order is Phoenix, + Dallas, Bangor, then this field contains the values [2, 0, + 1]. The index starts with 0 for the first intermediate + waypoint provided in the input. + localized_values (google.maps.routing_v2.types.Route.RouteLocalizedValues): + Text representations of properties of the ``Route``. + route_token (str): + An opaque token that can be passed to `Navigation + SDK `__ + to reconstruct the route during navigation, and, in the + event of rerouting, honor the original intention when the + route was created. Treat this token as an opaque blob. Don't + compare its value across requests as its value may change + even if the service returns the exact same route. + + NOTE: ``Route.route_token`` is only available for requests + that have set ``ComputeRoutesRequest.routing_preference`` to + ``TRAFFIC_AWARE`` or ``TRAFFIC_AWARE_OPTIMAL``. + ``Route.route_token`` is not supported for requests that + have Via waypoints. + polyline_details (google.maps.routing_v2.types.PolylineDetails): + Contains information about details along the + polyline. + """ + + class RouteLocalizedValues(proto.Message): + r"""Text representations of certain properties. + + Attributes: + distance (google.type.localized_text_pb2.LocalizedText): + Travel distance represented in text form. + duration (google.type.localized_text_pb2.LocalizedText): + Duration, represented in text form and localized to the + region of the query. Takes traffic conditions into + consideration. Note: If you did not request traffic + information, this value is the same value as + ``static_duration``. + static_duration (google.type.localized_text_pb2.LocalizedText): + Duration without taking traffic conditions + into consideration, represented in text form. + transit_fare (google.type.localized_text_pb2.LocalizedText): + Transit fare represented in text form. + """ + + distance: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=1, + message=localized_text_pb2.LocalizedText, + ) + duration: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=2, + message=localized_text_pb2.LocalizedText, + ) + static_duration: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=3, + message=localized_text_pb2.LocalizedText, + ) + transit_fare: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=4, + message=localized_text_pb2.LocalizedText, + ) + + route_labels: MutableSequence[route_label.RouteLabel] = proto.RepeatedField( + proto.ENUM, + number=13, + enum=route_label.RouteLabel, + ) + legs: MutableSequence['RouteLeg'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='RouteLeg', + ) + distance_meters: int = proto.Field( + proto.INT32, + number=2, + ) + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) + static_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + polyline: gmr_polyline.Polyline = proto.Field( + proto.MESSAGE, + number=5, + message=gmr_polyline.Polyline, + ) + description: str = proto.Field( + proto.STRING, + number=6, + ) + warnings: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + viewport: ggt_viewport.Viewport = proto.Field( + proto.MESSAGE, + number=8, + message=ggt_viewport.Viewport, + ) + travel_advisory: 'RouteTravelAdvisory' = proto.Field( + proto.MESSAGE, + number=9, + message='RouteTravelAdvisory', + ) + optimized_intermediate_waypoint_index: MutableSequence[int] = proto.RepeatedField( + proto.INT32, + number=10, + ) + localized_values: RouteLocalizedValues = proto.Field( + proto.MESSAGE, + number=11, + message=RouteLocalizedValues, + ) + route_token: str = proto.Field( + proto.STRING, + number=12, + ) + polyline_details: gmr_polyline_details.PolylineDetails = proto.Field( + proto.MESSAGE, + number=14, + message=gmr_polyline_details.PolylineDetails, + ) + + +class RouteTravelAdvisory(proto.Message): + r"""Contains the additional information that the user should be + informed about, such as possible traffic zone restrictions. + + Attributes: + toll_info (google.maps.routing_v2.types.TollInfo): + Contains information about tolls on the route. This field is + only populated if tolls are expected on the route. If this + field is set, but the ``estimatedPrice`` subfield is not + populated, then the route contains tolls, but the estimated + price is unknown. If this field is not set, then there are + no tolls expected on the route. + speed_reading_intervals (MutableSequence[google.maps.routing_v2.types.SpeedReadingInterval]): + Speed reading intervals detailing traffic density. + Applicable in case of ``TRAFFIC_AWARE`` and + ``TRAFFIC_AWARE_OPTIMAL`` routing preferences. The intervals + cover the entire polyline of the route without overlap. The + start point of a specified interval is the same as the end + point of the preceding interval. + + Example: + + :: + + polyline: A ---- B ---- C ---- D ---- E ---- F ---- G + speed_reading_intervals: [A,C), [C,D), [D,G). + fuel_consumption_microliters (int): + The predicted fuel consumption in + microliters. + route_restrictions_partially_ignored (bool): + Returned route may have restrictions that are + not suitable for requested travel mode or route + modifiers. + transit_fare (google.type.money_pb2.Money): + If present, contains the total fare or ticket costs on this + route This property is only returned for ``TRANSIT`` + requests and only for routes where fare information is + available for all transit steps. + """ + + toll_info: gmr_toll_info.TollInfo = proto.Field( + proto.MESSAGE, + number=2, + message=gmr_toll_info.TollInfo, + ) + speed_reading_intervals: MutableSequence[speed_reading_interval.SpeedReadingInterval] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=speed_reading_interval.SpeedReadingInterval, + ) + fuel_consumption_microliters: int = proto.Field( + proto.INT64, + number=5, + ) + route_restrictions_partially_ignored: bool = proto.Field( + proto.BOOL, + number=6, + ) + transit_fare: money_pb2.Money = proto.Field( + proto.MESSAGE, + number=7, + message=money_pb2.Money, + ) + + +class RouteLegTravelAdvisory(proto.Message): + r"""Contains the additional information that the user should be + informed about on a leg step, such as possible traffic zone + restrictions. + + Attributes: + toll_info (google.maps.routing_v2.types.TollInfo): + Contains information about tolls on the specific + ``RouteLeg``. This field is only populated if we expect + there are tolls on the ``RouteLeg``. If this field is set + but the estimated_price subfield is not populated, we expect + that road contains tolls but we do not know an estimated + price. If this field does not exist, then there is no toll + on the ``RouteLeg``. + speed_reading_intervals (MutableSequence[google.maps.routing_v2.types.SpeedReadingInterval]): + Speed reading intervals detailing traffic density. + Applicable in case of ``TRAFFIC_AWARE`` and + ``TRAFFIC_AWARE_OPTIMAL`` routing preferences. The intervals + cover the entire polyline of the ``RouteLeg`` without + overlap. The start point of a specified interval is the same + as the end point of the preceding interval. + + Example: + + :: + + polyline: A ---- B ---- C ---- D ---- E ---- F ---- G + speed_reading_intervals: [A,C), [C,D), [D,G). + """ + + toll_info: gmr_toll_info.TollInfo = proto.Field( + proto.MESSAGE, + number=1, + message=gmr_toll_info.TollInfo, + ) + speed_reading_intervals: MutableSequence[speed_reading_interval.SpeedReadingInterval] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=speed_reading_interval.SpeedReadingInterval, + ) + + +class RouteLegStepTravelAdvisory(proto.Message): + r"""Contains the additional information that the user should be + informed about, such as possible traffic zone restrictions on a + leg step. + + Attributes: + speed_reading_intervals (MutableSequence[google.maps.routing_v2.types.SpeedReadingInterval]): + NOTE: This field is not currently populated. + """ + + speed_reading_intervals: MutableSequence[speed_reading_interval.SpeedReadingInterval] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=speed_reading_interval.SpeedReadingInterval, + ) + + +class RouteLeg(proto.Message): + r"""Contains a segment between non-\ ``via`` waypoints. + + Attributes: + distance_meters (int): + The travel distance of the route leg, in + meters. + duration (google.protobuf.duration_pb2.Duration): + The length of time needed to navigate the leg. If the + ``route_preference`` is set to ``TRAFFIC_UNAWARE``, then + this value is the same as ``static_duration``. If the + ``route_preference`` is either ``TRAFFIC_AWARE`` or + ``TRAFFIC_AWARE_OPTIMAL``, then this value is calculated + taking traffic conditions into account. + static_duration (google.protobuf.duration_pb2.Duration): + The duration of travel through the leg, + calculated without taking traffic conditions + into consideration. + polyline (google.maps.routing_v2.types.Polyline): + The overall polyline for this leg that includes each + ``step``'s polyline. + start_location (google.maps.routing_v2.types.Location): + The start location of this leg. This location might be + different from the provided ``origin``. For example, when + the provided ``origin`` is not near a road, this is a point + on the road. + end_location (google.maps.routing_v2.types.Location): + The end location of this leg. This location might be + different from the provided ``destination``. For example, + when the provided ``destination`` is not near a road, this + is a point on the road. + steps (MutableSequence[google.maps.routing_v2.types.RouteLegStep]): + An array of steps denoting segments within + this leg. Each step represents one navigation + instruction. + travel_advisory (google.maps.routing_v2.types.RouteLegTravelAdvisory): + Contains the additional information that the + user should be informed about, such as possible + traffic zone restrictions, on a route leg. + localized_values (google.maps.routing_v2.types.RouteLeg.RouteLegLocalizedValues): + Text representations of properties of the ``RouteLeg``. + steps_overview (google.maps.routing_v2.types.RouteLeg.StepsOverview): + Overview information about the steps in this ``RouteLeg``. + This field is only populated for TRANSIT routes. + """ + + class RouteLegLocalizedValues(proto.Message): + r"""Text representations of certain properties. + + Attributes: + distance (google.type.localized_text_pb2.LocalizedText): + Travel distance represented in text form. + duration (google.type.localized_text_pb2.LocalizedText): + Duration, represented in text form and localized to the + region of the query. Takes traffic conditions into + consideration. Note: If you did not request traffic + information, this value is the same value as + static_duration. + static_duration (google.type.localized_text_pb2.LocalizedText): + Duration without taking traffic conditions + into consideration, represented in text form. + """ + + distance: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=1, + message=localized_text_pb2.LocalizedText, + ) + duration: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=2, + message=localized_text_pb2.LocalizedText, + ) + static_duration: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=3, + message=localized_text_pb2.LocalizedText, + ) + + class StepsOverview(proto.Message): + r"""Provides overview information about a list of ``RouteLegStep``\ s. + + Attributes: + multi_modal_segments (MutableSequence[google.maps.routing_v2.types.RouteLeg.StepsOverview.MultiModalSegment]): + Summarized information about different multi-modal segments + of the ``RouteLeg.steps``. This field is not populated if + the ``RouteLeg`` does not contain any multi-modal segments + in the steps. + """ + + class MultiModalSegment(proto.Message): + r"""Provides summarized information about different multi-modal segments + of the ``RouteLeg.steps``. A multi-modal segment is defined as one + or more contiguous ``RouteLegStep`` that have the same + ``RouteTravelMode``. This field is not populated if the ``RouteLeg`` + does not contain any multi-modal segments in the steps. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + step_start_index (int): + The corresponding ``RouteLegStep`` index that is the start + of a multi-modal segment. + + This field is a member of `oneof`_ ``_step_start_index``. + step_end_index (int): + The corresponding ``RouteLegStep`` index that is the end of + a multi-modal segment. + + This field is a member of `oneof`_ ``_step_end_index``. + navigation_instruction (google.maps.routing_v2.types.NavigationInstruction): + NavigationInstruction for the multi-modal + segment. + travel_mode (google.maps.routing_v2.types.RouteTravelMode): + The travel mode of the multi-modal segment. + """ + + step_start_index: int = proto.Field( + proto.INT32, + number=1, + optional=True, + ) + step_end_index: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + navigation_instruction: gmr_navigation_instruction.NavigationInstruction = proto.Field( + proto.MESSAGE, + number=3, + message=gmr_navigation_instruction.NavigationInstruction, + ) + travel_mode: route_travel_mode.RouteTravelMode = proto.Field( + proto.ENUM, + number=4, + enum=route_travel_mode.RouteTravelMode, + ) + + multi_modal_segments: MutableSequence['RouteLeg.StepsOverview.MultiModalSegment'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='RouteLeg.StepsOverview.MultiModalSegment', + ) + + distance_meters: int = proto.Field( + proto.INT32, + number=1, + ) + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + static_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) + polyline: gmr_polyline.Polyline = proto.Field( + proto.MESSAGE, + number=4, + message=gmr_polyline.Polyline, + ) + start_location: location.Location = proto.Field( + proto.MESSAGE, + number=5, + message=location.Location, + ) + end_location: location.Location = proto.Field( + proto.MESSAGE, + number=6, + message=location.Location, + ) + steps: MutableSequence['RouteLegStep'] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message='RouteLegStep', + ) + travel_advisory: 'RouteLegTravelAdvisory' = proto.Field( + proto.MESSAGE, + number=8, + message='RouteLegTravelAdvisory', + ) + localized_values: RouteLegLocalizedValues = proto.Field( + proto.MESSAGE, + number=9, + message=RouteLegLocalizedValues, + ) + steps_overview: StepsOverview = proto.Field( + proto.MESSAGE, + number=10, + message=StepsOverview, + ) + + +class RouteLegStep(proto.Message): + r"""Contains a segment of a + [``RouteLeg``][google.maps.routing.v2.RouteLeg]. A step corresponds + to a single navigation instruction. Route legs are made up of steps. + + Attributes: + distance_meters (int): + The travel distance of this step, in meters. + In some circumstances, this field might not have + a value. + static_duration (google.protobuf.duration_pb2.Duration): + The duration of travel through this step + without taking traffic conditions into + consideration. In some circumstances, this field + might not have a value. + polyline (google.maps.routing_v2.types.Polyline): + The polyline associated with this step. + start_location (google.maps.routing_v2.types.Location): + The start location of this step. + end_location (google.maps.routing_v2.types.Location): + The end location of this step. + navigation_instruction (google.maps.routing_v2.types.NavigationInstruction): + Navigation instructions. + travel_advisory (google.maps.routing_v2.types.RouteLegStepTravelAdvisory): + Contains the additional information that the + user should be informed about, such as possible + traffic zone restrictions, on a leg step. + localized_values (google.maps.routing_v2.types.RouteLegStep.RouteLegStepLocalizedValues): + Text representations of properties of the ``RouteLegStep``. + transit_details (google.maps.routing_v2.types.RouteLegStepTransitDetails): + Details pertaining to this step if the travel mode is + ``TRANSIT``. + travel_mode (google.maps.routing_v2.types.RouteTravelMode): + The travel mode used for this step. + """ + + class RouteLegStepLocalizedValues(proto.Message): + r"""Text representations of certain properties. + + Attributes: + distance (google.type.localized_text_pb2.LocalizedText): + Travel distance represented in text form. + static_duration (google.type.localized_text_pb2.LocalizedText): + Duration without taking traffic conditions + into consideration, represented in text form. + """ + + distance: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=1, + message=localized_text_pb2.LocalizedText, + ) + static_duration: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=3, + message=localized_text_pb2.LocalizedText, + ) + + distance_meters: int = proto.Field( + proto.INT32, + number=1, + ) + static_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + polyline: gmr_polyline.Polyline = proto.Field( + proto.MESSAGE, + number=3, + message=gmr_polyline.Polyline, + ) + start_location: location.Location = proto.Field( + proto.MESSAGE, + number=4, + message=location.Location, + ) + end_location: location.Location = proto.Field( + proto.MESSAGE, + number=5, + message=location.Location, + ) + navigation_instruction: gmr_navigation_instruction.NavigationInstruction = proto.Field( + proto.MESSAGE, + number=6, + message=gmr_navigation_instruction.NavigationInstruction, + ) + travel_advisory: 'RouteLegStepTravelAdvisory' = proto.Field( + proto.MESSAGE, + number=7, + message='RouteLegStepTravelAdvisory', + ) + localized_values: RouteLegStepLocalizedValues = proto.Field( + proto.MESSAGE, + number=8, + message=RouteLegStepLocalizedValues, + ) + transit_details: 'RouteLegStepTransitDetails' = proto.Field( + proto.MESSAGE, + number=9, + message='RouteLegStepTransitDetails', + ) + travel_mode: route_travel_mode.RouteTravelMode = proto.Field( + proto.ENUM, + number=10, + enum=route_travel_mode.RouteTravelMode, + ) + + +class RouteLegStepTransitDetails(proto.Message): + r"""Additional information for the ``RouteLegStep`` related to + ``TRANSIT`` routes. + + Attributes: + stop_details (google.maps.routing_v2.types.RouteLegStepTransitDetails.TransitStopDetails): + Information about the arrival and departure + stops for the step. + localized_values (google.maps.routing_v2.types.RouteLegStepTransitDetails.TransitDetailsLocalizedValues): + Text representations of properties of the + ``RouteLegStepTransitDetails``. + headsign (str): + Specifies the direction in which to travel on + this line as marked on the vehicle or at the + departure stop. The direction is often the + terminus station. + headway (google.protobuf.duration_pb2.Duration): + Specifies the expected time as a duration + between departures from the same stop at this + time. For example, with a headway seconds value + of 600, you would expect a ten minute wait if + you should miss your bus. + transit_line (google.maps.routing_v2.types.TransitLine): + Information about the transit line used in + this step. + stop_count (int): + The number of stops from the departure to the arrival stop. + This count includes the arrival stop, but excludes the + departure stop. For example, if your route leaves from Stop + A, passes through stops B and C, and arrives at stop D, + stop_count returns 3. + trip_short_text (str): + The text that appears in schedules and sign boards to + identify a transit trip to passengers. The text should + uniquely identify a trip within a service day. For example, + "538" is the ``trip_short_text`` of the Amtrak train that + leaves San Jose, CA at 15:10 on weekdays to Sacramento, CA. + """ + + class TransitStopDetails(proto.Message): + r"""Details about the transit stops for the ``RouteLegStep``. + + Attributes: + arrival_stop (google.maps.routing_v2.types.TransitStop): + Information about the arrival stop for the + step. + arrival_time (google.protobuf.timestamp_pb2.Timestamp): + The estimated time of arrival for the step. + departure_stop (google.maps.routing_v2.types.TransitStop): + Information about the departure stop for the + step. + departure_time (google.protobuf.timestamp_pb2.Timestamp): + The estimated time of departure for the step. + """ + + arrival_stop: transit.TransitStop = proto.Field( + proto.MESSAGE, + number=1, + message=transit.TransitStop, + ) + arrival_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + departure_stop: transit.TransitStop = proto.Field( + proto.MESSAGE, + number=3, + message=transit.TransitStop, + ) + departure_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + + class TransitDetailsLocalizedValues(proto.Message): + r"""Localized descriptions of values for ``RouteTransitDetails``. + + Attributes: + arrival_time (google.maps.routing_v2.types.LocalizedTime): + Time in its formatted text representation + with a corresponding time zone. + departure_time (google.maps.routing_v2.types.LocalizedTime): + Time in its formatted text representation + with a corresponding time zone. + """ + + arrival_time: localized_time.LocalizedTime = proto.Field( + proto.MESSAGE, + number=1, + message=localized_time.LocalizedTime, + ) + departure_time: localized_time.LocalizedTime = proto.Field( + proto.MESSAGE, + number=2, + message=localized_time.LocalizedTime, + ) + + stop_details: TransitStopDetails = proto.Field( + proto.MESSAGE, + number=1, + message=TransitStopDetails, + ) + localized_values: TransitDetailsLocalizedValues = proto.Field( + proto.MESSAGE, + number=2, + message=TransitDetailsLocalizedValues, + ) + headsign: str = proto.Field( + proto.STRING, + number=3, + ) + headway: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + transit_line: transit.TransitLine = proto.Field( + proto.MESSAGE, + number=5, + message=transit.TransitLine, + ) + stop_count: int = proto.Field( + proto.INT32, + number=6, + ) + trip_short_text: str = proto.Field( + proto.STRING, + number=7, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py new file mode 100644 index 000000000000..57aa11e9666e --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.routing.v2', + manifest={ + 'RouteLabel', + }, +) + + +class RouteLabel(proto.Enum): + r"""Labels for the [``Route``][google.maps.routing.v2.Route] that are + useful to identify specific properties of the route to compare + against others. + + Values: + ROUTE_LABEL_UNSPECIFIED (0): + Default - not used. + DEFAULT_ROUTE (1): + The default "best" route returned for the + route computation. + DEFAULT_ROUTE_ALTERNATE (2): + An alternative to the default "best" route. Routes like this + will be returned when + [``compute_alternative_routes``][google.maps.routing.v2.ComputeRoutesRequest.compute_alternative_routes] + is specified. + FUEL_EFFICIENT (3): + Fuel efficient route. Routes labeled with + this value are determined to be optimized for + Eco parameters such as fuel consumption. + SHORTER_DISTANCE (4): + Shorter travel distance route. This is an + experimental feature. + """ + ROUTE_LABEL_UNSPECIFIED = 0 + DEFAULT_ROUTE = 1 + DEFAULT_ROUTE_ALTERNATE = 2 + FUEL_EFFICIENT = 3 + SHORTER_DISTANCE = 4 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py new file mode 100644 index 000000000000..a8a386928907 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py @@ -0,0 +1,98 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.routing_v2.types import toll_passes as gmr_toll_passes +from google.maps.routing_v2.types import vehicle_info as gmr_vehicle_info + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'RouteModifiers', + }, +) + + +class RouteModifiers(proto.Message): + r"""Encapsulates a set of optional conditions to satisfy when + calculating the routes. + + Attributes: + avoid_tolls (bool): + When set to true, avoids toll roads where reasonable, giving + preference to routes not containing toll roads. Applies only + to the ``DRIVE`` and ``TWO_WHEELER`` + [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode]. + avoid_highways (bool): + When set to true, avoids highways where reasonable, giving + preference to routes not containing highways. Applies only + to the ``DRIVE`` and ``TWO_WHEELER`` + [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode]. + avoid_ferries (bool): + When set to true, avoids ferries where reasonable, giving + preference to routes not containing ferries. Applies only to + the ``DRIVE`` and\ ``TWO_WHEELER`` + [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode]. + avoid_indoor (bool): + When set to true, avoids navigating indoors where + reasonable, giving preference to routes not containing + indoor navigation. Applies only to the ``WALK`` + [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode]. + vehicle_info (google.maps.routing_v2.types.VehicleInfo): + Specifies the vehicle information. + toll_passes (MutableSequence[google.maps.routing_v2.types.TollPass]): + Encapsulates information about toll passes. If toll passes + are provided, the API tries to return the pass price. If + toll passes are not provided, the API treats the toll pass + as unknown and tries to return the cash price. Applies only + to the ``DRIVE`` and ``TWO_WHEELER`` + [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode]. + """ + + avoid_tolls: bool = proto.Field( + proto.BOOL, + number=1, + ) + avoid_highways: bool = proto.Field( + proto.BOOL, + number=2, + ) + avoid_ferries: bool = proto.Field( + proto.BOOL, + number=3, + ) + avoid_indoor: bool = proto.Field( + proto.BOOL, + number=4, + ) + vehicle_info: gmr_vehicle_info.VehicleInfo = proto.Field( + proto.MESSAGE, + number=5, + message=gmr_vehicle_info.VehicleInfo, + ) + toll_passes: MutableSequence[gmr_toll_passes.TollPass] = proto.RepeatedField( + proto.ENUM, + number=6, + enum=gmr_toll_passes.TollPass, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py new file mode 100644 index 000000000000..674af4e560a3 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.routing.v2', + manifest={ + 'RouteTravelMode', + }, +) + + +class RouteTravelMode(proto.Enum): + r"""A set of values used to specify the mode of travel. NOTE: ``WALK``, + ``BICYCLE``, and ``TWO_WHEELER`` routes are in beta and might + sometimes be missing clear sidewalks, pedestrian paths, or bicycling + paths. You must display this warning to the user for all walking, + bicycling, and two-wheel routes that you display in your app. + + Values: + TRAVEL_MODE_UNSPECIFIED (0): + No travel mode specified. Defaults to ``DRIVE``. + DRIVE (1): + Travel by passenger car. + BICYCLE (2): + Travel by bicycle. + WALK (3): + Travel by walking. + TWO_WHEELER (4): + Two-wheeled, motorized vehicle. For example, motorcycle. + Note that this differs from the ``BICYCLE`` travel mode + which covers human-powered mode. + TRANSIT (7): + Travel by public transit routes, where + available. + """ + TRAVEL_MODE_UNSPECIFIED = 0 + DRIVE = 1 + BICYCLE = 2 + WALK = 3 + TWO_WHEELER = 4 + TRANSIT = 7 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py new file mode 100644 index 000000000000..1f560384693a --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py @@ -0,0 +1,748 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.routing_v2.types import fallback_info as gmr_fallback_info +from google.maps.routing_v2.types import geocoding_results as gmr_geocoding_results +from google.maps.routing_v2.types import polyline +from google.maps.routing_v2.types import route +from google.maps.routing_v2.types import route_modifiers as gmr_route_modifiers +from google.maps.routing_v2.types import route_travel_mode +from google.maps.routing_v2.types import routing_preference as gmr_routing_preference +from google.maps.routing_v2.types import traffic_model as gmr_traffic_model +from google.maps.routing_v2.types import transit_preferences as gmr_transit_preferences +from google.maps.routing_v2.types import units as gmr_units +from google.maps.routing_v2.types import waypoint as gmr_waypoint +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import localized_text_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'RouteMatrixElementCondition', + 'ComputeRoutesRequest', + 'ComputeRoutesResponse', + 'ComputeRouteMatrixRequest', + 'RouteMatrixOrigin', + 'RouteMatrixDestination', + 'RouteMatrixElement', + }, +) + + +class RouteMatrixElementCondition(proto.Enum): + r"""The condition of the route being returned. + + Values: + ROUTE_MATRIX_ELEMENT_CONDITION_UNSPECIFIED (0): + Only used when the ``status`` of the element is not OK. + ROUTE_EXISTS (1): + A route was found, and the corresponding + information was filled out for the element. + ROUTE_NOT_FOUND (2): + No route could be found. Fields containing route + information, such as ``distance_meters`` or ``duration``, + will not be filled out in the element. + """ + ROUTE_MATRIX_ELEMENT_CONDITION_UNSPECIFIED = 0 + ROUTE_EXISTS = 1 + ROUTE_NOT_FOUND = 2 + + +class ComputeRoutesRequest(proto.Message): + r"""ComputeRoutes request message. + + Attributes: + origin (google.maps.routing_v2.types.Waypoint): + Required. Origin waypoint. + destination (google.maps.routing_v2.types.Waypoint): + Required. Destination waypoint. + intermediates (MutableSequence[google.maps.routing_v2.types.Waypoint]): + Optional. A set of waypoints along the route + (excluding terminal points), for either stopping + at or passing by. Up to 25 intermediate + waypoints are supported. + travel_mode (google.maps.routing_v2.types.RouteTravelMode): + Optional. Specifies the mode of + transportation. + routing_preference (google.maps.routing_v2.types.RoutingPreference): + Optional. Specifies how to compute the route. The server + attempts to use the selected routing preference to compute + the route. If the routing preference results in an error or + an extra long latency, then an error is returned. You can + specify this option only when the ``travel_mode`` is + ``DRIVE`` or ``TWO_WHEELER``, otherwise the request fails. + polyline_quality (google.maps.routing_v2.types.PolylineQuality): + Optional. Specifies your preference for the + quality of the polyline. + polyline_encoding (google.maps.routing_v2.types.PolylineEncoding): + Optional. Specifies the preferred encoding + for the polyline. + departure_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. The departure time. If you don't set this value, + then this value defaults to the time that you made the + request. NOTE: You can only specify a ``departure_time`` in + the past when + [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode] + is set to ``TRANSIT``. Transit trips are available for up to + 7 days in the past or 100 days in the future. + arrival_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. The arrival time. NOTE: Can only be set when + [RouteTravelMode][google.maps.routing.v2.RouteTravelMode] is + set to ``TRANSIT``. You can specify either + ``departure_time`` or ``arrival_time``, but not both. + Transit trips are available for up to 7 days in the past or + 100 days in the future. + compute_alternative_routes (bool): + Optional. Specifies whether to calculate + alternate routes in addition to the route. No + alternative routes are returned for requests + that have intermediate waypoints. + route_modifiers (google.maps.routing_v2.types.RouteModifiers): + Optional. A set of conditions to satisfy that + affect the way routes are calculated. + language_code (str): + Optional. The BCP-47 language code, such as "en-US" or + "sr-Latn". For more information, see `Unicode Locale + Identifier `__. + See `Language + Support `__ + for the list of supported languages. When you don't provide + this value, the display language is inferred from the + location of the route request. + region_code (str): + Optional. The region code, specified as a ccTLD ("top-level + domain") two-character value. For more information see + `Country code top-level + domains `__. + units (google.maps.routing_v2.types.Units): + Optional. Specifies the units of measure for the display + fields. These fields include the ``instruction`` field in + [``NavigationInstruction``][google.maps.routing.v2.NavigationInstruction]. + The units of measure used for the route, leg, step distance, + and duration are not affected by this value. If you don't + provide this value, then the display units are inferred from + the location of the first origin. + optimize_waypoint_order (bool): + Optional. If set to true, the service attempts to minimize + the overall cost of the route by re-ordering the specified + intermediate waypoints. The request fails if any of the + intermediate waypoints is a ``via`` waypoint. Use + ``ComputeRoutesResponse.Routes.optimized_intermediate_waypoint_index`` + to find the new ordering. If + ``ComputeRoutesResponseroutes.optimized_intermediate_waypoint_index`` + is not requested in the ``X-Goog-FieldMask`` header, the + request fails. If ``optimize_waypoint_order`` is set to + false, + ``ComputeRoutesResponse.optimized_intermediate_waypoint_index`` + will be empty. + requested_reference_routes (MutableSequence[google.maps.routing_v2.types.ComputeRoutesRequest.ReferenceRoute]): + Optional. Specifies what reference routes to calculate as + part of the request in addition to the default route. A + reference route is a route with a different route + calculation objective than the default route. For example a + ``FUEL_EFFICIENT`` reference route calculation takes into + account various parameters that would generate an optimal + fuel efficient route. When using this feature, look for + [``route_labels``][google.maps.routing.v2.Route.route_labels] + on the resulting routes. + extra_computations (MutableSequence[google.maps.routing_v2.types.ComputeRoutesRequest.ExtraComputation]): + Optional. A list of extra computations which + may be used to complete the request. Note: These + extra computations may return extra fields on + the response. These extra fields must also be + specified in the field mask to be returned in + the response. + traffic_model (google.maps.routing_v2.types.TrafficModel): + Optional. Specifies the assumptions to use when calculating + time in traffic. This setting affects the value returned in + the duration field in the + [``Route``][google.maps.routing.v2.Route] and + [``RouteLeg``][google.maps.routing.v2.RouteLeg] which + contains the predicted time in traffic based on historical + averages. ``TrafficModel`` is only available for requests + that have set + [``RoutingPreference``][google.maps.routing.v2.RoutingPreference] + to ``TRAFFIC_AWARE_OPTIMAL`` and + [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode] + to ``DRIVE``. Defaults to ``BEST_GUESS`` if traffic is + requested and ``TrafficModel`` is not specified. + transit_preferences (google.maps.routing_v2.types.TransitPreferences): + Optional. Specifies preferences that influence the route + returned for ``TRANSIT`` routes. NOTE: You can only specify + a ``transit_preferences`` when + [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode] + is set to ``TRANSIT``. + """ + class ReferenceRoute(proto.Enum): + r"""A supported reference route on the ComputeRoutesRequest. + + Values: + REFERENCE_ROUTE_UNSPECIFIED (0): + Not used. Requests containing this value + fail. + FUEL_EFFICIENT (1): + Fuel efficient route. + SHORTER_DISTANCE (2): + Route with shorter travel distance. This is an experimental + feature. + + For ``DRIVE`` requests, this feature prioritizes shorter + distance over driving comfort. For example, it may prefer + local roads instead of highways, take dirt roads, cut + through parking lots, etc. This feature does not return any + maneuvers that Google Maps knows to be illegal. + + For ``BICYCLE`` and ``TWO_WHEELER`` requests, this feature + returns routes similar to those returned when you don't + specify ``requested_reference_routes``. + + This feature is not compatible with any other travel modes, + via intermediate waypoints, or ``optimize_waypoint_order``; + such requests will fail. However, you can use it with any + ``routing_preference``. + """ + REFERENCE_ROUTE_UNSPECIFIED = 0 + FUEL_EFFICIENT = 1 + SHORTER_DISTANCE = 2 + + class ExtraComputation(proto.Enum): + r"""Extra computations to perform while completing the request. + + Values: + EXTRA_COMPUTATION_UNSPECIFIED (0): + Not used. Requests containing this value will + fail. + TOLLS (1): + Toll information for the route(s). + FUEL_CONSUMPTION (2): + Estimated fuel consumption for the route(s). + TRAFFIC_ON_POLYLINE (3): + Traffic aware polylines for the route(s). + HTML_FORMATTED_NAVIGATION_INSTRUCTIONS (4): + ```NavigationInstructions`` `__ + presented as a formatted HTML text string. This content is + meant to be read as-is. This content is for display only. Do + not programmatically parse it. + FLYOVER_INFO_ON_POLYLINE (7): + Flyover information for the route(s). The + ``routes.polyline_details.flyover_info`` fieldmask must be + specified to return this information. This data will only + currently be populated for certain metros in India. This + feature is experimental, and the SKU/charge is subject to + change. + NARROW_ROAD_INFO_ON_POLYLINE (8): + Narrow road information for the route(s). The + ``routes.polyline_details.narrow_road_info`` fieldmask must + be specified to return this information. This data will only + currently be populated for certain metros in India. This + feature is experimental, and the SKU/charge is subject to + change. + """ + EXTRA_COMPUTATION_UNSPECIFIED = 0 + TOLLS = 1 + FUEL_CONSUMPTION = 2 + TRAFFIC_ON_POLYLINE = 3 + HTML_FORMATTED_NAVIGATION_INSTRUCTIONS = 4 + FLYOVER_INFO_ON_POLYLINE = 7 + NARROW_ROAD_INFO_ON_POLYLINE = 8 + + origin: gmr_waypoint.Waypoint = proto.Field( + proto.MESSAGE, + number=1, + message=gmr_waypoint.Waypoint, + ) + destination: gmr_waypoint.Waypoint = proto.Field( + proto.MESSAGE, + number=2, + message=gmr_waypoint.Waypoint, + ) + intermediates: MutableSequence[gmr_waypoint.Waypoint] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=gmr_waypoint.Waypoint, + ) + travel_mode: route_travel_mode.RouteTravelMode = proto.Field( + proto.ENUM, + number=4, + enum=route_travel_mode.RouteTravelMode, + ) + routing_preference: gmr_routing_preference.RoutingPreference = proto.Field( + proto.ENUM, + number=5, + enum=gmr_routing_preference.RoutingPreference, + ) + polyline_quality: polyline.PolylineQuality = proto.Field( + proto.ENUM, + number=6, + enum=polyline.PolylineQuality, + ) + polyline_encoding: polyline.PolylineEncoding = proto.Field( + proto.ENUM, + number=12, + enum=polyline.PolylineEncoding, + ) + departure_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + arrival_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=19, + message=timestamp_pb2.Timestamp, + ) + compute_alternative_routes: bool = proto.Field( + proto.BOOL, + number=8, + ) + route_modifiers: gmr_route_modifiers.RouteModifiers = proto.Field( + proto.MESSAGE, + number=9, + message=gmr_route_modifiers.RouteModifiers, + ) + language_code: str = proto.Field( + proto.STRING, + number=10, + ) + region_code: str = proto.Field( + proto.STRING, + number=16, + ) + units: gmr_units.Units = proto.Field( + proto.ENUM, + number=11, + enum=gmr_units.Units, + ) + optimize_waypoint_order: bool = proto.Field( + proto.BOOL, + number=13, + ) + requested_reference_routes: MutableSequence[ReferenceRoute] = proto.RepeatedField( + proto.ENUM, + number=14, + enum=ReferenceRoute, + ) + extra_computations: MutableSequence[ExtraComputation] = proto.RepeatedField( + proto.ENUM, + number=15, + enum=ExtraComputation, + ) + traffic_model: gmr_traffic_model.TrafficModel = proto.Field( + proto.ENUM, + number=18, + enum=gmr_traffic_model.TrafficModel, + ) + transit_preferences: gmr_transit_preferences.TransitPreferences = proto.Field( + proto.MESSAGE, + number=20, + message=gmr_transit_preferences.TransitPreferences, + ) + + +class ComputeRoutesResponse(proto.Message): + r"""ComputeRoutes the response message. + + Attributes: + routes (MutableSequence[google.maps.routing_v2.types.Route]): + Contains an array of computed routes (up to three) when you + specify ``compute_alternatives_routes``, and contains just + one route when you don't. When this array contains multiple + entries, the first one is the most recommended route. If the + array is empty, then it means no route could be found. + fallback_info (google.maps.routing_v2.types.FallbackInfo): + In some cases when the server is not able to + compute the route results with all of the input + preferences, it may fallback to using a + different way of computation. When fallback mode + is used, this field contains detailed info about + the fallback response. Otherwise this field is + unset. + geocoding_results (google.maps.routing_v2.types.GeocodingResults): + Contains geocoding response info for + waypoints specified as addresses. + """ + + routes: MutableSequence[route.Route] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=route.Route, + ) + fallback_info: gmr_fallback_info.FallbackInfo = proto.Field( + proto.MESSAGE, + number=2, + message=gmr_fallback_info.FallbackInfo, + ) + geocoding_results: gmr_geocoding_results.GeocodingResults = proto.Field( + proto.MESSAGE, + number=3, + message=gmr_geocoding_results.GeocodingResults, + ) + + +class ComputeRouteMatrixRequest(proto.Message): + r"""ComputeRouteMatrix request message + + Attributes: + origins (MutableSequence[google.maps.routing_v2.types.RouteMatrixOrigin]): + Required. Array of origins, which determines the rows of the + response matrix. Several size restrictions apply to the + cardinality of origins and destinations: + + - The sum of the number of origins + the number of + destinations specified as either ``place_id`` or + ``address`` must be no greater than 50. + - The product of number of origins × number of destinations + must be no greater than 625 in any case. + - The product of the number of origins × number of + destinations must be no greater than 100 if + routing_preference is set to ``TRAFFIC_AWARE_OPTIMAL``. + - The product of the number of origins × number of + destinations must be no greater than 100 if travel_mode + is set to ``TRANSIT``. + destinations (MutableSequence[google.maps.routing_v2.types.RouteMatrixDestination]): + Required. Array of destinations, which + determines the columns of the response matrix. + travel_mode (google.maps.routing_v2.types.RouteTravelMode): + Optional. Specifies the mode of + transportation. + routing_preference (google.maps.routing_v2.types.RoutingPreference): + Optional. Specifies how to compute the route. The server + attempts to use the selected routing preference to compute + the route. If the routing preference results in an error or + an extra long latency, an error is returned. You can specify + this option only when the ``travel_mode`` is ``DRIVE`` or + ``TWO_WHEELER``, otherwise the request fails. + departure_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. The departure time. If you don't set this value, + then this value defaults to the time that you made the + request. NOTE: You can only specify a ``departure_time`` in + the past when + [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode] + is set to ``TRANSIT``. + arrival_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. The arrival time. NOTE: Can only be set when + [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode] + is set to ``TRANSIT``. You can specify either + ``departure_time`` or ``arrival_time``, but not both. + language_code (str): + Optional. The BCP-47 language code, such as "en-US" or + "sr-Latn". For more information, see `Unicode Locale + Identifier `__. + See `Language + Support `__ + for the list of supported languages. When you don't provide + this value, the display language is inferred from the + location of the first origin. + region_code (str): + Optional. The region code, specified as a ccTLD ("top-level + domain") two-character value. For more information see + `Country code top-level + domains `__. + units (google.maps.routing_v2.types.Units): + Optional. Specifies the units of measure for + the display fields. + extra_computations (MutableSequence[google.maps.routing_v2.types.ComputeRouteMatrixRequest.ExtraComputation]): + Optional. A list of extra computations which + may be used to complete the request. Note: These + extra computations may return extra fields on + the response. These extra fields must also be + specified in the field mask to be returned in + the response. + traffic_model (google.maps.routing_v2.types.TrafficModel): + Optional. Specifies the assumptions to use when calculating + time in traffic. This setting affects the value returned in + the duration field in the + [RouteMatrixElement][google.maps.routing.v2.RouteMatrixElement] + which contains the predicted time in traffic based on + historical averages. + [RoutingPreference][google.maps.routing.v2.RoutingPreference] + to ``TRAFFIC_AWARE_OPTIMAL`` and + [RouteTravelMode][google.maps.routing.v2.RouteTravelMode] to + ``DRIVE``. Defaults to ``BEST_GUESS`` if traffic is + requested and ``TrafficModel`` is not specified. + transit_preferences (google.maps.routing_v2.types.TransitPreferences): + Optional. Specifies preferences that influence the route + returned for ``TRANSIT`` routes. NOTE: You can only specify + a ``transit_preferences`` when + [RouteTravelMode][google.maps.routing.v2.RouteTravelMode] is + set to ``TRANSIT``. + """ + class ExtraComputation(proto.Enum): + r"""Extra computations to perform while completing the request. + + Values: + EXTRA_COMPUTATION_UNSPECIFIED (0): + Not used. Requests containing this value will + fail. + TOLLS (1): + Toll information for the matrix element(s). + """ + EXTRA_COMPUTATION_UNSPECIFIED = 0 + TOLLS = 1 + + origins: MutableSequence['RouteMatrixOrigin'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='RouteMatrixOrigin', + ) + destinations: MutableSequence['RouteMatrixDestination'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='RouteMatrixDestination', + ) + travel_mode: route_travel_mode.RouteTravelMode = proto.Field( + proto.ENUM, + number=3, + enum=route_travel_mode.RouteTravelMode, + ) + routing_preference: gmr_routing_preference.RoutingPreference = proto.Field( + proto.ENUM, + number=4, + enum=gmr_routing_preference.RoutingPreference, + ) + departure_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + arrival_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=11, + message=timestamp_pb2.Timestamp, + ) + language_code: str = proto.Field( + proto.STRING, + number=6, + ) + region_code: str = proto.Field( + proto.STRING, + number=9, + ) + units: gmr_units.Units = proto.Field( + proto.ENUM, + number=7, + enum=gmr_units.Units, + ) + extra_computations: MutableSequence[ExtraComputation] = proto.RepeatedField( + proto.ENUM, + number=8, + enum=ExtraComputation, + ) + traffic_model: gmr_traffic_model.TrafficModel = proto.Field( + proto.ENUM, + number=10, + enum=gmr_traffic_model.TrafficModel, + ) + transit_preferences: gmr_transit_preferences.TransitPreferences = proto.Field( + proto.MESSAGE, + number=12, + message=gmr_transit_preferences.TransitPreferences, + ) + + +class RouteMatrixOrigin(proto.Message): + r"""A single origin for ComputeRouteMatrixRequest + + Attributes: + waypoint (google.maps.routing_v2.types.Waypoint): + Required. Origin waypoint + route_modifiers (google.maps.routing_v2.types.RouteModifiers): + Optional. Modifiers for every route that + takes this as the origin + """ + + waypoint: gmr_waypoint.Waypoint = proto.Field( + proto.MESSAGE, + number=1, + message=gmr_waypoint.Waypoint, + ) + route_modifiers: gmr_route_modifiers.RouteModifiers = proto.Field( + proto.MESSAGE, + number=2, + message=gmr_route_modifiers.RouteModifiers, + ) + + +class RouteMatrixDestination(proto.Message): + r"""A single destination for ComputeRouteMatrixRequest + + Attributes: + waypoint (google.maps.routing_v2.types.Waypoint): + Required. Destination waypoint + """ + + waypoint: gmr_waypoint.Waypoint = proto.Field( + proto.MESSAGE, + number=1, + message=gmr_waypoint.Waypoint, + ) + + +class RouteMatrixElement(proto.Message): + r"""Contains route information computed for an origin/destination + pair in the ComputeRouteMatrix API. This proto can be streamed + to the client. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + origin_index (int): + Zero-based index of the origin in the + request. + + This field is a member of `oneof`_ ``_origin_index``. + destination_index (int): + Zero-based index of the destination in the + request. + + This field is a member of `oneof`_ ``_destination_index``. + status (google.rpc.status_pb2.Status): + Error status code for this element. + condition (google.maps.routing_v2.types.RouteMatrixElementCondition): + Indicates whether the route was found or not. + Independent of status. + distance_meters (int): + The travel distance of the route, in meters. + duration (google.protobuf.duration_pb2.Duration): + The length of time needed to navigate the route. If you set + the + [routing_preference][google.maps.routing.v2.ComputeRouteMatrixRequest.routing_preference] + to ``TRAFFIC_UNAWARE``, then this value is the same as + ``static_duration``. If you set the ``routing_preference`` + to either ``TRAFFIC_AWARE`` or ``TRAFFIC_AWARE_OPTIMAL``, + then this value is calculated taking traffic conditions into + account. + static_duration (google.protobuf.duration_pb2.Duration): + The duration of traveling through the route + without taking traffic conditions into + consideration. + travel_advisory (google.maps.routing_v2.types.RouteTravelAdvisory): + Additional information about the route. For + example: restriction information and toll + information + fallback_info (google.maps.routing_v2.types.FallbackInfo): + In some cases when the server is not able to + compute the route with the given preferences for + this particular origin/destination pair, it may + fall back to using a different mode of + computation. When fallback mode is used, this + field contains detailed information about the + fallback response. Otherwise this field is + unset. + localized_values (google.maps.routing_v2.types.RouteMatrixElement.LocalizedValues): + Text representations of properties of the + ``RouteMatrixElement``. + """ + + class LocalizedValues(proto.Message): + r"""Text representations of certain properties. + + Attributes: + distance (google.type.localized_text_pb2.LocalizedText): + Travel distance represented in text form. + duration (google.type.localized_text_pb2.LocalizedText): + Duration represented in text form taking traffic conditions + into consideration. Note: If traffic information was not + requested, this value is the same value as static_duration. + static_duration (google.type.localized_text_pb2.LocalizedText): + Duration represented in text form without + taking traffic conditions into consideration. + transit_fare (google.type.localized_text_pb2.LocalizedText): + Transit fare represented in text form. + """ + + distance: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=1, + message=localized_text_pb2.LocalizedText, + ) + duration: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=2, + message=localized_text_pb2.LocalizedText, + ) + static_duration: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=3, + message=localized_text_pb2.LocalizedText, + ) + transit_fare: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=4, + message=localized_text_pb2.LocalizedText, + ) + + origin_index: int = proto.Field( + proto.INT32, + number=1, + optional=True, + ) + destination_index: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + status: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=3, + message=status_pb2.Status, + ) + condition: 'RouteMatrixElementCondition' = proto.Field( + proto.ENUM, + number=9, + enum='RouteMatrixElementCondition', + ) + distance_meters: int = proto.Field( + proto.INT32, + number=4, + ) + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + static_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=6, + message=duration_pb2.Duration, + ) + travel_advisory: route.RouteTravelAdvisory = proto.Field( + proto.MESSAGE, + number=7, + message=route.RouteTravelAdvisory, + ) + fallback_info: gmr_fallback_info.FallbackInfo = proto.Field( + proto.MESSAGE, + number=8, + message=gmr_fallback_info.FallbackInfo, + ) + localized_values: LocalizedValues = proto.Field( + proto.MESSAGE, + number=10, + message=LocalizedValues, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py new file mode 100644 index 000000000000..a0bd24974a2d --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py @@ -0,0 +1,71 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.routing.v2', + manifest={ + 'RoutingPreference', + }, +) + + +class RoutingPreference(proto.Enum): + r"""A set of values that specify factors to take into + consideration when calculating the route. + + Values: + ROUTING_PREFERENCE_UNSPECIFIED (0): + No routing preference specified. Default to + ``TRAFFIC_UNAWARE``. + TRAFFIC_UNAWARE (1): + Computes routes without taking live traffic conditions into + consideration. Suitable when traffic conditions don't matter + or are not applicable. Using this value produces the lowest + latency. Note: For + [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode] + ``DRIVE`` and ``TWO_WHEELER``, the route and duration chosen + are based on road network and average time-independent + traffic conditions, not current road conditions. + Consequently, routes may include roads that are temporarily + closed. Results for a given request may vary over time due + to changes in the road network, updated average traffic + conditions, and the distributed nature of the service. + Results may also vary between nearly-equivalent routes at + any time or frequency. + TRAFFIC_AWARE (2): + Calculates routes taking live traffic conditions into + consideration. In contrast to ``TRAFFIC_AWARE_OPTIMAL``, + some optimizations are applied to significantly reduce + latency. + TRAFFIC_AWARE_OPTIMAL (3): + Calculates the routes taking live traffic + conditions into consideration, without applying + most performance optimizations. Using this value + produces the highest latency. + """ + ROUTING_PREFERENCE_UNSPECIFIED = 0 + TRAFFIC_UNAWARE = 1 + TRAFFIC_AWARE = 2 + TRAFFIC_AWARE_OPTIMAL = 3 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py new file mode 100644 index 000000000000..5ace8166d68d --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py @@ -0,0 +1,92 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.routing.v2', + manifest={ + 'SpeedReadingInterval', + }, +) + + +class SpeedReadingInterval(proto.Message): + r"""Traffic density indicator on a contiguous segment of a polyline or + path. Given a path with points P_0, P_1, ... , P_N (zero-based + index), the ``SpeedReadingInterval`` defines an interval and + describes its traffic using the following categories. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + start_polyline_point_index (int): + The starting index of this interval in the + polyline. + + This field is a member of `oneof`_ ``_start_polyline_point_index``. + end_polyline_point_index (int): + The ending index of this interval in the + polyline. + + This field is a member of `oneof`_ ``_end_polyline_point_index``. + speed (google.maps.routing_v2.types.SpeedReadingInterval.Speed): + Traffic speed in this interval. + + This field is a member of `oneof`_ ``speed_type``. + """ + class Speed(proto.Enum): + r"""The classification of polyline speed based on traffic data. + + Values: + SPEED_UNSPECIFIED (0): + Default value. This value is unused. + NORMAL (1): + Normal speed, no slowdown is detected. + SLOW (2): + Slowdown detected, but no traffic jam formed. + TRAFFIC_JAM (3): + Traffic jam detected. + """ + SPEED_UNSPECIFIED = 0 + NORMAL = 1 + SLOW = 2 + TRAFFIC_JAM = 3 + + start_polyline_point_index: int = proto.Field( + proto.INT32, + number=1, + optional=True, + ) + end_polyline_point_index: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + speed: Speed = proto.Field( + proto.ENUM, + number=3, + oneof='speed_type', + enum=Speed, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py new file mode 100644 index 000000000000..c6cf129bc732 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 money_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'TollInfo', + }, +) + + +class TollInfo(proto.Message): + r"""Encapsulates toll information on a + [``Route``][google.maps.routing.v2.Route] or on a + [``RouteLeg``][google.maps.routing.v2.RouteLeg]. + + Attributes: + estimated_price (MutableSequence[google.type.money_pb2.Money]): + The monetary amount of tolls for the corresponding + [``Route``][google.maps.routing.v2.Route] or + [``RouteLeg``][google.maps.routing.v2.RouteLeg]. This list + contains a money amount for each currency that is expected + to be charged by the toll stations. Typically this list will + contain only one item for routes with tolls in one currency. + For international trips, this list may contain multiple + items to reflect tolls in different currencies. + """ + + estimated_price: MutableSequence[money_pb2.Money] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=money_pb2.Money, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py new file mode 100644 index 000000000000..d0de0e8a78a8 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.routing.v2', + manifest={ + 'TollPass', + }, +) + + +class TollPass(proto.Enum): + r"""List of toll passes around the world that we support. + + Values: + TOLL_PASS_UNSPECIFIED (0): + Not used. If this value is used, then the + request fails. + AU_ETOLL_TAG (82): + Sydney toll pass. See additional details at + https://www.myetoll.com.au. + AU_EWAY_TAG (83): + Sydney toll pass. See additional details at + https://www.tollpay.com.au. + AU_LINKT (2): + Australia-wide toll pass. + See additional details at + https://www.linkt.com.au/. + AR_TELEPASE (3): + Argentina toll pass. See additional details + at https://telepase.com.ar + BR_AUTO_EXPRESO (81): + Brazil toll pass. See additional details at + https://www.autoexpreso.com + BR_CONECTCAR (7): + Brazil toll pass. See additional details at + https://conectcar.com. + BR_MOVE_MAIS (8): + Brazil toll pass. See additional details at + https://movemais.com. + BR_PASSA_RAPIDO (88): + Brazil toll pass. See additional details at + https://pasorapido.gob.do/ + BR_SEM_PARAR (9): + Brazil toll pass. See additional details at + https://www.semparar.com.br. + BR_TAGGY (10): + Brazil toll pass. See additional details at + https://taggy.com.br. + BR_VELOE (11): + Brazil toll pass. See additional details at + https://veloe.com.br/site/onde-usar. + CA_US_AKWASASNE_SEAWAY_CORPORATE_CARD (84): + Canada to United States border crossing. + CA_US_AKWASASNE_SEAWAY_TRANSIT_CARD (85): + Canada to United States border crossing. + CA_US_BLUE_WATER_EDGE_PASS (18): + Ontario, Canada to Michigan, United States + border crossing. + CA_US_CONNEXION (19): + Ontario, Canada to Michigan, United States + border crossing. + CA_US_NEXUS_CARD (20): + Canada to United States border crossing. + ID_E_TOLL (16): + Indonesia. + E-card provided by multiple banks used to pay + for tolls. All e-cards via banks are charged the + same so only one enum value is needed. E.g. + - Bank Mandiri + https://www.bankmandiri.co.id/e-money + - BCA https://www.bca.co.id/flazz + - BNI + https://www.bni.co.id/id-id/ebanking/tapcash + IN_FASTAG (78): + India. + IN_LOCAL_HP_PLATE_EXEMPT (79): + India, HP state plate exemption. + JP_ETC (98): + Japan + ETC. Electronic wireless system to collect + tolls. https://www.go-etc.jp/ + JP_ETC2 (99): + Japan + ETC2.0. New version of ETC with further discount + and bidirectional communication between devices + on vehicles and antennas on the road. + https://www.go-etc.jp/etc2/index.html + MX_IAVE (90): + Mexico toll pass. + https://iave.capufe.gob.mx/#/ + MX_PASE (91): + Mexico + https://www.pase.com.mx + MX_QUICKPASS (93): + Mexico + https://operadoravial.com/quick-pass/ + MX_SISTEMA_TELEPEAJE_CHIHUAHUA (89): + http://appsh.chihuahua.gob.mx/transparencia/?doc=/ingresos/TelepeajeFormato4.pdf + MX_TAG_IAVE (12): + Mexico + MX_TAG_TELEVIA (13): + Mexico toll pass company. One of many + operating in Mexico City. See additional details + at https://www.televia.com.mx. + MX_TELEVIA (92): + Mexico toll pass company. One of many + operating in Mexico City. + https://www.televia.com.mx + MX_VIAPASS (14): + Mexico toll pass. See additional details at + https://www.viapass.com.mx/viapass/web_home.aspx. + US_AL_FREEDOM_PASS (21): + AL, USA. + US_AK_ANTON_ANDERSON_TUNNEL_BOOK_OF_10_TICKETS (22): + AK, USA. + US_CA_FASTRAK (4): + CA, USA. + US_CA_FASTRAK_CAV_STICKER (86): + Indicates driver has any FasTrak pass in + addition to the DMV issued Clean Air Vehicle + (CAV) sticker. + https://www.bayareafastrak.org/en/guide/doINeedFlex.shtml + US_CO_EXPRESSTOLL (23): + CO, USA. + US_CO_GO_PASS (24): + CO, USA. + US_DE_EZPASSDE (25): + DE, USA. + US_FL_BOB_SIKES_TOLL_BRIDGE_PASS (65): + FL, USA. + US_FL_DUNES_COMMUNITY_DEVELOPMENT_DISTRICT_EXPRESSCARD (66): + FL, USA. + US_FL_EPASS (67): + FL, USA. + US_FL_GIBA_TOLL_PASS (68): + FL, USA. + US_FL_LEEWAY (69): + FL, USA. + US_FL_SUNPASS (70): + FL, USA. + US_FL_SUNPASS_PRO (71): + FL, USA. + US_IL_EZPASSIL (73): + IL, USA. + US_IL_IPASS (72): + IL, USA. + US_IN_EZPASSIN (26): + IN, USA. + US_KS_BESTPASS_HORIZON (27): + KS, USA. + US_KS_KTAG (28): + KS, USA. + US_KS_NATIONALPASS (29): + KS, USA. + US_KS_PREPASS_ELITEPASS (30): + KS, USA. + US_KY_RIVERLINK (31): + KY, USA. + US_LA_GEAUXPASS (32): + LA, USA. + US_LA_TOLL_TAG (33): + LA, USA. + US_MA_EZPASSMA (6): + MA, USA. + US_MD_EZPASSMD (34): + MD, USA. + US_ME_EZPASSME (35): + ME, USA. + US_MI_AMBASSADOR_BRIDGE_PREMIER_COMMUTER_CARD (36): + MI, USA. + US_MI_BCPASS (94): + MI, USA. + US_MI_GROSSE_ILE_TOLL_BRIDGE_PASS_TAG (37): + MI, USA. + US_MI_IQ_PROX_CARD (38): + MI, USA. + Deprecated as this pass type no longer exists. + US_MI_IQ_TAG (95): + MI, USA. + US_MI_MACKINAC_BRIDGE_MAC_PASS (39): + MI, USA. + US_MI_NEXPRESS_TOLL (40): + MI, USA. + US_MN_EZPASSMN (41): + MN, USA. + US_NC_EZPASSNC (42): + NC, USA. + US_NC_PEACH_PASS (87): + NC, USA. + US_NC_QUICK_PASS (43): + NC, USA. + US_NH_EZPASSNH (80): + NH, USA. + US_NJ_DOWNBEACH_EXPRESS_PASS (75): + NJ, USA. + US_NJ_EZPASSNJ (74): + NJ, USA. + US_NY_EXPRESSPASS (76): + NY, USA. + US_NY_EZPASSNY (77): + NY, USA. + US_OH_EZPASSOH (44): + OH, USA. + US_PA_EZPASSPA (45): + PA, USA. + US_RI_EZPASSRI (46): + RI, USA. + US_SC_PALPASS (47): + SC, USA. + US_TX_AVI_TAG (97): + TX, USA. + US_TX_BANCPASS (48): + TX, USA. + US_TX_DEL_RIO_PASS (49): + TX, USA. + US_TX_EFAST_PASS (50): + TX, USA. + US_TX_EAGLE_PASS_EXPRESS_CARD (51): + TX, USA. + US_TX_EPTOLL (52): + TX, USA. + US_TX_EZ_CROSS (53): + TX, USA. + US_TX_EZTAG (54): + TX, USA. + US_TX_FUEGO_TAG (96): + TX, USA. + US_TX_LAREDO_TRADE_TAG (55): + TX, USA. + US_TX_PLUSPASS (56): + TX, USA. + US_TX_TOLLTAG (57): + TX, USA. + US_TX_TXTAG (58): + TX, USA. + US_TX_XPRESS_CARD (59): + TX, USA. + US_UT_ADAMS_AVE_PARKWAY_EXPRESSCARD (60): + UT, USA. + US_VA_EZPASSVA (61): + VA, USA. + US_WA_BREEZEBY (17): + WA, USA. + US_WA_GOOD_TO_GO (1): + WA, USA. + US_WV_EZPASSWV (62): + WV, USA. + US_WV_MEMORIAL_BRIDGE_TICKETS (63): + WV, USA. + US_WV_MOV_PASS (100): + WV, USA + US_WV_NEWELL_TOLL_BRIDGE_TICKET (64): + WV, USA. + """ + TOLL_PASS_UNSPECIFIED = 0 + AU_ETOLL_TAG = 82 + AU_EWAY_TAG = 83 + AU_LINKT = 2 + AR_TELEPASE = 3 + BR_AUTO_EXPRESO = 81 + BR_CONECTCAR = 7 + BR_MOVE_MAIS = 8 + BR_PASSA_RAPIDO = 88 + BR_SEM_PARAR = 9 + BR_TAGGY = 10 + BR_VELOE = 11 + CA_US_AKWASASNE_SEAWAY_CORPORATE_CARD = 84 + CA_US_AKWASASNE_SEAWAY_TRANSIT_CARD = 85 + CA_US_BLUE_WATER_EDGE_PASS = 18 + CA_US_CONNEXION = 19 + CA_US_NEXUS_CARD = 20 + ID_E_TOLL = 16 + IN_FASTAG = 78 + IN_LOCAL_HP_PLATE_EXEMPT = 79 + JP_ETC = 98 + JP_ETC2 = 99 + MX_IAVE = 90 + MX_PASE = 91 + MX_QUICKPASS = 93 + MX_SISTEMA_TELEPEAJE_CHIHUAHUA = 89 + MX_TAG_IAVE = 12 + MX_TAG_TELEVIA = 13 + MX_TELEVIA = 92 + MX_VIAPASS = 14 + US_AL_FREEDOM_PASS = 21 + US_AK_ANTON_ANDERSON_TUNNEL_BOOK_OF_10_TICKETS = 22 + US_CA_FASTRAK = 4 + US_CA_FASTRAK_CAV_STICKER = 86 + US_CO_EXPRESSTOLL = 23 + US_CO_GO_PASS = 24 + US_DE_EZPASSDE = 25 + US_FL_BOB_SIKES_TOLL_BRIDGE_PASS = 65 + US_FL_DUNES_COMMUNITY_DEVELOPMENT_DISTRICT_EXPRESSCARD = 66 + US_FL_EPASS = 67 + US_FL_GIBA_TOLL_PASS = 68 + US_FL_LEEWAY = 69 + US_FL_SUNPASS = 70 + US_FL_SUNPASS_PRO = 71 + US_IL_EZPASSIL = 73 + US_IL_IPASS = 72 + US_IN_EZPASSIN = 26 + US_KS_BESTPASS_HORIZON = 27 + US_KS_KTAG = 28 + US_KS_NATIONALPASS = 29 + US_KS_PREPASS_ELITEPASS = 30 + US_KY_RIVERLINK = 31 + US_LA_GEAUXPASS = 32 + US_LA_TOLL_TAG = 33 + US_MA_EZPASSMA = 6 + US_MD_EZPASSMD = 34 + US_ME_EZPASSME = 35 + US_MI_AMBASSADOR_BRIDGE_PREMIER_COMMUTER_CARD = 36 + US_MI_BCPASS = 94 + US_MI_GROSSE_ILE_TOLL_BRIDGE_PASS_TAG = 37 + US_MI_IQ_PROX_CARD = 38 + US_MI_IQ_TAG = 95 + US_MI_MACKINAC_BRIDGE_MAC_PASS = 39 + US_MI_NEXPRESS_TOLL = 40 + US_MN_EZPASSMN = 41 + US_NC_EZPASSNC = 42 + US_NC_PEACH_PASS = 87 + US_NC_QUICK_PASS = 43 + US_NH_EZPASSNH = 80 + US_NJ_DOWNBEACH_EXPRESS_PASS = 75 + US_NJ_EZPASSNJ = 74 + US_NY_EXPRESSPASS = 76 + US_NY_EZPASSNY = 77 + US_OH_EZPASSOH = 44 + US_PA_EZPASSPA = 45 + US_RI_EZPASSRI = 46 + US_SC_PALPASS = 47 + US_TX_AVI_TAG = 97 + US_TX_BANCPASS = 48 + US_TX_DEL_RIO_PASS = 49 + US_TX_EFAST_PASS = 50 + US_TX_EAGLE_PASS_EXPRESS_CARD = 51 + US_TX_EPTOLL = 52 + US_TX_EZ_CROSS = 53 + US_TX_EZTAG = 54 + US_TX_FUEGO_TAG = 96 + US_TX_LAREDO_TRADE_TAG = 55 + US_TX_PLUSPASS = 56 + US_TX_TOLLTAG = 57 + US_TX_TXTAG = 58 + US_TX_XPRESS_CARD = 59 + US_UT_ADAMS_AVE_PARKWAY_EXPRESSCARD = 60 + US_VA_EZPASSVA = 61 + US_WA_BREEZEBY = 17 + US_WA_GOOD_TO_GO = 1 + US_WV_EZPASSWV = 62 + US_WV_MEMORIAL_BRIDGE_TICKETS = 63 + US_WV_MOV_PASS = 100 + US_WV_NEWELL_TOLL_BRIDGE_TICKET = 64 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/traffic_model.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/traffic_model.py new file mode 100644 index 000000000000..0f78d92f1f45 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/traffic_model.py @@ -0,0 +1,64 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.routing.v2', + manifest={ + 'TrafficModel', + }, +) + + +class TrafficModel(proto.Enum): + r"""Specifies the assumptions to use when calculating time in traffic. + This setting affects the value returned in the ``duration`` field in + the response, which contains the predicted time in traffic based on + historical averages. + + Values: + TRAFFIC_MODEL_UNSPECIFIED (0): + Unused. If specified, will default to ``BEST_GUESS``. + BEST_GUESS (1): + Indicates that the returned ``duration`` should be the best + estimate of travel time given what is known about both + historical traffic conditions and live traffic. Live traffic + becomes more important the closer the ``departure_time`` is + to now. + PESSIMISTIC (2): + Indicates that the returned duration should + be longer than the actual travel time on most + days, though occasional days with particularly + bad traffic conditions may exceed this value. + OPTIMISTIC (3): + Indicates that the returned duration should + be shorter than the actual travel time on most + days, though occasional days with particularly + good traffic conditions may be faster than this + value. + """ + TRAFFIC_MODEL_UNSPECIFIED = 0 + BEST_GUESS = 1 + PESSIMISTIC = 2 + OPTIMISTIC = 3 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/transit.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/transit.py new file mode 100644 index 000000000000..bfa6ba1e738e --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/transit.py @@ -0,0 +1,259 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.routing_v2.types import location as gmr_location +from google.type import localized_text_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'TransitAgency', + 'TransitLine', + 'TransitStop', + 'TransitVehicle', + }, +) + + +class TransitAgency(proto.Message): + r"""A transit agency that operates a transit line. + + Attributes: + name (str): + The name of this transit agency. + phone_number (str): + The transit agency's locale-specific + formatted phone number. + uri (str): + The transit agency's URI. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + phone_number: str = proto.Field( + proto.STRING, + number=2, + ) + uri: str = proto.Field( + proto.STRING, + number=3, + ) + + +class TransitLine(proto.Message): + r"""Contains information about the transit line used in this + step. + + Attributes: + agencies (MutableSequence[google.maps.routing_v2.types.TransitAgency]): + The transit agency (or agencies) that + operates this transit line. + name (str): + The full name of this transit line, For + example, "8 Avenue Local". + uri (str): + the URI for this transit line as provided by + the transit agency. + color (str): + The color commonly used in signage for this + line. Represented in hexadecimal. + icon_uri (str): + The URI for the icon associated with this + line. + name_short (str): + The short name of this transit line. This + name will normally be a line number, such as + "M7" or "355". + text_color (str): + The color commonly used in text on signage + for this line. Represented in hexadecimal. + vehicle (google.maps.routing_v2.types.TransitVehicle): + The type of vehicle that operates on this + transit line. + """ + + agencies: MutableSequence['TransitAgency'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='TransitAgency', + ) + name: str = proto.Field( + proto.STRING, + number=2, + ) + uri: str = proto.Field( + proto.STRING, + number=3, + ) + color: str = proto.Field( + proto.STRING, + number=4, + ) + icon_uri: str = proto.Field( + proto.STRING, + number=5, + ) + name_short: str = proto.Field( + proto.STRING, + number=6, + ) + text_color: str = proto.Field( + proto.STRING, + number=7, + ) + vehicle: 'TransitVehicle' = proto.Field( + proto.MESSAGE, + number=8, + message='TransitVehicle', + ) + + +class TransitStop(proto.Message): + r"""Information about a transit stop. + + Attributes: + name (str): + The name of the transit stop. + location (google.maps.routing_v2.types.Location): + The location of the stop expressed in + latitude/longitude coordinates. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + location: gmr_location.Location = proto.Field( + proto.MESSAGE, + number=2, + message=gmr_location.Location, + ) + + +class TransitVehicle(proto.Message): + r"""Information about a vehicle used in transit routes. + + Attributes: + name (google.type.localized_text_pb2.LocalizedText): + The name of this vehicle, capitalized. + type_ (google.maps.routing_v2.types.TransitVehicle.TransitVehicleType): + The type of vehicle used. + icon_uri (str): + The URI for an icon associated with this + vehicle type. + local_icon_uri (str): + The URI for the icon associated with this + vehicle type, based on the local transport + signage. + """ + class TransitVehicleType(proto.Enum): + r"""The type of vehicles for transit routes. + + Values: + TRANSIT_VEHICLE_TYPE_UNSPECIFIED (0): + Unused. + BUS (1): + Bus. + CABLE_CAR (2): + A vehicle that operates on a cable, usually on the ground. + Aerial cable cars may be of the type ``GONDOLA_LIFT``. + COMMUTER_TRAIN (3): + Commuter rail. + FERRY (4): + Ferry. + FUNICULAR (5): + A vehicle that is pulled up a steep incline + by a cable. A Funicular typically consists of + two cars, with each car acting as a + counterweight for the other. + GONDOLA_LIFT (6): + An aerial cable car. + HEAVY_RAIL (7): + Heavy rail. + HIGH_SPEED_TRAIN (8): + High speed train. + INTERCITY_BUS (9): + Intercity bus. + LONG_DISTANCE_TRAIN (10): + Long distance train. + METRO_RAIL (11): + Light rail transit. + MONORAIL (12): + Monorail. + OTHER (13): + All other vehicles. + RAIL (14): + Rail. + SHARE_TAXI (15): + Share taxi is a kind of bus with the ability + to drop off and pick up passengers anywhere on + its route. + SUBWAY (16): + Underground light rail. + TRAM (17): + Above ground light rail. + TROLLEYBUS (18): + Trolleybus. + """ + TRANSIT_VEHICLE_TYPE_UNSPECIFIED = 0 + BUS = 1 + CABLE_CAR = 2 + COMMUTER_TRAIN = 3 + FERRY = 4 + FUNICULAR = 5 + GONDOLA_LIFT = 6 + HEAVY_RAIL = 7 + HIGH_SPEED_TRAIN = 8 + INTERCITY_BUS = 9 + LONG_DISTANCE_TRAIN = 10 + METRO_RAIL = 11 + MONORAIL = 12 + OTHER = 13 + RAIL = 14 + SHARE_TAXI = 15 + SUBWAY = 16 + TRAM = 17 + TROLLEYBUS = 18 + + name: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=1, + message=localized_text_pb2.LocalizedText, + ) + type_: TransitVehicleType = proto.Field( + proto.ENUM, + number=2, + enum=TransitVehicleType, + ) + icon_uri: str = proto.Field( + proto.STRING, + number=3, + ) + local_icon_uri: str = proto.Field( + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/transit_preferences.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/transit_preferences.py new file mode 100644 index 000000000000..7786f8811da3 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/transit_preferences.py @@ -0,0 +1,97 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.routing.v2', + manifest={ + 'TransitPreferences', + }, +) + + +class TransitPreferences(proto.Message): + r"""Preferences for ``TRANSIT`` based routes that influence the route + that is returned. + + Attributes: + allowed_travel_modes (MutableSequence[google.maps.routing_v2.types.TransitPreferences.TransitTravelMode]): + A set of travel modes to use when getting a ``TRANSIT`` + route. Defaults to all supported modes of travel. + routing_preference (google.maps.routing_v2.types.TransitPreferences.TransitRoutingPreference): + A routing preference that, when specified, influences the + ``TRANSIT`` route returned. + """ + class TransitTravelMode(proto.Enum): + r"""A set of values used to specify the mode of transit. + + Values: + TRANSIT_TRAVEL_MODE_UNSPECIFIED (0): + No transit travel mode specified. + BUS (1): + Travel by bus. + SUBWAY (2): + Travel by subway. + TRAIN (3): + Travel by train. + LIGHT_RAIL (4): + Travel by light rail or tram. + RAIL (5): + Travel by rail. This is equivalent to a combination of + ``SUBWAY``, ``TRAIN``, and ``LIGHT_RAIL``. + """ + TRANSIT_TRAVEL_MODE_UNSPECIFIED = 0 + BUS = 1 + SUBWAY = 2 + TRAIN = 3 + LIGHT_RAIL = 4 + RAIL = 5 + + class TransitRoutingPreference(proto.Enum): + r"""Specifies routing preferences for transit routes. + + Values: + TRANSIT_ROUTING_PREFERENCE_UNSPECIFIED (0): + No preference specified. + LESS_WALKING (1): + Indicates that the calculated route should + prefer limited amounts of walking. + FEWER_TRANSFERS (2): + Indicates that the calculated route should + prefer a limited number of transfers. + """ + TRANSIT_ROUTING_PREFERENCE_UNSPECIFIED = 0 + LESS_WALKING = 1 + FEWER_TRANSFERS = 2 + + allowed_travel_modes: MutableSequence[TransitTravelMode] = proto.RepeatedField( + proto.ENUM, + number=1, + enum=TransitTravelMode, + ) + routing_preference: TransitRoutingPreference = proto.Field( + proto.ENUM, + number=2, + enum=TransitRoutingPreference, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py new file mode 100644 index 000000000000..911de7f76fd7 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.routing.v2', + manifest={ + 'Units', + }, +) + + +class Units(proto.Enum): + r"""A set of values that specify the unit of measure used in the + display. + + Values: + UNITS_UNSPECIFIED (0): + Units of measure not specified. Defaults to + the unit of measure inferred from the request. + METRIC (1): + Metric units of measure. + IMPERIAL (2): + Imperial (English) units of measure. + """ + UNITS_UNSPECIFIED = 0 + METRIC = 1 + IMPERIAL = 2 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py new file mode 100644 index 000000000000..9da25c5d86d9 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.routing.v2', + manifest={ + 'VehicleEmissionType', + }, +) + + +class VehicleEmissionType(proto.Enum): + r"""A set of values describing the vehicle's emission type. Applies only + to the ``DRIVE`` + [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode]. + + Values: + VEHICLE_EMISSION_TYPE_UNSPECIFIED (0): + No emission type specified. Default to ``GASOLINE``. + GASOLINE (1): + Gasoline/petrol fueled vehicle. + ELECTRIC (2): + Electricity powered vehicle. + HYBRID (3): + Hybrid fuel (such as gasoline + electric) + vehicle. + DIESEL (4): + Diesel fueled vehicle. + """ + VEHICLE_EMISSION_TYPE_UNSPECIFIED = 0 + GASOLINE = 1 + ELECTRIC = 2 + HYBRID = 3 + DIESEL = 4 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py new file mode 100644 index 000000000000..59b79853333c --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.routing_v2.types import vehicle_emission_type + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'VehicleInfo', + }, +) + + +class VehicleInfo(proto.Message): + r"""Contains the vehicle information, such as the vehicle + emission type. + + Attributes: + emission_type (google.maps.routing_v2.types.VehicleEmissionType): + Describes the vehicle's emission type. Applies only to the + ``DRIVE`` + [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode]. + """ + + emission_type: vehicle_emission_type.VehicleEmissionType = proto.Field( + proto.ENUM, + number=2, + enum=vehicle_emission_type.VehicleEmissionType, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py new file mode 100644 index 000000000000..d6748f9d6db3 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py @@ -0,0 +1,126 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.routing_v2.types import location as gmr_location + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'Waypoint', + }, +) + + +class Waypoint(proto.Message): + r"""Encapsulates a waypoint. Waypoints mark both the beginning + and end of a route, and include intermediate stops along the + route. + + 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 (google.maps.routing_v2.types.Location): + A point specified using geographic + coordinates, including an optional heading. + + This field is a member of `oneof`_ ``location_type``. + place_id (str): + The POI Place ID associated with the + waypoint. + + This field is a member of `oneof`_ ``location_type``. + address (str): + Human readable address or a plus code. + See https://plus.codes for details. + + This field is a member of `oneof`_ ``location_type``. + via (bool): + Marks this waypoint as a milestone rather a stopping point. + For each non-via waypoint in the request, the response + appends an entry to the + [``legs``][google.maps.routing.v2.Route.legs] array to + provide the details for stopovers on that leg of the trip. + Set this value to true when you want the route to pass + through this waypoint without stopping over. Via waypoints + don't cause an entry to be added to the ``legs`` array, but + they do route the journey through the waypoint. You can only + set this value on waypoints that are intermediates. The + request fails if you set this field on terminal waypoints. + If ``ComputeRoutesRequest.optimize_waypoint_order`` is set + to true then this field cannot be set to true; otherwise, + the request fails. + vehicle_stopover (bool): + Indicates that the waypoint is meant for vehicles to stop + at, where the intention is to either pickup or drop-off. + When you set this value, the calculated route won't include + non-\ ``via`` waypoints on roads that are unsuitable for + pickup and drop-off. This option works only for ``DRIVE`` + and ``TWO_WHEELER`` travel modes, and when the + ``location_type`` is + [``Location``][google.maps.routing.v2.Location]. + side_of_road (bool): + Indicates that the location of this waypoint is meant to + have a preference for the vehicle to stop at a particular + side of road. When you set this value, the route will pass + through the location so that the vehicle can stop at the + side of road that the location is biased towards from the + center of the road. This option works only for ``DRIVE`` and + ``TWO_WHEELER`` + [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode]. + """ + + location: gmr_location.Location = proto.Field( + proto.MESSAGE, + number=1, + oneof='location_type', + message=gmr_location.Location, + ) + place_id: str = proto.Field( + proto.STRING, + number=2, + oneof='location_type', + ) + address: str = proto.Field( + proto.STRING, + number=7, + oneof='location_type', + ) + via: bool = proto.Field( + proto.BOOL, + number=3, + ) + vehicle_stopover: bool = proto.Field( + proto.BOOL, + number=4, + ) + side_of_road: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/mypy.ini b/owl-bot-staging/google-maps-routing/v2/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-maps-routing/v2/noxfile.py b/owl-bot-staging/google-maps-routing/v2/noxfile.py new file mode 100644 index 000000000000..b99c4c5bb684 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/noxfile.py @@ -0,0 +1,280 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = 'google-maps-routing' + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.13" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "prerelease_deps", +] + +@nox.session(python=ALL_PYTHON) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def unit(session, protobuf_implementation): + """Run the unit test suite.""" + + 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+") + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") + + # 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") + + session.run( + 'py.test', + '--quiet', + '--cov=google/maps/routing_v2/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)), + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + +@nox.session(python=ALL_PYTHON[-1]) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def prerelease_deps(session, protobuf_implementation): + """Run the unit test suite against pre-release versions of dependencies.""" + + 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 test environment dependencies + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + + # Install the package without dependencies + session.install('-e', '.', '--no-deps') + + # We test the minimum dependency versions using the minimum Python + # version so the lowest python runtime that we test has a corresponding constraints + # file, located at `testing/constraints--.txt`, which contains all of the + # 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 + ) + ] + + session.install(*constraints_deps) + + prerel_deps = [ + "googleapis-common-protos", + "google-api-core", + "google-auth", + # Exclude grpcio!=1.67.0rc1 which does not support python 3.13 + "grpcio!=1.67.0rc1", + "grpcio-status", + "protobuf", + "proto-plus", + ] + + for dep in prerel_deps: + session.install("--pre", "--no-deps", "--upgrade", dep) + + # Remaining dependencies + other_deps = [ + "requests", + ] + session.install(*other_deps) + + # Print out prerelease package versions + + session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") + session.run("python", "-c", "import google.auth; print(google.auth.__version__)") + session.run("python", "-c", "import grpc; print(grpc.__version__)") + session.run( + "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" + ) + session.run( + "python", "-c", "import proto; print(proto.__version__)" + ) + + session.run( + 'py.test', + '--quiet', + '--cov=google/maps/routing_v2/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)), + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + + +@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=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 docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==7.0.1", "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=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", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py new file mode 100644 index 000000000000..f326b5e2134c --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ComputeRouteMatrix +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-routing + + +# [START routes_v2_generated_Routes_ComputeRouteMatrix_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.maps import routing_v2 + + +async def sample_compute_route_matrix(): + # Create a client + client = routing_v2.RoutesAsyncClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRouteMatrixRequest( + ) + + # Make the request + stream = await client.compute_route_matrix(request=request) + + # Handle the response + async for response in stream: + print(response) + +# [END routes_v2_generated_Routes_ComputeRouteMatrix_async] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py new file mode 100644 index 000000000000..9d1e1ae87791 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ComputeRouteMatrix +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-routing + + +# [START routes_v2_generated_Routes_ComputeRouteMatrix_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.maps import routing_v2 + + +def sample_compute_route_matrix(): + # Create a client + client = routing_v2.RoutesClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRouteMatrixRequest( + ) + + # Make the request + stream = client.compute_route_matrix(request=request) + + # Handle the response + for response in stream: + print(response) + +# [END routes_v2_generated_Routes_ComputeRouteMatrix_sync] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py new file mode 100644 index 000000000000..ba59057436a1 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ComputeRoutes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-routing + + +# [START routes_v2_generated_Routes_ComputeRoutes_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.maps import routing_v2 + + +async def sample_compute_routes(): + # Create a client + client = routing_v2.RoutesAsyncClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRoutesRequest( + ) + + # Make the request + response = await client.compute_routes(request=request) + + # Handle the response + print(response) + +# [END routes_v2_generated_Routes_ComputeRoutes_async] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py new file mode 100644 index 000000000000..49d835374e19 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ComputeRoutes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-routing + + +# [START routes_v2_generated_Routes_ComputeRoutes_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.maps import routing_v2 + + +def sample_compute_routes(): + # Create a client + client = routing_v2.RoutesClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRoutesRequest( + ) + + # Make the request + response = client.compute_routes(request=request) + + # Handle the response + print(response) + +# [END routes_v2_generated_Routes_ComputeRoutes_sync] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json new file mode 100644 index 000000000000..ebb0fa3e0c00 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json @@ -0,0 +1,321 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.maps.routing.v2", + "version": "v2" + } + ], + "language": "PYTHON", + "name": "google-maps-routing", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.routing_v2.RoutesAsyncClient", + "shortName": "RoutesAsyncClient" + }, + "fullName": "google.maps.routing_v2.RoutesAsyncClient.compute_route_matrix", + "method": { + "fullName": "google.maps.routing.v2.Routes.ComputeRouteMatrix", + "service": { + "fullName": "google.maps.routing.v2.Routes", + "shortName": "Routes" + }, + "shortName": "ComputeRouteMatrix" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.routing_v2.types.ComputeRouteMatrixRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "Iterable[google.maps.routing_v2.types.RouteMatrixElement]", + "shortName": "compute_route_matrix" + }, + "description": "Sample for ComputeRouteMatrix", + "file": "routes_v2_generated_routes_compute_route_matrix_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "routes_v2_generated_Routes_ComputeRouteMatrix_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": "routes_v2_generated_routes_compute_route_matrix_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.routing_v2.RoutesClient", + "shortName": "RoutesClient" + }, + "fullName": "google.maps.routing_v2.RoutesClient.compute_route_matrix", + "method": { + "fullName": "google.maps.routing.v2.Routes.ComputeRouteMatrix", + "service": { + "fullName": "google.maps.routing.v2.Routes", + "shortName": "Routes" + }, + "shortName": "ComputeRouteMatrix" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.routing_v2.types.ComputeRouteMatrixRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "Iterable[google.maps.routing_v2.types.RouteMatrixElement]", + "shortName": "compute_route_matrix" + }, + "description": "Sample for ComputeRouteMatrix", + "file": "routes_v2_generated_routes_compute_route_matrix_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "routes_v2_generated_Routes_ComputeRouteMatrix_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": "routes_v2_generated_routes_compute_route_matrix_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.routing_v2.RoutesAsyncClient", + "shortName": "RoutesAsyncClient" + }, + "fullName": "google.maps.routing_v2.RoutesAsyncClient.compute_routes", + "method": { + "fullName": "google.maps.routing.v2.Routes.ComputeRoutes", + "service": { + "fullName": "google.maps.routing.v2.Routes", + "shortName": "Routes" + }, + "shortName": "ComputeRoutes" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.routing_v2.types.ComputeRoutesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.maps.routing_v2.types.ComputeRoutesResponse", + "shortName": "compute_routes" + }, + "description": "Sample for ComputeRoutes", + "file": "routes_v2_generated_routes_compute_routes_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "routes_v2_generated_Routes_ComputeRoutes_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": "routes_v2_generated_routes_compute_routes_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.routing_v2.RoutesClient", + "shortName": "RoutesClient" + }, + "fullName": "google.maps.routing_v2.RoutesClient.compute_routes", + "method": { + "fullName": "google.maps.routing.v2.Routes.ComputeRoutes", + "service": { + "fullName": "google.maps.routing.v2.Routes", + "shortName": "Routes" + }, + "shortName": "ComputeRoutes" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.routing_v2.types.ComputeRoutesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.maps.routing_v2.types.ComputeRoutesResponse", + "shortName": "compute_routes" + }, + "description": "Sample for ComputeRoutes", + "file": "routes_v2_generated_routes_compute_routes_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "routes_v2_generated_Routes_ComputeRoutes_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": "routes_v2_generated_routes_compute_routes_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py b/owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py new file mode 100644 index 000000000000..8c26fc095087 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py @@ -0,0 +1,177 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 routingCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'compute_route_matrix': ('origins', 'destinations', 'travel_mode', 'routing_preference', 'departure_time', 'arrival_time', 'language_code', 'region_code', 'units', 'extra_computations', 'traffic_model', 'transit_preferences', ), + 'compute_routes': ('origin', 'destination', 'intermediates', 'travel_mode', 'routing_preference', 'polyline_quality', 'polyline_encoding', 'departure_time', 'arrival_time', 'compute_alternative_routes', 'route_modifiers', 'language_code', 'region_code', 'units', 'optimize_waypoint_order', 'requested_reference_routes', 'extra_computations', 'traffic_model', 'transit_preferences', ), + } + + 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=routingCallTransformer(), +): + """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 routing 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-maps-routing/v2/setup.py b/owl-bot-staging/google-maps-routing/v2/setup.py new file mode 100644 index 000000000000..4336dee44a87 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/setup.py @@ -0,0 +1,99 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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-maps-routing' + + +description = "Google Maps Routing API client library" + +version = None + +with open(os.path.join(package_root, 'google/maps/routing/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.0dev,!=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.0dev,!=2.24.0,!=2.25.0", + "proto-plus >= 1.22.3, <2.0.0dev", + "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'", + "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", + "google-geo-type >= 0.1.0, <1.0.0dev", +] +extras = { +} +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-routing" + +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-maps-routing/v2/testing/constraints-3.10.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.10.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/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-geo-type diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/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-geo-type diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/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-geo-type diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.13.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.13.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.13.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-geo-type diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt new file mode 100644 index 000000000000..277853c664a0 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/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.0dev", +# 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-geo-type==0.1.0 diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/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-geo-type diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/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-geo-type diff --git a/owl-bot-staging/google-maps-routing/v2/tests/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-maps-routing/v2/tests/unit/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-maps-routing/v2/tests/unit/gapic/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py new file mode 100644 index 000000000000..674acf72ee20 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py @@ -0,0 +1,2336 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.routing_v2.services.routes import RoutesAsyncClient +from google.maps.routing_v2.services.routes import RoutesClient +from google.maps.routing_v2.services.routes import transports +from google.maps.routing_v2.types import fallback_info +from google.maps.routing_v2.types import geocoding_results +from google.maps.routing_v2.types import location +from google.maps.routing_v2.types import polyline +from google.maps.routing_v2.types import route +from google.maps.routing_v2.types import route_modifiers +from google.maps.routing_v2.types import route_travel_mode +from google.maps.routing_v2.types import routes_service +from google.maps.routing_v2.types import routing_preference +from google.maps.routing_v2.types import toll_passes +from google.maps.routing_v2.types import traffic_model +from google.maps.routing_v2.types import transit_preferences +from google.maps.routing_v2.types import units +from google.maps.routing_v2.types import vehicle_emission_type +from google.maps.routing_v2.types import vehicle_info +from google.maps.routing_v2.types import waypoint +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore +import google.auth + + +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 RoutesClient._get_default_mtls_endpoint(None) is None + assert RoutesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert RoutesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert RoutesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert RoutesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert RoutesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert RoutesClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert RoutesClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert RoutesClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + RoutesClient._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 RoutesClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert RoutesClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert RoutesClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + RoutesClient._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 RoutesClient._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 RoutesClient._get_client_cert_source(None, False) is None + assert RoutesClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert RoutesClient._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 RoutesClient._get_client_cert_source(None, True) is mock_default_cert_source + assert RoutesClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(RoutesClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RoutesClient)) +@mock.patch.object(RoutesAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RoutesAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = RoutesClient._DEFAULT_UNIVERSE + default_endpoint = RoutesClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = RoutesClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert RoutesClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert RoutesClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == RoutesClient.DEFAULT_MTLS_ENDPOINT + assert RoutesClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert RoutesClient._get_api_endpoint(None, None, default_universe, "always") == RoutesClient.DEFAULT_MTLS_ENDPOINT + assert RoutesClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == RoutesClient.DEFAULT_MTLS_ENDPOINT + assert RoutesClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert RoutesClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + RoutesClient._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 RoutesClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert RoutesClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert RoutesClient._get_universe_domain(None, None) == RoutesClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + RoutesClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize("client_class,transport_name", [ + (RoutesClient, "grpc"), + (RoutesAsyncClient, "grpc_asyncio"), + (RoutesClient, "rest"), +]) +def test_routes_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 == ( + 'routes.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://routes.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.RoutesGrpcTransport, "grpc"), + (transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.RoutesRestTransport, "rest"), +]) +def test_routes_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", [ + (RoutesClient, "grpc"), + (RoutesAsyncClient, "grpc_asyncio"), + (RoutesClient, "rest"), +]) +def test_routes_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 == ( + 'routes.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://routes.googleapis.com' + ) + + +def test_routes_client_get_transport_class(): + transport = RoutesClient.get_transport_class() + available_transports = [ + transports.RoutesGrpcTransport, + transports.RoutesRestTransport, + ] + assert transport in available_transports + + transport = RoutesClient.get_transport_class("grpc") + assert transport == transports.RoutesGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (RoutesClient, transports.RoutesGrpcTransport, "grpc"), + (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio"), + (RoutesClient, transports.RoutesRestTransport, "rest"), +]) +@mock.patch.object(RoutesClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RoutesClient)) +@mock.patch.object(RoutesAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RoutesAsyncClient)) +def test_routes_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(RoutesClient, '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(RoutesClient, '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", [ + (RoutesClient, transports.RoutesGrpcTransport, "grpc", "true"), + (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (RoutesClient, transports.RoutesGrpcTransport, "grpc", "false"), + (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (RoutesClient, transports.RoutesRestTransport, "rest", "true"), + (RoutesClient, transports.RoutesRestTransport, "rest", "false"), +]) +@mock.patch.object(RoutesClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RoutesClient)) +@mock.patch.object(RoutesAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RoutesAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_routes_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", [ + RoutesClient, RoutesAsyncClient +]) +@mock.patch.object(RoutesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesClient)) +@mock.patch.object(RoutesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesAsyncClient)) +def test_routes_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", [ + RoutesClient, RoutesAsyncClient +]) +@mock.patch.object(RoutesClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RoutesClient)) +@mock.patch.object(RoutesAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RoutesAsyncClient)) +def test_routes_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = RoutesClient._DEFAULT_UNIVERSE + default_endpoint = RoutesClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = RoutesClient._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", [ + (RoutesClient, transports.RoutesGrpcTransport, "grpc"), + (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio"), + (RoutesClient, transports.RoutesRestTransport, "rest"), +]) +def test_routes_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", [ + (RoutesClient, transports.RoutesGrpcTransport, "grpc", grpc_helpers), + (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (RoutesClient, transports.RoutesRestTransport, "rest", None), +]) +def test_routes_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_routes_client_client_options_from_dict(): + with mock.patch('google.maps.routing_v2.services.routes.transports.RoutesGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = RoutesClient( + 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", [ + (RoutesClient, transports.RoutesGrpcTransport, "grpc", grpc_helpers), + (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_routes_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( + "routes.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( +), + scopes=None, + default_host="routes.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + routes_service.ComputeRoutesRequest, + dict, +]) +def test_compute_routes(request_type, transport: str = 'grpc'): + client = RoutesClient( + 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.compute_routes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = routes_service.ComputeRoutesResponse( + ) + response = client.compute_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = routes_service.ComputeRoutesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, routes_service.ComputeRoutesResponse) + + +def test_compute_routes_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 = RoutesClient( + 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 = routes_service.ComputeRoutesRequest( + language_code='language_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.compute_routes), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.compute_routes(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == routes_service.ComputeRoutesRequest( + language_code='language_code_value', + region_code='region_code_value', + ) + +def test_compute_routes_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RoutesClient( + 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.compute_routes in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.compute_routes] = mock_rpc + request = {} + client.compute_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.compute_routes(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_compute_routes_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = RoutesAsyncClient( + 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.compute_routes in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.compute_routes] = mock_rpc + + request = {} + await client.compute_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.compute_routes(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_compute_routes_async(transport: str = 'grpc_asyncio', request_type=routes_service.ComputeRoutesRequest): + client = RoutesAsyncClient( + 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.compute_routes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(routes_service.ComputeRoutesResponse( + )) + response = await client.compute_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = routes_service.ComputeRoutesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, routes_service.ComputeRoutesResponse) + + +@pytest.mark.asyncio +async def test_compute_routes_async_from_dict(): + await test_compute_routes_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + routes_service.ComputeRouteMatrixRequest, + dict, +]) +def test_compute_route_matrix(request_type, transport: str = 'grpc'): + client = RoutesClient( + 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.compute_route_matrix), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = iter([routes_service.RouteMatrixElement()]) + response = client.compute_route_matrix(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = routes_service.ComputeRouteMatrixRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + for message in response: + assert isinstance(message, routes_service.RouteMatrixElement) + + +def test_compute_route_matrix_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 = RoutesClient( + 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 = routes_service.ComputeRouteMatrixRequest( + language_code='language_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.compute_route_matrix), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.compute_route_matrix(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == routes_service.ComputeRouteMatrixRequest( + language_code='language_code_value', + region_code='region_code_value', + ) + +def test_compute_route_matrix_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RoutesClient( + 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.compute_route_matrix in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.compute_route_matrix] = mock_rpc + request = {} + client.compute_route_matrix(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.compute_route_matrix(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_compute_route_matrix_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = RoutesAsyncClient( + 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.compute_route_matrix in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.compute_route_matrix] = mock_rpc + + request = {} + await client.compute_route_matrix(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.compute_route_matrix(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_compute_route_matrix_async(transport: str = 'grpc_asyncio', request_type=routes_service.ComputeRouteMatrixRequest): + client = RoutesAsyncClient( + 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.compute_route_matrix), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True) + call.return_value.read = mock.AsyncMock(side_effect=[routes_service.RouteMatrixElement()]) + response = await client.compute_route_matrix(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = routes_service.ComputeRouteMatrixRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + message = await response.read() + assert isinstance(message, routes_service.RouteMatrixElement) + + +@pytest.mark.asyncio +async def test_compute_route_matrix_async_from_dict(): + await test_compute_route_matrix_async(request_type=dict) + + +def test_compute_routes_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 = RoutesClient( + 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.compute_routes in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.compute_routes] = mock_rpc + + request = {} + client.compute_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.compute_routes(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_compute_routes_rest_required_fields(request_type=routes_service.ComputeRoutesRequest): + transport_class = transports.RoutesRestTransport + + 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()).compute_routes._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()).compute_routes._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = routes_service.ComputeRoutesResponse() + # 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 = routes_service.ComputeRoutesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.compute_routes(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_compute_routes_rest_unset_required_fields(): + transport = transports.RoutesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.compute_routes._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("origin", "destination", ))) + + +def test_compute_route_matrix_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 = RoutesClient( + 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.compute_route_matrix in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.compute_route_matrix] = mock_rpc + + request = {} + client.compute_route_matrix(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.compute_route_matrix(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_compute_route_matrix_rest_required_fields(request_type=routes_service.ComputeRouteMatrixRequest): + transport_class = transports.RoutesRestTransport + + 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()).compute_route_matrix._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()).compute_route_matrix._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = routes_service.RouteMatrixElement() + # 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 = routes_service.RouteMatrixElement.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + json_return_value = "[{}]".format(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"} + + with mock.patch.object(response_value, 'iter_content') as iter_content: + iter_content.return_value = iter(json_return_value) + response = client.compute_route_matrix(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_compute_route_matrix_rest_unset_required_fields(): + transport = transports.RoutesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.compute_route_matrix._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("origins", "destinations", ))) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.RoutesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.RoutesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RoutesClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.RoutesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RoutesClient( + 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 = RoutesClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.RoutesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RoutesClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.RoutesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = RoutesClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.RoutesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.RoutesGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.RoutesGrpcTransport, + transports.RoutesGrpcAsyncIOTransport, + transports.RoutesRestTransport, +]) +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 = RoutesClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = RoutesClient( + 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_compute_routes_empty_call_grpc(): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.compute_routes), + '__call__') as call: + call.return_value = routes_service.ComputeRoutesResponse() + client.compute_routes(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = routes_service.ComputeRoutesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_compute_route_matrix_empty_call_grpc(): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.compute_route_matrix), + '__call__') as call: + call.return_value = iter([routes_service.RouteMatrixElement()]) + client.compute_route_matrix(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = routes_service.ComputeRouteMatrixRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = RoutesAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = RoutesAsyncClient( + 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_compute_routes_empty_call_grpc_asyncio(): + client = RoutesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.compute_routes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(routes_service.ComputeRoutesResponse( + )) + await client.compute_routes(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = routes_service.ComputeRoutesRequest() + + assert args[0] == request_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_compute_route_matrix_empty_call_grpc_asyncio(): + client = RoutesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.compute_route_matrix), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True) + call.return_value.read = mock.AsyncMock(side_effect=[routes_service.RouteMatrixElement()]) + await client.compute_route_matrix(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = routes_service.ComputeRouteMatrixRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = RoutesClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_compute_routes_rest_bad_request(request_type=routes_service.ComputeRoutesRequest): + client = RoutesClient( + 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.compute_routes(request) + + +@pytest.mark.parametrize("request_type", [ + routes_service.ComputeRoutesRequest, + dict, +]) +def test_compute_routes_rest_call_success(request_type): + client = RoutesClient( + 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 = routes_service.ComputeRoutesResponse( + ) + + # 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 = routes_service.ComputeRoutesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.compute_routes(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, routes_service.ComputeRoutesResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_compute_routes_rest_interceptors(null_interceptor): + transport = transports.RoutesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RoutesRestInterceptor(), + ) + client = RoutesClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RoutesRestInterceptor, "post_compute_routes") as post, \ + mock.patch.object(transports.RoutesRestInterceptor, "pre_compute_routes") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = routes_service.ComputeRoutesRequest.pb(routes_service.ComputeRoutesRequest()) + 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 = routes_service.ComputeRoutesResponse.to_json(routes_service.ComputeRoutesResponse()) + req.return_value.content = return_value + + request = routes_service.ComputeRoutesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = routes_service.ComputeRoutesResponse() + + client.compute_routes(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_compute_route_matrix_rest_bad_request(request_type=routes_service.ComputeRouteMatrixRequest): + client = RoutesClient( + 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.compute_route_matrix(request) + + +@pytest.mark.parametrize("request_type", [ + routes_service.ComputeRouteMatrixRequest, + dict, +]) +def test_compute_route_matrix_rest_call_success(request_type): + client = RoutesClient( + 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 = routes_service.RouteMatrixElement( + origin_index=1279, + destination_index=1817, + condition=routes_service.RouteMatrixElementCondition.ROUTE_EXISTS, + distance_meters=1594, + ) + + # 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 = routes_service.RouteMatrixElement.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + json_return_value = "[{}]".format(json_return_value) + response_value.iter_content = mock.Mock(return_value=iter(json_return_value)) + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.compute_route_matrix(request) + + assert isinstance(response, Iterable) + response = next(response) + + # Establish that the response is the type that we expect. + assert isinstance(response, routes_service.RouteMatrixElement) + assert response.origin_index == 1279 + assert response.destination_index == 1817 + assert response.condition == routes_service.RouteMatrixElementCondition.ROUTE_EXISTS + assert response.distance_meters == 1594 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_compute_route_matrix_rest_interceptors(null_interceptor): + transport = transports.RoutesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RoutesRestInterceptor(), + ) + client = RoutesClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RoutesRestInterceptor, "post_compute_route_matrix") as post, \ + mock.patch.object(transports.RoutesRestInterceptor, "pre_compute_route_matrix") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = routes_service.ComputeRouteMatrixRequest.pb(routes_service.ComputeRouteMatrixRequest()) + 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 = routes_service.RouteMatrixElement.to_json(routes_service.RouteMatrixElement()) + req.return_value.iter_content = mock.Mock(return_value=iter(return_value)) + + request = routes_service.ComputeRouteMatrixRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = routes_service.RouteMatrixElement() + + client.compute_route_matrix(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + +def test_initialize_client_w_rest(): + client = RoutesClient( + 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_compute_routes_empty_call_rest(): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.compute_routes), + '__call__') as call: + client.compute_routes(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = routes_service.ComputeRoutesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_compute_route_matrix_empty_call_rest(): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.compute_route_matrix), + '__call__') as call: + client.compute_route_matrix(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = routes_service.ComputeRouteMatrixRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.RoutesGrpcTransport, + ) + +def test_routes_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.RoutesTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_routes_base_transport(): + # Instantiate the base transport. + with mock.patch('google.maps.routing_v2.services.routes.transports.RoutesTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.RoutesTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'compute_routes', + 'compute_route_matrix', + ) + 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_routes_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.maps.routing_v2.services.routes.transports.RoutesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RoutesTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( +), + quota_project_id="octopus", + ) + + +def test_routes_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.maps.routing_v2.services.routes.transports.RoutesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RoutesTransport() + adc.assert_called_once() + + +def test_routes_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) + RoutesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RoutesGrpcTransport, + transports.RoutesGrpcAsyncIOTransport, + ], +) +def test_routes_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=(), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RoutesGrpcTransport, + transports.RoutesGrpcAsyncIOTransport, + transports.RoutesRestTransport, + ], +) +def test_routes_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.RoutesGrpcTransport, grpc_helpers), + (transports.RoutesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_routes_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( + "routes.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( +), + scopes=["1", "2"], + default_host="routes.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.RoutesGrpcTransport, transports.RoutesGrpcAsyncIOTransport]) +def test_routes_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_routes_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.RoutesRestTransport ( + 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_routes_host_no_port(transport_name): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='routes.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'routes.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://routes.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_routes_host_with_port(transport_name): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='routes.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'routes.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://routes.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_routes_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = RoutesClient( + credentials=creds1, + transport=transport_name, + ) + client2 = RoutesClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.compute_routes._session + session2 = client2.transport.compute_routes._session + assert session1 != session2 + session1 = client1.transport.compute_route_matrix._session + session2 = client2.transport.compute_route_matrix._session + assert session1 != session2 +def test_routes_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.RoutesGrpcTransport( + 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_routes_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.RoutesGrpcAsyncIOTransport( + 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.RoutesGrpcTransport, transports.RoutesGrpcAsyncIOTransport]) +def test_routes_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.RoutesGrpcTransport, transports.RoutesGrpcAsyncIOTransport]) +def test_routes_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_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = RoutesClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = RoutesClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = RoutesClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = RoutesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = RoutesClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = RoutesClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = RoutesClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = RoutesClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = RoutesClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = RoutesClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = RoutesClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = RoutesClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = RoutesClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = RoutesClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = RoutesClient.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.RoutesTransport, '_prep_wrapped_messages') as prep: + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.RoutesTransport, '_prep_wrapped_messages') as prep: + transport_class = RoutesClient.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 = RoutesClient( + 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 = RoutesAsyncClient( + 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 = RoutesClient( + 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 = RoutesClient( + 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", [ + (RoutesClient, transports.RoutesGrpcTransport), + (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport), +]) +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-maps-solar/v1/.coveragerc b/owl-bot-staging/google-maps-solar/v1/.coveragerc new file mode 100644 index 000000000000..ad069738e9cd --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/maps/solar/__init__.py + google/maps/solar/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-maps-solar/v1/.flake8 b/owl-bot-staging/google-maps-solar/v1/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/google-maps-solar/v1/MANIFEST.in b/owl-bot-staging/google-maps-solar/v1/MANIFEST.in new file mode 100644 index 000000000000..3a3118ae37a3 --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/maps/solar *.py +recursive-include google/maps/solar_v1 *.py diff --git a/owl-bot-staging/google-maps-solar/v1/README.rst b/owl-bot-staging/google-maps-solar/v1/README.rst new file mode 100644 index 000000000000..dc40707ede3b --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Maps Solar 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 Maps Solar 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 diff --git a/owl-bot-staging/google-maps-solar/v1/docs/_static/custom.css b/owl-bot-staging/google-maps-solar/v1/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-maps-solar/v1/docs/conf.py b/owl-bot-staging/google-maps-solar/v1/docs/conf.py new file mode 100644 index 000000000000..f01c97e24b0b --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-maps-solar 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("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# 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.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +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-maps-solar" +copyright = u"2023, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# 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 = 'en' + +# 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"] + +# 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 Maps Client Libraries for Python", + "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-maps-solar-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-maps-solar.tex", + u"google-maps-solar 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-maps-solar", + u"Google Maps Solar 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-maps-solar", + u"google-maps-solar Documentation", + author, + "google-maps-solar", + "GAPIC library for Google Maps Solar API", + "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": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", 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-maps-solar/v1/docs/index.rst b/owl-bot-staging/google-maps-solar/v1/docs/index.rst new file mode 100644 index 000000000000..ac524abe54c3 --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + solar_v1/services_ + solar_v1/types_ diff --git a/owl-bot-staging/google-maps-solar/v1/docs/solar_v1/services_.rst b/owl-bot-staging/google-maps-solar/v1/docs/solar_v1/services_.rst new file mode 100644 index 000000000000..e8894bb30331 --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/docs/solar_v1/services_.rst @@ -0,0 +1,6 @@ +Services for Google Maps Solar v1 API +===================================== +.. toctree:: + :maxdepth: 2 + + solar diff --git a/owl-bot-staging/google-maps-solar/v1/docs/solar_v1/solar.rst b/owl-bot-staging/google-maps-solar/v1/docs/solar_v1/solar.rst new file mode 100644 index 000000000000..d50d0f6cb877 --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/docs/solar_v1/solar.rst @@ -0,0 +1,6 @@ +Solar +----------------------- + +.. automodule:: google.maps.solar_v1.services.solar + :members: + :inherited-members: diff --git a/owl-bot-staging/google-maps-solar/v1/docs/solar_v1/types_.rst b/owl-bot-staging/google-maps-solar/v1/docs/solar_v1/types_.rst new file mode 100644 index 000000000000..04d6a941fd87 --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/docs/solar_v1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Maps Solar v1 API +================================== + +.. automodule:: google.maps.solar_v1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-maps-solar/v1/google/maps/solar/__init__.py b/owl-bot-staging/google-maps-solar/v1/google/maps/solar/__init__.py new file mode 100644 index 000000000000..f715b18cb2e9 --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/google/maps/solar/__init__.py @@ -0,0 +1,69 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.solar import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.maps.solar_v1.services.solar.client import SolarClient +from google.maps.solar_v1.services.solar.async_client import SolarAsyncClient + +from google.maps.solar_v1.types.solar_service import BuildingInsights +from google.maps.solar_v1.types.solar_service import CashPurchaseSavings +from google.maps.solar_v1.types.solar_service import DataLayers +from google.maps.solar_v1.types.solar_service import FinancedPurchaseSavings +from google.maps.solar_v1.types.solar_service import FinancialAnalysis +from google.maps.solar_v1.types.solar_service import FinancialDetails +from google.maps.solar_v1.types.solar_service import FindClosestBuildingInsightsRequest +from google.maps.solar_v1.types.solar_service import GetDataLayersRequest +from google.maps.solar_v1.types.solar_service import GetGeoTiffRequest +from google.maps.solar_v1.types.solar_service import LatLngBox +from google.maps.solar_v1.types.solar_service import LeasingSavings +from google.maps.solar_v1.types.solar_service import RoofSegmentSizeAndSunshineStats +from google.maps.solar_v1.types.solar_service import RoofSegmentSummary +from google.maps.solar_v1.types.solar_service import SavingsOverTime +from google.maps.solar_v1.types.solar_service import SizeAndSunshineStats +from google.maps.solar_v1.types.solar_service import SolarPanel +from google.maps.solar_v1.types.solar_service import SolarPanelConfig +from google.maps.solar_v1.types.solar_service import SolarPotential +from google.maps.solar_v1.types.solar_service import DataLayerView +from google.maps.solar_v1.types.solar_service import ImageryQuality +from google.maps.solar_v1.types.solar_service import SolarPanelOrientation + +__all__ = ('SolarClient', + 'SolarAsyncClient', + 'BuildingInsights', + 'CashPurchaseSavings', + 'DataLayers', + 'FinancedPurchaseSavings', + 'FinancialAnalysis', + 'FinancialDetails', + 'FindClosestBuildingInsightsRequest', + 'GetDataLayersRequest', + 'GetGeoTiffRequest', + 'LatLngBox', + 'LeasingSavings', + 'RoofSegmentSizeAndSunshineStats', + 'RoofSegmentSummary', + 'SavingsOverTime', + 'SizeAndSunshineStats', + 'SolarPanel', + 'SolarPanelConfig', + 'SolarPotential', + 'DataLayerView', + 'ImageryQuality', + 'SolarPanelOrientation', +) diff --git a/owl-bot-staging/google-maps-solar/v1/google/maps/solar/gapic_version.py b/owl-bot-staging/google-maps-solar/v1/google/maps/solar/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/google/maps/solar/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-maps-solar/v1/google/maps/solar/py.typed b/owl-bot-staging/google-maps-solar/v1/google/maps/solar/py.typed new file mode 100644 index 000000000000..9203ebe476fb --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/google/maps/solar/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-maps-solar package uses inline types. diff --git a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/__init__.py b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/__init__.py new file mode 100644 index 000000000000..09b279b6c567 --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/__init__.py @@ -0,0 +1,70 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.solar_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.solar import SolarClient +from .services.solar import SolarAsyncClient + +from .types.solar_service import BuildingInsights +from .types.solar_service import CashPurchaseSavings +from .types.solar_service import DataLayers +from .types.solar_service import FinancedPurchaseSavings +from .types.solar_service import FinancialAnalysis +from .types.solar_service import FinancialDetails +from .types.solar_service import FindClosestBuildingInsightsRequest +from .types.solar_service import GetDataLayersRequest +from .types.solar_service import GetGeoTiffRequest +from .types.solar_service import LatLngBox +from .types.solar_service import LeasingSavings +from .types.solar_service import RoofSegmentSizeAndSunshineStats +from .types.solar_service import RoofSegmentSummary +from .types.solar_service import SavingsOverTime +from .types.solar_service import SizeAndSunshineStats +from .types.solar_service import SolarPanel +from .types.solar_service import SolarPanelConfig +from .types.solar_service import SolarPotential +from .types.solar_service import DataLayerView +from .types.solar_service import ImageryQuality +from .types.solar_service import SolarPanelOrientation + +__all__ = ( + 'SolarAsyncClient', +'BuildingInsights', +'CashPurchaseSavings', +'DataLayerView', +'DataLayers', +'FinancedPurchaseSavings', +'FinancialAnalysis', +'FinancialDetails', +'FindClosestBuildingInsightsRequest', +'GetDataLayersRequest', +'GetGeoTiffRequest', +'ImageryQuality', +'LatLngBox', +'LeasingSavings', +'RoofSegmentSizeAndSunshineStats', +'RoofSegmentSummary', +'SavingsOverTime', +'SizeAndSunshineStats', +'SolarClient', +'SolarPanel', +'SolarPanelConfig', +'SolarPanelOrientation', +'SolarPotential', +) diff --git a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/gapic_metadata.json b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/gapic_metadata.json new file mode 100644 index 000000000000..d829bb1e665f --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/gapic_metadata.json @@ -0,0 +1,73 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.maps.solar_v1", + "protoPackage": "google.maps.solar.v1", + "schema": "1.0", + "services": { + "Solar": { + "clients": { + "grpc": { + "libraryClient": "SolarClient", + "rpcs": { + "FindClosestBuildingInsights": { + "methods": [ + "find_closest_building_insights" + ] + }, + "GetDataLayers": { + "methods": [ + "get_data_layers" + ] + }, + "GetGeoTiff": { + "methods": [ + "get_geo_tiff" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SolarAsyncClient", + "rpcs": { + "FindClosestBuildingInsights": { + "methods": [ + "find_closest_building_insights" + ] + }, + "GetDataLayers": { + "methods": [ + "get_data_layers" + ] + }, + "GetGeoTiff": { + "methods": [ + "get_geo_tiff" + ] + } + } + }, + "rest": { + "libraryClient": "SolarClient", + "rpcs": { + "FindClosestBuildingInsights": { + "methods": [ + "find_closest_building_insights" + ] + }, + "GetDataLayers": { + "methods": [ + "get_data_layers" + ] + }, + "GetGeoTiff": { + "methods": [ + "get_geo_tiff" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/gapic_version.py b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-maps-solar/v1/google/maps/solar_v1/py.typed b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/py.typed new file mode 100644 index 000000000000..9203ebe476fb --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-maps-solar package uses inline types. diff --git a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/__init__.py b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-maps-solar/v1/google/maps/solar_v1/services/solar/__init__.py b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/__init__.py new file mode 100644 index 000000000000..860c1815c59b --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 SolarClient +from .async_client import SolarAsyncClient + +__all__ = ( + 'SolarClient', + 'SolarAsyncClient', +) diff --git a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/async_client.py b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/async_client.py new file mode 100644 index 000000000000..2c7eece887bb --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/async_client.py @@ -0,0 +1,549 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.solar_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 + + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.maps.solar_v1.types import solar_service +from google.protobuf import any_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore +from .transports.base import SolarTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import SolarGrpcAsyncIOTransport +from .client import SolarClient + +try: + from google.api_core import client_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 SolarAsyncClient: + """Service definition for the Solar API.""" + + _client: SolarClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = SolarClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SolarClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = SolarClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = SolarClient._DEFAULT_UNIVERSE + + common_billing_account_path = staticmethod(SolarClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(SolarClient.parse_common_billing_account_path) + common_folder_path = staticmethod(SolarClient.common_folder_path) + parse_common_folder_path = staticmethod(SolarClient.parse_common_folder_path) + common_organization_path = staticmethod(SolarClient.common_organization_path) + parse_common_organization_path = staticmethod(SolarClient.parse_common_organization_path) + common_project_path = staticmethod(SolarClient.common_project_path) + parse_common_project_path = staticmethod(SolarClient.parse_common_project_path) + common_location_path = staticmethod(SolarClient.common_location_path) + parse_common_location_path = staticmethod(SolarClient.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: + SolarAsyncClient: The constructed client. + """ + return SolarClient.from_service_account_info.__func__(SolarAsyncClient, 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: + SolarAsyncClient: The constructed client. + """ + return SolarClient.from_service_account_file.__func__(SolarAsyncClient, 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 SolarClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> SolarTransport: + """Returns the transport used by the client instance. + + Returns: + SolarTransport: 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 = SolarClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, SolarTransport, Callable[..., SolarTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the solar 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,SolarTransport,Callable[..., SolarTransport]]]): + 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 SolarTransport 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 = SolarClient( + 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.maps.solar_v1.SolarAsyncClient`.", + extra = { + "serviceName": "google.maps.solar.v1.Solar", + "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.maps.solar.v1.Solar", + "credentialsType": None, + } + ) + + async def find_closest_building_insights(self, + request: Optional[Union[solar_service.FindClosestBuildingInsightsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> solar_service.BuildingInsights: + r"""Locates the closest building to a query point. Returns an error + with code ``NOT_FOUND`` if there are no buildings within + approximately 50m of the query point. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import solar_v1 + + async def sample_find_closest_building_insights(): + # Create a client + client = solar_v1.SolarAsyncClient() + + # Initialize request argument(s) + request = solar_v1.FindClosestBuildingInsightsRequest( + ) + + # Make the request + response = await client.find_closest_building_insights(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.solar_v1.types.FindClosestBuildingInsightsRequest, dict]]): + The request object. Request message for + ``Solar.FindClosestBuildingInsights``. + 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.maps.solar_v1.types.BuildingInsights: + Response message for Solar.FindClosestBuildingInsights. + Information about the location, dimensions, and solar + potential of a building. + + """ + # 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, solar_service.FindClosestBuildingInsightsRequest): + request = solar_service.FindClosestBuildingInsightsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.find_closest_building_insights] + + # 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_data_layers(self, + request: Optional[Union[solar_service.GetDataLayersRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> solar_service.DataLayers: + r"""Gets solar information for a region surrounding a location. + Returns an error with code ``NOT_FOUND`` if the location is + outside the coverage area. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import solar_v1 + + async def sample_get_data_layers(): + # Create a client + client = solar_v1.SolarAsyncClient() + + # Initialize request argument(s) + request = solar_v1.GetDataLayersRequest( + radius_meters=0.1399, + ) + + # Make the request + response = await client.get_data_layers(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.solar_v1.types.GetDataLayersRequest, dict]]): + The request object. Request message for ``Solar.GetDataLayers``. + 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.maps.solar_v1.types.DataLayers: + Information about the solar potential of a region. The actual data + are contained in a number of GeoTIFF files covering + the requested region, for which this message contains + URLs: Each string in the DataLayers message contains + a URL from which the corresponding GeoTIFF can be + fetched. These URLs are valid for a few hours after + they've been generated. Most of the GeoTIFF files are + at a resolution of 0.1m/pixel, but the monthly flux + file is at 0.5m/pixel, and the hourly shade files are + at 1m/pixel. If a pixel_size_meters value was + specified in the GetDataLayersRequest, then the + minimum resolution in the GeoTIFF files will be that + value. + + """ + # 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, solar_service.GetDataLayersRequest): + request = solar_service.GetDataLayersRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_data_layers] + + # 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_geo_tiff(self, + request: Optional[Union[solar_service.GetGeoTiffRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> httpbody_pb2.HttpBody: + r"""Returns an image by its 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.maps import solar_v1 + + async def sample_get_geo_tiff(): + # Create a client + client = solar_v1.SolarAsyncClient() + + # Initialize request argument(s) + request = solar_v1.GetGeoTiffRequest( + id="id_value", + ) + + # Make the request + response = await client.get_geo_tiff(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.solar_v1.types.GetGeoTiffRequest, dict]]): + The request object. Request message for ``Solar.GetGeoTiff``. + 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.api.httpbody_pb2.HttpBody: + Message that represents an arbitrary HTTP body. It should only be used for + payload formats that can't be represented as JSON, + such as raw binary or an HTML page. + + This message can be used both in streaming and + non-streaming API methods in the request as well as + the response. + + It can be used as a top-level request field, which is + convenient if one wants to extract parameters from + either the URL or HTTP template into the request + fields and also want access to the raw HTTP body. + + Example: + + message GetResourceRequest { + // A unique request id. string request_id = 1; + + // The raw HTTP body is bound to this field. + google.api.HttpBody http_body = 2; + + } + + service ResourceService { + rpc GetResource(GetResourceRequest) + returns (google.api.HttpBody); + + rpc UpdateResource(google.api.HttpBody) + returns (google.protobuf.Empty); + + } + + Example with streaming methods: + + service CaldavService { + rpc GetCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + rpc UpdateCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + } + + Use of this type only changes how the request and + response bodies are handled, all other features will + continue to work unchanged. + + """ + # 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, solar_service.GetGeoTiffRequest): + request = solar_service.GetGeoTiffRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_geo_tiff] + + # 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) -> "SolarAsyncClient": + 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__) + + +__all__ = ( + "SolarAsyncClient", +) diff --git a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/client.py b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/client.py new file mode 100644 index 000000000000..89f5172b8129 --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/client.py @@ -0,0 +1,876 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +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.maps.solar_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 + +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.api import httpbody_pb2 # type: ignore +from google.maps.solar_v1.types import solar_service +from google.protobuf import any_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore +from .transports.base import SolarTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SolarGrpcTransport +from .transports.grpc_asyncio import SolarGrpcAsyncIOTransport +from .transports.rest import SolarRestTransport + + +class SolarClientMeta(type): + """Metaclass for the Solar 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[SolarTransport]] + _transport_registry["grpc"] = SolarGrpcTransport + _transport_registry["grpc_asyncio"] = SolarGrpcAsyncIOTransport + _transport_registry["rest"] = SolarRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[SolarTransport]: + """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 SolarClient(metaclass=SolarClientMeta): + """Service definition for the Solar 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 = "solar.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "solar.{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: + SolarClient: 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: + SolarClient: 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) -> SolarTransport: + """Returns the transport used by the client instance. + + Returns: + SolarTransport: The transport used by the client + instance. + """ + return self._transport + + @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 = SolarClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = SolarClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = SolarClient._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 = SolarClient._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 + + @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, SolarTransport, Callable[..., SolarTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the solar 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,SolarTransport,Callable[..., SolarTransport]]]): + 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 SolarTransport 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 = SolarClient._read_environment_variables() + self._client_cert_source = SolarClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = SolarClient._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, SolarTransport) + if transport_provided: + # transport is a SolarTransport 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(SolarTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + SolarClient._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[SolarTransport], Callable[..., SolarTransport]] = ( + SolarClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., SolarTransport], 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.maps.solar_v1.SolarClient`.", + extra = { + "serviceName": "google.maps.solar.v1.Solar", + "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.maps.solar.v1.Solar", + "credentialsType": None, + } + ) + + def find_closest_building_insights(self, + request: Optional[Union[solar_service.FindClosestBuildingInsightsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> solar_service.BuildingInsights: + r"""Locates the closest building to a query point. Returns an error + with code ``NOT_FOUND`` if there are no buildings within + approximately 50m of the query point. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import solar_v1 + + def sample_find_closest_building_insights(): + # Create a client + client = solar_v1.SolarClient() + + # Initialize request argument(s) + request = solar_v1.FindClosestBuildingInsightsRequest( + ) + + # Make the request + response = client.find_closest_building_insights(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.solar_v1.types.FindClosestBuildingInsightsRequest, dict]): + The request object. Request message for + ``Solar.FindClosestBuildingInsights``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.maps.solar_v1.types.BuildingInsights: + Response message for Solar.FindClosestBuildingInsights. + Information about the location, dimensions, and solar + potential of a building. + + """ + # 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, solar_service.FindClosestBuildingInsightsRequest): + request = solar_service.FindClosestBuildingInsightsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.find_closest_building_insights] + + # 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_data_layers(self, + request: Optional[Union[solar_service.GetDataLayersRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> solar_service.DataLayers: + r"""Gets solar information for a region surrounding a location. + Returns an error with code ``NOT_FOUND`` if the location is + outside the coverage area. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import solar_v1 + + def sample_get_data_layers(): + # Create a client + client = solar_v1.SolarClient() + + # Initialize request argument(s) + request = solar_v1.GetDataLayersRequest( + radius_meters=0.1399, + ) + + # Make the request + response = client.get_data_layers(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.solar_v1.types.GetDataLayersRequest, dict]): + The request object. Request message for ``Solar.GetDataLayers``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.maps.solar_v1.types.DataLayers: + Information about the solar potential of a region. The actual data + are contained in a number of GeoTIFF files covering + the requested region, for which this message contains + URLs: Each string in the DataLayers message contains + a URL from which the corresponding GeoTIFF can be + fetched. These URLs are valid for a few hours after + they've been generated. Most of the GeoTIFF files are + at a resolution of 0.1m/pixel, but the monthly flux + file is at 0.5m/pixel, and the hourly shade files are + at 1m/pixel. If a pixel_size_meters value was + specified in the GetDataLayersRequest, then the + minimum resolution in the GeoTIFF files will be that + value. + + """ + # 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, solar_service.GetDataLayersRequest): + request = solar_service.GetDataLayersRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_data_layers] + + # 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_geo_tiff(self, + request: Optional[Union[solar_service.GetGeoTiffRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> httpbody_pb2.HttpBody: + r"""Returns an image by its 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.maps import solar_v1 + + def sample_get_geo_tiff(): + # Create a client + client = solar_v1.SolarClient() + + # Initialize request argument(s) + request = solar_v1.GetGeoTiffRequest( + id="id_value", + ) + + # Make the request + response = client.get_geo_tiff(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.solar_v1.types.GetGeoTiffRequest, dict]): + The request object. Request message for ``Solar.GetGeoTiff``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api.httpbody_pb2.HttpBody: + Message that represents an arbitrary HTTP body. It should only be used for + payload formats that can't be represented as JSON, + such as raw binary or an HTML page. + + This message can be used both in streaming and + non-streaming API methods in the request as well as + the response. + + It can be used as a top-level request field, which is + convenient if one wants to extract parameters from + either the URL or HTTP template into the request + fields and also want access to the raw HTTP body. + + Example: + + message GetResourceRequest { + // A unique request id. string request_id = 1; + + // The raw HTTP body is bound to this field. + google.api.HttpBody http_body = 2; + + } + + service ResourceService { + rpc GetResource(GetResourceRequest) + returns (google.api.HttpBody); + + rpc UpdateResource(google.api.HttpBody) + returns (google.protobuf.Empty); + + } + + Example with streaming methods: + + service CaldavService { + rpc GetCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + rpc UpdateCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + } + + Use of this type only changes how the request and + response bodies are handled, all other features will + continue to work unchanged. + + """ + # 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, solar_service.GetGeoTiffRequest): + request = solar_service.GetGeoTiffRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_geo_tiff] + + # 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) -> "SolarClient": + 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__) + + +__all__ = ( + "SolarClient", +) diff --git a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/README.rst b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/README.rst new file mode 100644 index 000000000000..9860e8dc616e --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`SolarTransport` is the ABC for all transports. +- public child `SolarGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `SolarGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseSolarRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `SolarRestTransport` 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-maps-solar/v1/google/maps/solar_v1/services/solar/transports/__init__.py b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/__init__.py new file mode 100644 index 000000000000..65c6bd1fe24b --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 SolarTransport +from .grpc import SolarGrpcTransport +from .grpc_asyncio import SolarGrpcAsyncIOTransport +from .rest import SolarRestTransport +from .rest import SolarRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SolarTransport]] +_transport_registry['grpc'] = SolarGrpcTransport +_transport_registry['grpc_asyncio'] = SolarGrpcAsyncIOTransport +_transport_registry['rest'] = SolarRestTransport + +__all__ = ( + 'SolarTransport', + 'SolarGrpcTransport', + 'SolarGrpcAsyncIOTransport', + 'SolarRestTransport', + 'SolarRestInterceptor', +) diff --git a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/base.py b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/base.py new file mode 100644 index 000000000000..6f94fcccd295 --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/base.py @@ -0,0 +1,210 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.maps.solar_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 + +from google.api import httpbody_pb2 # type: ignore +from google.maps.solar_v1.types import solar_service + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class SolarTransport(abc.ABC): + """Abstract transport class for Solar.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'solar.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: 'solar.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to 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_closest_building_insights: gapic_v1.method.wrap_method( + self.find_closest_building_insights, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_data_layers: gapic_v1.method.wrap_method( + self.get_data_layers, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_geo_tiff: gapic_v1.method.wrap_method( + self.get_geo_tiff, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def find_closest_building_insights(self) -> Callable[ + [solar_service.FindClosestBuildingInsightsRequest], + Union[ + solar_service.BuildingInsights, + Awaitable[solar_service.BuildingInsights] + ]]: + raise NotImplementedError() + + @property + def get_data_layers(self) -> Callable[ + [solar_service.GetDataLayersRequest], + Union[ + solar_service.DataLayers, + Awaitable[solar_service.DataLayers] + ]]: + raise NotImplementedError() + + @property + def get_geo_tiff(self) -> Callable[ + [solar_service.GetGeoTiffRequest], + Union[ + httpbody_pb2.HttpBody, + Awaitable[httpbody_pb2.HttpBody] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'SolarTransport', +) diff --git a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/grpc.py b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/grpc.py new file mode 100644 index 000000000000..d91cce1af58c --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/grpc.py @@ -0,0 +1,404 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.api import httpbody_pb2 # type: ignore +from google.maps.solar_v1.types import solar_service +from .base import SolarTransport, 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.maps.solar.v1.Solar", + "rpcName": 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.maps.solar.v1.Solar", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class SolarGrpcTransport(SolarTransport): + """gRPC backend transport for Solar. + + Service definition for the Solar 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 = 'solar.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: 'solar.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to 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 = 'solar.googleapis.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_closest_building_insights(self) -> Callable[ + [solar_service.FindClosestBuildingInsightsRequest], + solar_service.BuildingInsights]: + r"""Return a callable for the find closest building insights method over gRPC. + + Locates the closest building to a query point. Returns an error + with code ``NOT_FOUND`` if there are no buildings within + approximately 50m of the query point. + + Returns: + Callable[[~.FindClosestBuildingInsightsRequest], + ~.BuildingInsights]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_closest_building_insights' not in self._stubs: + self._stubs['find_closest_building_insights'] = self._logged_channel.unary_unary( + '/google.maps.solar.v1.Solar/FindClosestBuildingInsights', + request_serializer=solar_service.FindClosestBuildingInsightsRequest.serialize, + response_deserializer=solar_service.BuildingInsights.deserialize, + ) + return self._stubs['find_closest_building_insights'] + + @property + def get_data_layers(self) -> Callable[ + [solar_service.GetDataLayersRequest], + solar_service.DataLayers]: + r"""Return a callable for the get data layers method over gRPC. + + Gets solar information for a region surrounding a location. + Returns an error with code ``NOT_FOUND`` if the location is + outside the coverage area. + + Returns: + Callable[[~.GetDataLayersRequest], + ~.DataLayers]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_data_layers' not in self._stubs: + self._stubs['get_data_layers'] = self._logged_channel.unary_unary( + '/google.maps.solar.v1.Solar/GetDataLayers', + request_serializer=solar_service.GetDataLayersRequest.serialize, + response_deserializer=solar_service.DataLayers.deserialize, + ) + return self._stubs['get_data_layers'] + + @property + def get_geo_tiff(self) -> Callable[ + [solar_service.GetGeoTiffRequest], + httpbody_pb2.HttpBody]: + r"""Return a callable for the get geo tiff method over gRPC. + + Returns an image by its ID. + + Returns: + Callable[[~.GetGeoTiffRequest], + ~.HttpBody]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_geo_tiff' not in self._stubs: + self._stubs['get_geo_tiff'] = self._logged_channel.unary_unary( + '/google.maps.solar.v1.Solar/GetGeoTiff', + request_serializer=solar_service.GetGeoTiffRequest.serialize, + response_deserializer=httpbody_pb2.HttpBody.FromString, + ) + return self._stubs['get_geo_tiff'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'SolarGrpcTransport', +) diff --git a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/grpc_asyncio.py b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/grpc_asyncio.py new file mode 100644 index 000000000000..1bd9080f8973 --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/grpc_asyncio.py @@ -0,0 +1,461 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.api import httpbody_pb2 # type: ignore +from google.maps.solar_v1.types import solar_service +from .base import SolarTransport, DEFAULT_CLIENT_INFO +from .grpc import SolarGrpcTransport + +try: + from google.api_core import client_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.maps.solar.v1.Solar", + "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.maps.solar.v1.Solar", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class SolarGrpcAsyncIOTransport(SolarTransport): + """gRPC AsyncIO backend transport for Solar. + + Service definition for the Solar 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 = 'solar.googleapis.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 = 'solar.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: 'solar.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to 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_closest_building_insights(self) -> Callable[ + [solar_service.FindClosestBuildingInsightsRequest], + Awaitable[solar_service.BuildingInsights]]: + r"""Return a callable for the find closest building insights method over gRPC. + + Locates the closest building to a query point. Returns an error + with code ``NOT_FOUND`` if there are no buildings within + approximately 50m of the query point. + + Returns: + Callable[[~.FindClosestBuildingInsightsRequest], + Awaitable[~.BuildingInsights]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_closest_building_insights' not in self._stubs: + self._stubs['find_closest_building_insights'] = self._logged_channel.unary_unary( + '/google.maps.solar.v1.Solar/FindClosestBuildingInsights', + request_serializer=solar_service.FindClosestBuildingInsightsRequest.serialize, + response_deserializer=solar_service.BuildingInsights.deserialize, + ) + return self._stubs['find_closest_building_insights'] + + @property + def get_data_layers(self) -> Callable[ + [solar_service.GetDataLayersRequest], + Awaitable[solar_service.DataLayers]]: + r"""Return a callable for the get data layers method over gRPC. + + Gets solar information for a region surrounding a location. + Returns an error with code ``NOT_FOUND`` if the location is + outside the coverage area. + + Returns: + Callable[[~.GetDataLayersRequest], + Awaitable[~.DataLayers]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_data_layers' not in self._stubs: + self._stubs['get_data_layers'] = self._logged_channel.unary_unary( + '/google.maps.solar.v1.Solar/GetDataLayers', + request_serializer=solar_service.GetDataLayersRequest.serialize, + response_deserializer=solar_service.DataLayers.deserialize, + ) + return self._stubs['get_data_layers'] + + @property + def get_geo_tiff(self) -> Callable[ + [solar_service.GetGeoTiffRequest], + Awaitable[httpbody_pb2.HttpBody]]: + r"""Return a callable for the get geo tiff method over gRPC. + + Returns an image by its ID. + + Returns: + Callable[[~.GetGeoTiffRequest], + Awaitable[~.HttpBody]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_geo_tiff' not in self._stubs: + self._stubs['get_geo_tiff'] = self._logged_channel.unary_unary( + '/google.maps.solar.v1.Solar/GetGeoTiff', + request_serializer=solar_service.GetGeoTiffRequest.serialize, + response_deserializer=httpbody_pb2.HttpBody.FromString, + ) + return self._stubs['get_geo_tiff'] + + 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_closest_building_insights: self._wrap_method( + self.find_closest_building_insights, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_data_layers: self._wrap_method( + self.get_data_layers, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_geo_tiff: self._wrap_method( + self.get_geo_tiff, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + 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__ = ( + 'SolarGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/rest.py b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/rest.py new file mode 100644 index 000000000000..ced1d9a2a090 --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/rest.py @@ -0,0 +1,694 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +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.api import httpbody_pb2 # type: ignore +from google.maps.solar_v1.types import solar_service + + +from .rest_base import _BaseSolarRestTransport +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}", +) + + +class SolarRestInterceptor: + """Interceptor for Solar. + + 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 SolarRestTransport. + + .. code-block:: python + class MyCustomSolarInterceptor(SolarRestInterceptor): + def pre_find_closest_building_insights(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_find_closest_building_insights(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_data_layers(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_data_layers(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_geo_tiff(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_geo_tiff(self, response): + logging.log(f"Received response: {response}") + return response + + transport = SolarRestTransport(interceptor=MyCustomSolarInterceptor()) + client = SolarClient(transport=transport) + + + """ + def pre_find_closest_building_insights(self, request: solar_service.FindClosestBuildingInsightsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[solar_service.FindClosestBuildingInsightsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for find_closest_building_insights + + Override in a subclass to manipulate the request or metadata + before they are sent to the Solar server. + """ + return request, metadata + + def post_find_closest_building_insights(self, response: solar_service.BuildingInsights) -> solar_service.BuildingInsights: + """Post-rpc interceptor for find_closest_building_insights + + Override in a subclass to manipulate the response + after it is returned by the Solar server but before + it is returned to user code. + """ + return response + + def pre_get_data_layers(self, request: solar_service.GetDataLayersRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[solar_service.GetDataLayersRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_data_layers + + Override in a subclass to manipulate the request or metadata + before they are sent to the Solar server. + """ + return request, metadata + + def post_get_data_layers(self, response: solar_service.DataLayers) -> solar_service.DataLayers: + """Post-rpc interceptor for get_data_layers + + Override in a subclass to manipulate the response + after it is returned by the Solar server but before + it is returned to user code. + """ + return response + + def pre_get_geo_tiff(self, request: solar_service.GetGeoTiffRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[solar_service.GetGeoTiffRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_geo_tiff + + Override in a subclass to manipulate the request or metadata + before they are sent to the Solar server. + """ + return request, metadata + + def post_get_geo_tiff(self, response: httpbody_pb2.HttpBody) -> httpbody_pb2.HttpBody: + """Post-rpc interceptor for get_geo_tiff + + Override in a subclass to manipulate the response + after it is returned by the Solar server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class SolarRestStub: + _session: AuthorizedSession + _host: str + _interceptor: SolarRestInterceptor + + +class SolarRestTransport(_BaseSolarRestTransport): + """REST backend synchronous transport for Solar. + + Service definition for the Solar 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 = 'solar.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[SolarRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'solar.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to 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 SolarRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _FindClosestBuildingInsights(_BaseSolarRestTransport._BaseFindClosestBuildingInsights, SolarRestStub): + def __hash__(self): + return hash("SolarRestTransport.FindClosestBuildingInsights") + + @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: solar_service.FindClosestBuildingInsightsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> solar_service.BuildingInsights: + r"""Call the find closest building + insights method over HTTP. + + Args: + request (~.solar_service.FindClosestBuildingInsightsRequest): + The request object. Request message for + ``Solar.FindClosestBuildingInsights``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.solar_service.BuildingInsights: + Response message for + ``Solar.FindClosestBuildingInsights``. Information about + the location, dimensions, and solar potential of a + building. + + """ + + http_options = _BaseSolarRestTransport._BaseFindClosestBuildingInsights._get_http_options() + + request, metadata = self._interceptor.pre_find_closest_building_insights(request, metadata) + transcoded_request = _BaseSolarRestTransport._BaseFindClosestBuildingInsights._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseSolarRestTransport._BaseFindClosestBuildingInsights._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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.maps.solar_v1.SolarClient.FindClosestBuildingInsights", + extra = { + "serviceName": "google.maps.solar.v1.Solar", + "rpcName": "FindClosestBuildingInsights", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SolarRestTransport._FindClosestBuildingInsights._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 = solar_service.BuildingInsights() + pb_resp = solar_service.BuildingInsights.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_find_closest_building_insights(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = solar_service.BuildingInsights.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.maps.solar_v1.SolarClient.find_closest_building_insights", + extra = { + "serviceName": "google.maps.solar.v1.Solar", + "rpcName": "FindClosestBuildingInsights", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetDataLayers(_BaseSolarRestTransport._BaseGetDataLayers, SolarRestStub): + def __hash__(self): + return hash("SolarRestTransport.GetDataLayers") + + @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: solar_service.GetDataLayersRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> solar_service.DataLayers: + r"""Call the get data layers method over HTTP. + + Args: + request (~.solar_service.GetDataLayersRequest): + The request object. Request message for ``Solar.GetDataLayers``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.solar_service.DataLayers: + Information about the solar potential of a region. The + actual data are contained in a number of GeoTIFF files + covering the requested region, for which this message + contains URLs: Each string in the ``DataLayers`` message + contains a URL from which the corresponding GeoTIFF can + be fetched. These URLs are valid for a few hours after + they've been generated. Most of the GeoTIFF files are at + a resolution of 0.1m/pixel, but the monthly flux file is + at 0.5m/pixel, and the hourly shade files are at + 1m/pixel. If a ``pixel_size_meters`` value was specified + in the ``GetDataLayersRequest``, then the minimum + resolution in the GeoTIFF files will be that value. + + """ + + http_options = _BaseSolarRestTransport._BaseGetDataLayers._get_http_options() + + request, metadata = self._interceptor.pre_get_data_layers(request, metadata) + transcoded_request = _BaseSolarRestTransport._BaseGetDataLayers._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseSolarRestTransport._BaseGetDataLayers._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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.maps.solar_v1.SolarClient.GetDataLayers", + extra = { + "serviceName": "google.maps.solar.v1.Solar", + "rpcName": "GetDataLayers", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SolarRestTransport._GetDataLayers._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 = solar_service.DataLayers() + pb_resp = solar_service.DataLayers.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_data_layers(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = solar_service.DataLayers.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.maps.solar_v1.SolarClient.get_data_layers", + extra = { + "serviceName": "google.maps.solar.v1.Solar", + "rpcName": "GetDataLayers", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetGeoTiff(_BaseSolarRestTransport._BaseGetGeoTiff, SolarRestStub): + def __hash__(self): + return hash("SolarRestTransport.GetGeoTiff") + + @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: solar_service.GetGeoTiffRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> httpbody_pb2.HttpBody: + r"""Call the get geo tiff method over HTTP. + + Args: + request (~.solar_service.GetGeoTiffRequest): + The request object. Request message for ``Solar.GetGeoTiff``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.httpbody_pb2.HttpBody: + Message that represents an arbitrary HTTP body. It + should only be used for payload formats that can't be + represented as JSON, such as raw binary or an HTML page. + + This message can be used both in streaming and + non-streaming API methods in the request as well as the + response. + + It can be used as a top-level request field, which is + convenient if one wants to extract parameters from + either the URL or HTTP template into the request fields + and also want access to the raw HTTP body. + + Example: + + :: + + message GetResourceRequest { + // A unique request id. + string request_id = 1; + + // The raw HTTP body is bound to this field. + google.api.HttpBody http_body = 2; + + } + + service ResourceService { + rpc GetResource(GetResourceRequest) + returns (google.api.HttpBody); + rpc UpdateResource(google.api.HttpBody) + returns (google.protobuf.Empty); + + } + + Example with streaming methods: + + :: + + service CaldavService { + rpc GetCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + rpc UpdateCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + } + + Use of this type only changes how the request and + response bodies are handled, all other features will + continue to work unchanged. + + """ + + http_options = _BaseSolarRestTransport._BaseGetGeoTiff._get_http_options() + + request, metadata = self._interceptor.pre_get_geo_tiff(request, metadata) + transcoded_request = _BaseSolarRestTransport._BaseGetGeoTiff._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseSolarRestTransport._BaseGetGeoTiff._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(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.maps.solar_v1.SolarClient.GetGeoTiff", + extra = { + "serviceName": "google.maps.solar.v1.Solar", + "rpcName": "GetGeoTiff", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SolarRestTransport._GetGeoTiff._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 = httpbody_pb2.HttpBody() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_geo_tiff(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.maps.solar_v1.SolarClient.get_geo_tiff", + extra = { + "serviceName": "google.maps.solar.v1.Solar", + "rpcName": "GetGeoTiff", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def find_closest_building_insights(self) -> Callable[ + [solar_service.FindClosestBuildingInsightsRequest], + solar_service.BuildingInsights]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._FindClosestBuildingInsights(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_data_layers(self) -> Callable[ + [solar_service.GetDataLayersRequest], + solar_service.DataLayers]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetDataLayers(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_geo_tiff(self) -> Callable[ + [solar_service.GetGeoTiffRequest], + httpbody_pb2.HttpBody]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetGeoTiff(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'SolarRestTransport', +) diff --git a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/rest_base.py b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/rest_base.py new file mode 100644 index 000000000000..7c3b2ee3d17a --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/rest_base.py @@ -0,0 +1,203 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 SolarTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.api import httpbody_pb2 # type: ignore +from google.maps.solar_v1.types import solar_service + + +class _BaseSolarRestTransport(SolarTransport): + """Base REST backend transport for Solar. + + 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 = 'solar.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: 'solar.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 _BaseFindClosestBuildingInsights: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "location" : {}, } + + @classmethod + def _get_unset_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': '/v1/buildingInsights:findClosest', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = solar_service.FindClosestBuildingInsightsRequest.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(_BaseSolarRestTransport._BaseFindClosestBuildingInsights._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetDataLayers: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "location" : {}, "radiusMeters" : 0.0, } + + @classmethod + def _get_unset_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': '/v1/dataLayers:get', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = solar_service.GetDataLayersRequest.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(_BaseSolarRestTransport._BaseGetDataLayers._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetGeoTiff: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "id" : "", } + + @classmethod + def _get_unset_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': '/v1/geoTiff:get', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = solar_service.GetGeoTiffRequest.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(_BaseSolarRestTransport._BaseGetGeoTiff._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseSolarRestTransport', +) diff --git a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/types/__init__.py b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/types/__init__.py new file mode 100644 index 000000000000..f0543dfdf183 --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/types/__init__.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .solar_service import ( + BuildingInsights, + CashPurchaseSavings, + DataLayers, + FinancedPurchaseSavings, + FinancialAnalysis, + FinancialDetails, + FindClosestBuildingInsightsRequest, + GetDataLayersRequest, + GetGeoTiffRequest, + LatLngBox, + LeasingSavings, + RoofSegmentSizeAndSunshineStats, + RoofSegmentSummary, + SavingsOverTime, + SizeAndSunshineStats, + SolarPanel, + SolarPanelConfig, + SolarPotential, + DataLayerView, + ImageryQuality, + SolarPanelOrientation, +) + +__all__ = ( + 'BuildingInsights', + 'CashPurchaseSavings', + 'DataLayers', + 'FinancedPurchaseSavings', + 'FinancialAnalysis', + 'FinancialDetails', + 'FindClosestBuildingInsightsRequest', + 'GetDataLayersRequest', + 'GetGeoTiffRequest', + 'LatLngBox', + 'LeasingSavings', + 'RoofSegmentSizeAndSunshineStats', + 'RoofSegmentSummary', + 'SavingsOverTime', + 'SizeAndSunshineStats', + 'SolarPanel', + 'SolarPanelConfig', + 'SolarPotential', + 'DataLayerView', + 'ImageryQuality', + 'SolarPanelOrientation', +) diff --git a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/types/solar_service.py b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/types/solar_service.py new file mode 100644 index 000000000000..fccb525f1b78 --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/types/solar_service.py @@ -0,0 +1,1306 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 date_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore +from google.type import money_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.solar.v1', + manifest={ + 'DataLayerView', + 'ImageryQuality', + 'SolarPanelOrientation', + 'FindClosestBuildingInsightsRequest', + 'LatLngBox', + 'BuildingInsights', + 'SolarPotential', + 'RoofSegmentSizeAndSunshineStats', + 'SizeAndSunshineStats', + 'SolarPanel', + 'SolarPanelConfig', + 'RoofSegmentSummary', + 'FinancialAnalysis', + 'FinancialDetails', + 'SavingsOverTime', + 'LeasingSavings', + 'CashPurchaseSavings', + 'FinancedPurchaseSavings', + 'GetDataLayersRequest', + 'DataLayers', + 'GetGeoTiffRequest', + }, +) + + +class DataLayerView(proto.Enum): + r"""What subset of the solar information to return. + + Values: + DATA_LAYER_VIEW_UNSPECIFIED (0): + Equivalent to FULL. + DSM_LAYER (1): + Get the DSM only. + IMAGERY_LAYERS (2): + Get the DSM, RGB, and mask. + IMAGERY_AND_ANNUAL_FLUX_LAYERS (3): + Get the DSM, RGB, mask, and annual flux. + IMAGERY_AND_ALL_FLUX_LAYERS (4): + Get the DSM, RGB, mask, annual flux, and + monthly flux. + FULL_LAYERS (5): + Get all data. + """ + DATA_LAYER_VIEW_UNSPECIFIED = 0 + DSM_LAYER = 1 + IMAGERY_LAYERS = 2 + IMAGERY_AND_ANNUAL_FLUX_LAYERS = 3 + IMAGERY_AND_ALL_FLUX_LAYERS = 4 + FULL_LAYERS = 5 + + +class ImageryQuality(proto.Enum): + r"""The quality of the imagery used to compute some API result. + + Note: Regardless of imagery quality level, DSM outputs always + have a resolution of 0.1 m/pixel, monthly flux outputs always + have a resolution of 0.5 m/pixel, and hourly shade outputs + always have a resolution of 1 m/pixel. + + Values: + IMAGERY_QUALITY_UNSPECIFIED (0): + No quality is known. + HIGH (1): + The underlying imagery and DSM data were + processed at 0.1 m/pixel. + MEDIUM (2): + The underlying imagery and DSM data were + processed at 0.25 m/pixel. + LOW (3): + The underlying imagery and DSM data were + processed at 0.5 m/pixel. + """ + IMAGERY_QUALITY_UNSPECIFIED = 0 + HIGH = 1 + MEDIUM = 2 + LOW = 3 + + +class SolarPanelOrientation(proto.Enum): + r"""The orientation of a solar panel. This must be interpreted + relative to the azimuth of the roof segment that the panel is + placed on. + + Values: + SOLAR_PANEL_ORIENTATION_UNSPECIFIED (0): + No panel orientation is known. + LANDSCAPE (1): + A ``LANDSCAPE`` panel has its long edge perpendicular to the + azimuth direction of the roof segment that it is placed on. + PORTRAIT (2): + A ``PORTRAIT`` panel has its long edge parallel to the + azimuth direction of the roof segment that it is placed on. + """ + SOLAR_PANEL_ORIENTATION_UNSPECIFIED = 0 + LANDSCAPE = 1 + PORTRAIT = 2 + + +class FindClosestBuildingInsightsRequest(proto.Message): + r"""Request message for ``Solar.FindClosestBuildingInsights``. + + Attributes: + location (google.type.latlng_pb2.LatLng): + Required. The longitude and latitude from + which the API looks for the nearest known + building. + required_quality (google.maps.solar_v1.types.ImageryQuality): + Optional. The minimum quality level allowed + in the results. No result with lower quality + than this will be returned. Not specifying this + is equivalent to restricting to HIGH quality + only. + exact_quality_required (bool): + Optional. Whether to require exact quality of the imagery. + If set to false, the ``required_quality`` field is + interpreted as the minimum required quality, such that HIGH + quality imagery may be returned when ``required_quality`` is + set to MEDIUM. If set to true, ``required_quality`` is + interpreted as the exact required quality and only + ``MEDIUM`` quality imagery is returned if + ``required_quality`` is set to ``MEDIUM``. + """ + + location: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=1, + message=latlng_pb2.LatLng, + ) + required_quality: 'ImageryQuality' = proto.Field( + proto.ENUM, + number=3, + enum='ImageryQuality', + ) + exact_quality_required: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class LatLngBox(proto.Message): + r"""A bounding box in lat/lng coordinates. + + Attributes: + sw (google.type.latlng_pb2.LatLng): + The southwest corner of the box. + ne (google.type.latlng_pb2.LatLng): + The northeast corner of the box. + """ + + sw: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=1, + message=latlng_pb2.LatLng, + ) + ne: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=2, + message=latlng_pb2.LatLng, + ) + + +class BuildingInsights(proto.Message): + r"""Response message for ``Solar.FindClosestBuildingInsights``. + Information about the location, dimensions, and solar potential of a + building. + + Attributes: + name (str): + The resource name for the building, of the format + ``building/``. + center (google.type.latlng_pb2.LatLng): + A point near the center of the building. + bounding_box (google.maps.solar_v1.types.LatLngBox): + The bounding box of the building. + imagery_date (google.type.date_pb2.Date): + Date that the underlying imagery was + acquired. This is approximate. + imagery_processed_date (google.type.date_pb2.Date): + When processing was completed on this + imagery. + postal_code (str): + Postal code (e.g., US zip code) this building + is contained by. + administrative_area (str): + Administrative area 1 (e.g., in the US, the + state) that contains this building. For example, + in the US, the abbreviation might be "MA" or + "CA.". + statistical_area (str): + Statistical area (e.g., US census tract) this + building is in. + region_code (str): + Region code for the country (or region) this + building is in. + solar_potential (google.maps.solar_v1.types.SolarPotential): + Solar potential of the building. + imagery_quality (google.maps.solar_v1.types.ImageryQuality): + The quality of the imagery used to compute + the data for this building. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + center: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=2, + message=latlng_pb2.LatLng, + ) + bounding_box: 'LatLngBox' = proto.Field( + proto.MESSAGE, + number=9, + message='LatLngBox', + ) + imagery_date: date_pb2.Date = proto.Field( + proto.MESSAGE, + number=3, + message=date_pb2.Date, + ) + imagery_processed_date: date_pb2.Date = proto.Field( + proto.MESSAGE, + number=11, + message=date_pb2.Date, + ) + postal_code: str = proto.Field( + proto.STRING, + number=4, + ) + administrative_area: str = proto.Field( + proto.STRING, + number=5, + ) + statistical_area: str = proto.Field( + proto.STRING, + number=6, + ) + region_code: str = proto.Field( + proto.STRING, + number=7, + ) + solar_potential: 'SolarPotential' = proto.Field( + proto.MESSAGE, + number=8, + message='SolarPotential', + ) + imagery_quality: 'ImageryQuality' = proto.Field( + proto.ENUM, + number=10, + enum='ImageryQuality', + ) + + +class SolarPotential(proto.Message): + r"""Information about the solar potential of a building. A number of + fields in this are defined in terms of "panels". The fields + [panel_capacity_watts] + [google.maps.solar.v1.SolarPotential.panel_capacity_watts], + [panel_height_meters] + [google.maps.solar.v1.SolarPotential.panel_height_meters], and + [panel_width_meters] + [google.maps.solar.v1.SolarPotential.panel_width_meters] describe + the parameters of the model of panel used in these calculations. + + Attributes: + max_array_panels_count (int): + Size of the maximum array - that is, the + maximum number of panels that can fit on the + roof. + panel_capacity_watts (float): + Capacity, in watts, of the panel used in the + calculations. + panel_height_meters (float): + Height, in meters in portrait orientation, of + the panel used in the calculations. + panel_width_meters (float): + Width, in meters in portrait orientation, of + the panel used in the calculations. + panel_lifetime_years (int): + The expected lifetime, in years, of the solar + panels. This is used in the financial + calculations. + max_array_area_meters2 (float): + Size, in square meters, of the maximum array. + max_sunshine_hours_per_year (float): + Maximum number of sunshine hours received per + year, by any point on the roof. Sunshine hours + are a measure of the total amount of insolation + (energy) received per year. 1 sunshine hour = 1 + kWh per kW (where kW refers to kW of capacity + under Standard Testing Conditions). + carbon_offset_factor_kg_per_mwh (float): + Equivalent amount of CO2 produced per MWh of + grid electricity. This is a measure of the + carbon intensity of grid electricity displaced + by solar electricity. + whole_roof_stats (google.maps.solar_v1.types.SizeAndSunshineStats): + Total size and sunlight quantiles for the part of the roof + that was assigned to some roof segment. Despite the name, + this may not include the entire building. See + [building_stats] + [google.maps.solar.v1.SolarPotential.building_stats]. + building_stats (google.maps.solar_v1.types.SizeAndSunshineStats): + Size and sunlight quantiles for the entire building, + including parts of the roof that were not assigned to some + roof segment. Because the orientations of these parts are + not well characterised, the roof area estimate is + unreliable, but the ground area estimate is reliable. It may + be that a more reliable whole building roof area can be + obtained by scaling the roof area from [whole_roof_stats] + [google.maps.solar.v1.SolarPotential.whole_roof_stats] by + the ratio of the ground areas of ``building_stats`` and + ``whole_roof_stats``. + roof_segment_stats (MutableSequence[google.maps.solar_v1.types.RoofSegmentSizeAndSunshineStats]): + Size and sunlight quantiles for each roof + segment. + solar_panels (MutableSequence[google.maps.solar_v1.types.SolarPanel]): + Each [SolarPanel] [google.maps.solar.v1.SolarPanel] + describes a single solar panel. They are listed in the order + that the panel layout algorithm placed this. This is + usually, though not always, in decreasing order of annual + energy production. + solar_panel_configs (MutableSequence[google.maps.solar_v1.types.SolarPanelConfig]): + Each [SolarPanelConfig] + [google.maps.solar.v1.SolarPanelConfig] describes a + different arrangement of solar panels on the roof. They are + in order of increasing number of panels. The + ``SolarPanelConfig`` with [panels_count] + [google.maps.solar.v1.SolarPanelConfig.panels_count]=N is + based on the first N panels in the ``solar_panels`` list. + This field is only populated if at least 4 panels can fit on + a roof. + financial_analyses (MutableSequence[google.maps.solar_v1.types.FinancialAnalysis]): + A [FinancialAnalysis] + [google.maps.solar.v1.FinancialAnalysis] gives the savings + from going solar assuming a given monthly bill and a given + electricity provider. They are in order of increasing order + of monthly bill amount. This field will be empty for + buildings in areas for which the Solar API does not have + enough information to perform financial computations. + """ + + max_array_panels_count: int = proto.Field( + proto.INT32, + number=1, + ) + panel_capacity_watts: float = proto.Field( + proto.FLOAT, + number=9, + ) + panel_height_meters: float = proto.Field( + proto.FLOAT, + number=10, + ) + panel_width_meters: float = proto.Field( + proto.FLOAT, + number=11, + ) + panel_lifetime_years: int = proto.Field( + proto.INT32, + number=12, + ) + max_array_area_meters2: float = proto.Field( + proto.FLOAT, + number=2, + ) + max_sunshine_hours_per_year: float = proto.Field( + proto.FLOAT, + number=3, + ) + carbon_offset_factor_kg_per_mwh: float = proto.Field( + proto.FLOAT, + number=4, + ) + whole_roof_stats: 'SizeAndSunshineStats' = proto.Field( + proto.MESSAGE, + number=5, + message='SizeAndSunshineStats', + ) + building_stats: 'SizeAndSunshineStats' = proto.Field( + proto.MESSAGE, + number=13, + message='SizeAndSunshineStats', + ) + roof_segment_stats: MutableSequence['RoofSegmentSizeAndSunshineStats'] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='RoofSegmentSizeAndSunshineStats', + ) + solar_panels: MutableSequence['SolarPanel'] = proto.RepeatedField( + proto.MESSAGE, + number=14, + message='SolarPanel', + ) + solar_panel_configs: MutableSequence['SolarPanelConfig'] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message='SolarPanelConfig', + ) + financial_analyses: MutableSequence['FinancialAnalysis'] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message='FinancialAnalysis', + ) + + +class RoofSegmentSizeAndSunshineStats(proto.Message): + r"""Information about the size and sunniness quantiles of a roof + segment. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + pitch_degrees (float): + Angle of the roof segment relative to the + theoretical ground plane. 0 = parallel to the + ground, 90 = perpendicular to the ground. + + This field is a member of `oneof`_ ``_pitch_degrees``. + azimuth_degrees (float): + Compass direction the roof segment is pointing in. 0 = + North, 90 = East, 180 = South. For a "flat" roof segment + (``pitch_degrees`` very near 0), azimuth is not well + defined, so for consistency, we define it arbitrarily to be + 0 (North). + + This field is a member of `oneof`_ ``_azimuth_degrees``. + stats (google.maps.solar_v1.types.SizeAndSunshineStats): + Total size and sunlight quantiles for the + roof segment. + center (google.type.latlng_pb2.LatLng): + A point near the center of the roof segment. + bounding_box (google.maps.solar_v1.types.LatLngBox): + The bounding box of the roof segment. + plane_height_at_center_meters (float): + The height of the roof segment plane, in meters above sea + level, at the point designated by ``center``. Together with + the pitch, azimuth, and center location, this fully defines + the roof segment plane. + + This field is a member of `oneof`_ ``_plane_height_at_center_meters``. + """ + + pitch_degrees: float = proto.Field( + proto.FLOAT, + number=1, + optional=True, + ) + azimuth_degrees: float = proto.Field( + proto.FLOAT, + number=2, + optional=True, + ) + stats: 'SizeAndSunshineStats' = proto.Field( + proto.MESSAGE, + number=3, + message='SizeAndSunshineStats', + ) + center: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=4, + message=latlng_pb2.LatLng, + ) + bounding_box: 'LatLngBox' = proto.Field( + proto.MESSAGE, + number=5, + message='LatLngBox', + ) + plane_height_at_center_meters: float = proto.Field( + proto.FLOAT, + number=6, + optional=True, + ) + + +class SizeAndSunshineStats(proto.Message): + r"""Size and sunniness quantiles of a roof, or part of a roof. + + Attributes: + area_meters2 (float): + The area of the roof or roof segment, in m^2. + This is the roof area (accounting for tilt), not + the ground footprint area. + sunshine_quantiles (MutableSequence[float]): + Quantiles of the pointwise sunniness across the area. If + there are N values here, this represents the (N-1)-iles. For + example, if there are 5 values, then they would be the + quartiles (min, 25%, 50%, 75%, max). Values are in annual + kWh/kW like [max_sunshine_hours_per_year] + [google.maps.solar.v1.SolarPotential.max_sunshine_hours_per_year]. + ground_area_meters2 (float): + The ground footprint area covered by the roof + or roof segment, in m^2. + """ + + area_meters2: float = proto.Field( + proto.FLOAT, + number=1, + ) + sunshine_quantiles: MutableSequence[float] = proto.RepeatedField( + proto.FLOAT, + number=2, + ) + ground_area_meters2: float = proto.Field( + proto.FLOAT, + number=3, + ) + + +class SolarPanel(proto.Message): + r"""SolarPanel describes the position, orientation, and production of a + single solar panel. See the [panel_height_meters] + [google.maps.solar.v1.SolarPotential.panel_height_meters], + [panel_width_meters] + [google.maps.solar.v1.SolarPotential.panel_width_meters], and + [panel_capacity_watts] + [google.maps.solar.v1.SolarPotential.panel_capacity_watts] fields in + [SolarPotential] [google.maps.solar.v1.SolarPotential] for + information on the parameters of the panel. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + center (google.type.latlng_pb2.LatLng): + The centre of the panel. + orientation (google.maps.solar_v1.types.SolarPanelOrientation): + The orientation of the panel. + yearly_energy_dc_kwh (float): + How much sunlight energy this layout captures + over the course of a year, in DC kWh. + segment_index (int): + Index in [roof_segment_stats] + [google.maps.solar.v1.SolarPotential.roof_segment_stats] of + the ``RoofSegmentSizeAndSunshineStats`` which corresponds to + the roof segment that this panel is placed on. + + This field is a member of `oneof`_ ``_segment_index``. + """ + + center: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=1, + message=latlng_pb2.LatLng, + ) + orientation: 'SolarPanelOrientation' = proto.Field( + proto.ENUM, + number=2, + enum='SolarPanelOrientation', + ) + yearly_energy_dc_kwh: float = proto.Field( + proto.FLOAT, + number=3, + ) + segment_index: int = proto.Field( + proto.INT32, + number=4, + optional=True, + ) + + +class SolarPanelConfig(proto.Message): + r"""SolarPanelConfig describes a particular placement of solar + panels on the roof. + + Attributes: + panels_count (int): + Total number of panels. Note that this is redundant to (the + sum of) the corresponding fields in [roof_segment_summaries] + [google.maps.solar.v1.SolarPanelConfig.roof_segment_summaries]. + yearly_energy_dc_kwh (float): + How much sunlight energy this layout captures + over the course of a year, in DC kWh, assuming + the panels described above. + roof_segment_summaries (MutableSequence[google.maps.solar_v1.types.RoofSegmentSummary]): + Information about the production of each roof segment that + is carrying at least one panel in this layout. + ``roof_segment_summaries[i]`` describes the i-th roof + segment, including its size, expected production and + orientation. + """ + + panels_count: int = proto.Field( + proto.INT32, + number=1, + ) + yearly_energy_dc_kwh: float = proto.Field( + proto.FLOAT, + number=2, + ) + roof_segment_summaries: MutableSequence['RoofSegmentSummary'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='RoofSegmentSummary', + ) + + +class RoofSegmentSummary(proto.Message): + r"""Information about a roof segment on the building, with some + number of panels placed on it. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + pitch_degrees (float): + Angle of the roof segment relative to the + theoretical ground plane. 0 = parallel to the + ground, 90 = perpendicular to the ground. + + This field is a member of `oneof`_ ``_pitch_degrees``. + azimuth_degrees (float): + Compass direction the roof segment is pointing in. 0 = + North, 90 = East, 180 = South. For a "flat" roof segment + (``pitch_degrees`` very near 0), azimuth is not well + defined, so for consistency, we define it arbitrarily to be + 0 (North). + + This field is a member of `oneof`_ ``_azimuth_degrees``. + panels_count (int): + The total number of panels on this segment. + yearly_energy_dc_kwh (float): + How much sunlight energy this part of the + layout captures over the course of a year, in DC + kWh, assuming the panels described above. + segment_index (int): + Index in [roof_segment_stats] + [google.maps.solar.v1.SolarPotential.roof_segment_stats] of + the corresponding ``RoofSegmentSizeAndSunshineStats``. + + This field is a member of `oneof`_ ``_segment_index``. + """ + + pitch_degrees: float = proto.Field( + proto.FLOAT, + number=2, + optional=True, + ) + azimuth_degrees: float = proto.Field( + proto.FLOAT, + number=3, + optional=True, + ) + panels_count: int = proto.Field( + proto.INT32, + number=7, + ) + yearly_energy_dc_kwh: float = proto.Field( + proto.FLOAT, + number=8, + ) + segment_index: int = proto.Field( + proto.INT32, + number=9, + optional=True, + ) + + +class FinancialAnalysis(proto.Message): + r"""Analysis of the cost and benefits of the optimum solar layout + for a particular electric bill size. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + monthly_bill (google.type.money_pb2.Money): + The monthly electric bill this analysis + assumes. + default_bill (bool): + Whether this is the bill size selected to be the default + bill for the area this building is in. Exactly one + ``FinancialAnalysis`` in ``BuildingSolarPotential`` should + have ``default_bill`` set. + average_kwh_per_month (float): + How much electricity the house uses in an + average month, based on the bill size and the + local electricity rates. + panel_config_index (int): + Index in [solar_panel_configs] + [google.maps.solar.v1.SolarPotential.solar_panel_configs] of + the optimum solar layout for this bill size. This can be -1 + indicating that there is no layout. In this case, the + remaining submessages will be omitted. + + This field is a member of `oneof`_ ``_panel_config_index``. + financial_details (google.maps.solar_v1.types.FinancialDetails): + Financial information that applies regardless + of the financing method used. + leasing_savings (google.maps.solar_v1.types.LeasingSavings): + Cost and benefit of leasing the solar panels. + cash_purchase_savings (google.maps.solar_v1.types.CashPurchaseSavings): + Cost and benefit of buying the solar panels + with cash. + financed_purchase_savings (google.maps.solar_v1.types.FinancedPurchaseSavings): + Cost and benefit of buying the solar panels + by financing the purchase. + """ + + monthly_bill: money_pb2.Money = proto.Field( + proto.MESSAGE, + number=3, + message=money_pb2.Money, + ) + default_bill: bool = proto.Field( + proto.BOOL, + number=4, + ) + average_kwh_per_month: float = proto.Field( + proto.FLOAT, + number=5, + ) + panel_config_index: int = proto.Field( + proto.INT32, + number=6, + optional=True, + ) + financial_details: 'FinancialDetails' = proto.Field( + proto.MESSAGE, + number=7, + message='FinancialDetails', + ) + leasing_savings: 'LeasingSavings' = proto.Field( + proto.MESSAGE, + number=8, + message='LeasingSavings', + ) + cash_purchase_savings: 'CashPurchaseSavings' = proto.Field( + proto.MESSAGE, + number=9, + message='CashPurchaseSavings', + ) + financed_purchase_savings: 'FinancedPurchaseSavings' = proto.Field( + proto.MESSAGE, + number=10, + message='FinancedPurchaseSavings', + ) + + +class FinancialDetails(proto.Message): + r"""Details of a financial analysis. Some of these details are already + stored at higher levels (e.g., out of pocket cost). Total money + amounts are over a lifetime period defined by the + [panel_lifetime_years] + [google.maps.solar.v1.SolarPotential.panel_lifetime_years] field in + [SolarPotential] [google.maps.solar.v1.SolarPotential]. Note: The + out of pocket cost of purchasing the panels is given in the + [out_of_pocket_cost] + [google.maps.solar.v1.CashPurchaseSavings.out_of_pocket_cost] field + in [CashPurchaseSavings] [google.maps.solar.v1.CashPurchaseSavings]. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + initial_ac_kwh_per_year (float): + How many AC kWh we think the solar panels + will generate in their first year. + remaining_lifetime_utility_bill (google.type.money_pb2.Money): + Utility bill for electricity not produced by + solar, for the lifetime of the panels. + federal_incentive (google.type.money_pb2.Money): + Amount of money available from federal + incentives; this applies if the user buys (with + or without a loan) the panels. + state_incentive (google.type.money_pb2.Money): + Amount of money available from state + incentives; this applies if the user buys (with + or without a loan) the panels. + utility_incentive (google.type.money_pb2.Money): + Amount of money available from utility + incentives; this applies if the user buys (with + or without a loan) the panels. + lifetime_srec_total (google.type.money_pb2.Money): + Amount of money the user will receive from + Solar Renewable Energy Credits over the panel + lifetime; this applies if the user buys (with or + without a loan) the panels. + cost_of_electricity_without_solar (google.type.money_pb2.Money): + Total cost of electricity the user would have + paid over the lifetime period if they didn't + install solar. + net_metering_allowed (bool): + Whether net metering is allowed. + solar_percentage (float): + Percentage (0-100) of the user's power + supplied by solar. Valid for the first year but + approximately correct for future years. + + This field is a member of `oneof`_ ``_solar_percentage``. + percentage_exported_to_grid (float): + The percentage (0-100) of solar electricity + production we assumed was exported to the grid, + based on the first quarter of production. This + affects the calculations if net metering is not + allowed. + + This field is a member of `oneof`_ ``_percentage_exported_to_grid``. + """ + + initial_ac_kwh_per_year: float = proto.Field( + proto.FLOAT, + number=1, + ) + remaining_lifetime_utility_bill: money_pb2.Money = proto.Field( + proto.MESSAGE, + number=2, + message=money_pb2.Money, + ) + federal_incentive: money_pb2.Money = proto.Field( + proto.MESSAGE, + number=3, + message=money_pb2.Money, + ) + state_incentive: money_pb2.Money = proto.Field( + proto.MESSAGE, + number=4, + message=money_pb2.Money, + ) + utility_incentive: money_pb2.Money = proto.Field( + proto.MESSAGE, + number=5, + message=money_pb2.Money, + ) + lifetime_srec_total: money_pb2.Money = proto.Field( + proto.MESSAGE, + number=6, + message=money_pb2.Money, + ) + cost_of_electricity_without_solar: money_pb2.Money = proto.Field( + proto.MESSAGE, + number=7, + message=money_pb2.Money, + ) + net_metering_allowed: bool = proto.Field( + proto.BOOL, + number=8, + ) + solar_percentage: float = proto.Field( + proto.FLOAT, + number=9, + optional=True, + ) + percentage_exported_to_grid: float = proto.Field( + proto.FLOAT, + number=10, + optional=True, + ) + + +class SavingsOverTime(proto.Message): + r"""Financial information that's shared between different + financing methods. + + Attributes: + savings_year1 (google.type.money_pb2.Money): + Savings in the first year after panel + installation. + savings_year20 (google.type.money_pb2.Money): + Savings in the first twenty years after panel + installation. + present_value_of_savings_year20 (google.type.money_pb2.Money): + Using the assumed discount rate, what is the + present value of the cumulative 20-year savings? + savings_lifetime (google.type.money_pb2.Money): + Savings in the entire panel lifetime. + present_value_of_savings_lifetime (google.type.money_pb2.Money): + Using the assumed discount rate, what is the + present value of the cumulative lifetime + savings? + financially_viable (bool): + Indicates whether this scenario is + financially viable. Will be false for scenarios + with poor financial viability (e.g., + money-losing). + """ + + savings_year1: money_pb2.Money = proto.Field( + proto.MESSAGE, + number=1, + message=money_pb2.Money, + ) + savings_year20: money_pb2.Money = proto.Field( + proto.MESSAGE, + number=2, + message=money_pb2.Money, + ) + present_value_of_savings_year20: money_pb2.Money = proto.Field( + proto.MESSAGE, + number=3, + message=money_pb2.Money, + ) + savings_lifetime: money_pb2.Money = proto.Field( + proto.MESSAGE, + number=5, + message=money_pb2.Money, + ) + present_value_of_savings_lifetime: money_pb2.Money = proto.Field( + proto.MESSAGE, + number=6, + message=money_pb2.Money, + ) + financially_viable: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class LeasingSavings(proto.Message): + r"""Cost and benefit of leasing a particular configuration of + solar panels with a particular electricity usage. + + Attributes: + leases_allowed (bool): + Whether leases are allowed in this + juristiction (leases are not allowed in some + states). If this field is false, then the values + in this message should probably be ignored. + leases_supported (bool): + Whether leases are supported in this juristiction by the + financial calculation engine. If this field is false, then + the values in this message should probably be ignored. This + is independent of ``leases_allowed``: in some areas leases + are allowed, but under conditions that aren't handled by the + financial models. + annual_leasing_cost (google.type.money_pb2.Money): + Estimated annual leasing cost. + savings (google.maps.solar_v1.types.SavingsOverTime): + How much is saved (or not) over the lifetime + period. + """ + + leases_allowed: bool = proto.Field( + proto.BOOL, + number=1, + ) + leases_supported: bool = proto.Field( + proto.BOOL, + number=2, + ) + annual_leasing_cost: money_pb2.Money = proto.Field( + proto.MESSAGE, + number=3, + message=money_pb2.Money, + ) + savings: 'SavingsOverTime' = proto.Field( + proto.MESSAGE, + number=4, + message='SavingsOverTime', + ) + + +class CashPurchaseSavings(proto.Message): + r"""Cost and benefit of an outright purchase of a particular + configuration of solar panels with a particular electricity + usage. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + out_of_pocket_cost (google.type.money_pb2.Money): + Initial cost before tax incentives: the amount that must be + paid out-of-pocket. Contrast with ``upfront_cost``, which is + after tax incentives. + upfront_cost (google.type.money_pb2.Money): + Initial cost after tax incentives: it's the amount that must + be paid during first year. Contrast with + ``out_of_pocket_cost``, which is before tax incentives. + rebate_value (google.type.money_pb2.Money): + The value of all tax rebates. + payback_years (float): + Number of years until payback occurs. A + negative value means payback never occurs within + the lifetime period. + + This field is a member of `oneof`_ ``_payback_years``. + savings (google.maps.solar_v1.types.SavingsOverTime): + How much is saved (or not) over the lifetime + period. + """ + + out_of_pocket_cost: money_pb2.Money = proto.Field( + proto.MESSAGE, + number=1, + message=money_pb2.Money, + ) + upfront_cost: money_pb2.Money = proto.Field( + proto.MESSAGE, + number=2, + message=money_pb2.Money, + ) + rebate_value: money_pb2.Money = proto.Field( + proto.MESSAGE, + number=3, + message=money_pb2.Money, + ) + payback_years: float = proto.Field( + proto.FLOAT, + number=4, + optional=True, + ) + savings: 'SavingsOverTime' = proto.Field( + proto.MESSAGE, + number=5, + message='SavingsOverTime', + ) + + +class FinancedPurchaseSavings(proto.Message): + r"""Cost and benefit of using a loan to buy a particular + configuration of solar panels with a particular electricity + usage. + + Attributes: + annual_loan_payment (google.type.money_pb2.Money): + Annual loan payments. + rebate_value (google.type.money_pb2.Money): + The value of all tax rebates (including + Federal Investment Tax Credit (ITC)). + loan_interest_rate (float): + The interest rate on loans assumed in this + set of calculations. + savings (google.maps.solar_v1.types.SavingsOverTime): + How much is saved (or not) over the lifetime + period. + """ + + annual_loan_payment: money_pb2.Money = proto.Field( + proto.MESSAGE, + number=1, + message=money_pb2.Money, + ) + rebate_value: money_pb2.Money = proto.Field( + proto.MESSAGE, + number=2, + message=money_pb2.Money, + ) + loan_interest_rate: float = proto.Field( + proto.FLOAT, + number=3, + ) + savings: 'SavingsOverTime' = proto.Field( + proto.MESSAGE, + number=4, + message='SavingsOverTime', + ) + + +class GetDataLayersRequest(proto.Message): + r"""Request message for ``Solar.GetDataLayers``. + + Attributes: + location (google.type.latlng_pb2.LatLng): + Required. The longitude and latitude for the + center of the region to get data for. + radius_meters (float): + Required. The radius, in meters, defining the region + surrounding that centre point for which data should be + returned. The limitations on this value are: + + - Any value up to 100m can always be specified. + - Values over 100m can be specified, as long as + ``radius_meters`` <= ``pixel_size_meters * 1000``. + - However, for values over 175m, the ``DataLayerView`` in + the request must not include monthly flux or hourly + shade. + view (google.maps.solar_v1.types.DataLayerView): + Optional. The desired subset of the data to + return. + required_quality (google.maps.solar_v1.types.ImageryQuality): + Optional. The minimum quality level allowed + in the results. No result with lower quality + than this will be returned. Not specifying this + is equivalent to restricting to HIGH quality + only. + pixel_size_meters (float): + Optional. The minimum scale, in meters per pixel, of the + data to return. Values of 0.1 (the default, if this field is + not set explicitly), 0.25, 0.5, and 1.0 are supported. + Imagery components whose normal resolution is less than + ``pixel_size_meters`` will be returned at the resolution + specified by ``pixel_size_meters``; imagery components whose + normal resolution is equal to or greater than + ``pixel_size_meters`` will be returned at that normal + resolution. + exact_quality_required (bool): + Optional. Whether to require exact quality of the imagery. + If set to false, the ``required_quality`` field is + interpreted as the minimum required quality, such that HIGH + quality imagery may be returned when ``required_quality`` is + set to MEDIUM. If set to true, ``required_quality`` is + interpreted as the exact required quality and only + ``MEDIUM`` quality imagery is returned if + ``required_quality`` is set to ``MEDIUM``. + """ + + location: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=1, + message=latlng_pb2.LatLng, + ) + radius_meters: float = proto.Field( + proto.FLOAT, + number=2, + ) + view: 'DataLayerView' = proto.Field( + proto.ENUM, + number=3, + enum='DataLayerView', + ) + required_quality: 'ImageryQuality' = proto.Field( + proto.ENUM, + number=5, + enum='ImageryQuality', + ) + pixel_size_meters: float = proto.Field( + proto.FLOAT, + number=6, + ) + exact_quality_required: bool = proto.Field( + proto.BOOL, + number=7, + ) + + +class DataLayers(proto.Message): + r"""Information about the solar potential of a region. The actual data + are contained in a number of GeoTIFF files covering the requested + region, for which this message contains URLs: Each string in the + ``DataLayers`` message contains a URL from which the corresponding + GeoTIFF can be fetched. These URLs are valid for a few hours after + they've been generated. Most of the GeoTIFF files are at a + resolution of 0.1m/pixel, but the monthly flux file is at + 0.5m/pixel, and the hourly shade files are at 1m/pixel. If a + ``pixel_size_meters`` value was specified in the + ``GetDataLayersRequest``, then the minimum resolution in the GeoTIFF + files will be that value. + + Attributes: + imagery_date (google.type.date_pb2.Date): + When the source imagery (from which all the + other data are derived) in this region was + taken. It is necessarily somewhat approximate, + as the images may have been taken over more than + one day. + imagery_processed_date (google.type.date_pb2.Date): + When processing was completed on this + imagery. + dsm_url (str): + The URL for an image of the DSM (Digital + Surface Model) of the region. Values are in + meters above EGM96 geoid (i.e., sea level). + Invalid locations (where we don't have data) are + stored as -9999. + rgb_url (str): + The URL for an image of RGB data (aerial + photo) of the region. + mask_url (str): + The URL for the building mask image: one bit + per pixel saying whether that pixel is + considered to be part of a rooftop or not. + annual_flux_url (str): + The URL for the annual flux map (annual sunlight on roofs) + of the region. Values are kWh/kW/year. This is *unmasked + flux*: flux is computed for every location, not just + building rooftops. Invalid locations are stored as -9999: + locations outside our coverage area will be invalid, and a + few locations inside the coverage area, where we were unable + to calculate flux, will also be invalid. + monthly_flux_url (str): + The URL for the monthly flux map (sunlight on + roofs, broken down by month) of the region. + Values are kWh/kW/year. The GeoTIFF pointed to + by this URL will contain twelve bands, + corresponding to January...December, in order. + hourly_shade_urls (MutableSequence[str]): + Twelve URLs for hourly shade, corresponding to + January...December, in order. Each GeoTIFF will contain 24 + bands, corresponding to the 24 hours of the day. Each pixel + is a 32 bit integer, corresponding to the (up to) 31 days of + that month; a 1 bit means that the corresponding location is + able to see the sun at that day, of that hour, of that + month. Invalid locations are stored as -9999 (since this is + negative, it has bit 31 set, and no valid value could have + bit 31 set as that would correspond to the 32nd day of the + month). + + An example may be useful. If you want to know whether a + point (at pixel location (x, y)) saw sun at 4pm on the 22nd + of June you would: + + 1. fetch the sixth URL in this list (corresponding to June). + 2. look up the 17th channel (corresponding to 4pm). + 3. read the 32-bit value at (x, y). + 4. read bit 21 of the value (corresponding to the 22nd of + the month). + 5. if that bit is a 1, then that spot saw the sun at 4pm 22 + June. + + More formally: Given ``month`` (1-12), ``day`` (1...month + max; February has 28 days) and ``hour`` (0-23), the + shade/sun for that month/day/hour at a position ``(x, y)`` + is the bit + + :: + + (hourly_shade[month - 1])(x, y)[hour] & (1 << (day - 1)) + + where ``(x, y)`` is spatial indexing, ``[month - 1]`` refers + to fetching the ``month - 1``\ st URL (indexing from zero), + ``[hour]`` is indexing into the channels, and a final + non-zero result means "sunny". There are no leap days, and + DST doesn't exist (all days are 24 hours long; noon is + always "standard time" noon). + imagery_quality (google.maps.solar_v1.types.ImageryQuality): + The quality of the result's imagery. + """ + + imagery_date: date_pb2.Date = proto.Field( + proto.MESSAGE, + number=1, + message=date_pb2.Date, + ) + imagery_processed_date: date_pb2.Date = proto.Field( + proto.MESSAGE, + number=2, + message=date_pb2.Date, + ) + dsm_url: str = proto.Field( + proto.STRING, + number=3, + ) + rgb_url: str = proto.Field( + proto.STRING, + number=4, + ) + mask_url: str = proto.Field( + proto.STRING, + number=5, + ) + annual_flux_url: str = proto.Field( + proto.STRING, + number=6, + ) + monthly_flux_url: str = proto.Field( + proto.STRING, + number=7, + ) + hourly_shade_urls: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=8, + ) + imagery_quality: 'ImageryQuality' = proto.Field( + proto.ENUM, + number=9, + enum='ImageryQuality', + ) + + +class GetGeoTiffRequest(proto.Message): + r"""Request message for ``Solar.GetGeoTiff``. + + Attributes: + id (str): + Required. The ID of the asset being + requested. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-solar/v1/mypy.ini b/owl-bot-staging/google-maps-solar/v1/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-maps-solar/v1/noxfile.py b/owl-bot-staging/google-maps-solar/v1/noxfile.py new file mode 100644 index 000000000000..b6a24bc4aae0 --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/noxfile.py @@ -0,0 +1,280 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = 'google-maps-solar' + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.13" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "prerelease_deps", +] + +@nox.session(python=ALL_PYTHON) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def unit(session, protobuf_implementation): + """Run the unit test suite.""" + + 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+") + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") + + # 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") + + session.run( + 'py.test', + '--quiet', + '--cov=google/maps/solar_v1/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)), + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + +@nox.session(python=ALL_PYTHON[-1]) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def prerelease_deps(session, protobuf_implementation): + """Run the unit test suite against pre-release versions of dependencies.""" + + 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 test environment dependencies + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + + # Install the package without dependencies + session.install('-e', '.', '--no-deps') + + # We test the minimum dependency versions using the minimum Python + # version so the lowest python runtime that we test has a corresponding constraints + # file, located at `testing/constraints--.txt`, which contains all of the + # 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 + ) + ] + + session.install(*constraints_deps) + + prerel_deps = [ + "googleapis-common-protos", + "google-api-core", + "google-auth", + # Exclude grpcio!=1.67.0rc1 which does not support python 3.13 + "grpcio!=1.67.0rc1", + "grpcio-status", + "protobuf", + "proto-plus", + ] + + for dep in prerel_deps: + session.install("--pre", "--no-deps", "--upgrade", dep) + + # Remaining dependencies + other_deps = [ + "requests", + ] + session.install(*other_deps) + + # Print out prerelease package versions + + session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") + session.run("python", "-c", "import google.auth; print(google.auth.__version__)") + session.run("python", "-c", "import grpc; print(grpc.__version__)") + session.run( + "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" + ) + session.run( + "python", "-c", "import proto; print(proto.__version__)" + ) + + session.run( + 'py.test', + '--quiet', + '--cov=google/maps/solar_v1/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)), + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + + +@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=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 docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==7.0.1", "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=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", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) diff --git a/owl-bot-staging/google-maps-solar/v1/samples/generated_samples/snippet_metadata_google.maps.solar.v1.json b/owl-bot-staging/google-maps-solar/v1/samples/generated_samples/snippet_metadata_google.maps.solar.v1.json new file mode 100644 index 000000000000..b0cd14fdb324 --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/samples/generated_samples/snippet_metadata_google.maps.solar.v1.json @@ -0,0 +1,474 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.maps.solar.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-maps-solar", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.solar_v1.SolarAsyncClient", + "shortName": "SolarAsyncClient" + }, + "fullName": "google.maps.solar_v1.SolarAsyncClient.find_closest_building_insights", + "method": { + "fullName": "google.maps.solar.v1.Solar.FindClosestBuildingInsights", + "service": { + "fullName": "google.maps.solar.v1.Solar", + "shortName": "Solar" + }, + "shortName": "FindClosestBuildingInsights" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.solar_v1.types.FindClosestBuildingInsightsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.maps.solar_v1.types.BuildingInsights", + "shortName": "find_closest_building_insights" + }, + "description": "Sample for FindClosestBuildingInsights", + "file": "solar_v1_generated_solar_find_closest_building_insights_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "solar_v1_generated_Solar_FindClosestBuildingInsights_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": "solar_v1_generated_solar_find_closest_building_insights_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.solar_v1.SolarClient", + "shortName": "SolarClient" + }, + "fullName": "google.maps.solar_v1.SolarClient.find_closest_building_insights", + "method": { + "fullName": "google.maps.solar.v1.Solar.FindClosestBuildingInsights", + "service": { + "fullName": "google.maps.solar.v1.Solar", + "shortName": "Solar" + }, + "shortName": "FindClosestBuildingInsights" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.solar_v1.types.FindClosestBuildingInsightsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.maps.solar_v1.types.BuildingInsights", + "shortName": "find_closest_building_insights" + }, + "description": "Sample for FindClosestBuildingInsights", + "file": "solar_v1_generated_solar_find_closest_building_insights_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "solar_v1_generated_Solar_FindClosestBuildingInsights_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": "solar_v1_generated_solar_find_closest_building_insights_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.solar_v1.SolarAsyncClient", + "shortName": "SolarAsyncClient" + }, + "fullName": "google.maps.solar_v1.SolarAsyncClient.get_data_layers", + "method": { + "fullName": "google.maps.solar.v1.Solar.GetDataLayers", + "service": { + "fullName": "google.maps.solar.v1.Solar", + "shortName": "Solar" + }, + "shortName": "GetDataLayers" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.solar_v1.types.GetDataLayersRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.maps.solar_v1.types.DataLayers", + "shortName": "get_data_layers" + }, + "description": "Sample for GetDataLayers", + "file": "solar_v1_generated_solar_get_data_layers_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "solar_v1_generated_Solar_GetDataLayers_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": "solar_v1_generated_solar_get_data_layers_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.solar_v1.SolarClient", + "shortName": "SolarClient" + }, + "fullName": "google.maps.solar_v1.SolarClient.get_data_layers", + "method": { + "fullName": "google.maps.solar.v1.Solar.GetDataLayers", + "service": { + "fullName": "google.maps.solar.v1.Solar", + "shortName": "Solar" + }, + "shortName": "GetDataLayers" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.solar_v1.types.GetDataLayersRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.maps.solar_v1.types.DataLayers", + "shortName": "get_data_layers" + }, + "description": "Sample for GetDataLayers", + "file": "solar_v1_generated_solar_get_data_layers_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "solar_v1_generated_Solar_GetDataLayers_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": "solar_v1_generated_solar_get_data_layers_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.solar_v1.SolarAsyncClient", + "shortName": "SolarAsyncClient" + }, + "fullName": "google.maps.solar_v1.SolarAsyncClient.get_geo_tiff", + "method": { + "fullName": "google.maps.solar.v1.Solar.GetGeoTiff", + "service": { + "fullName": "google.maps.solar.v1.Solar", + "shortName": "Solar" + }, + "shortName": "GetGeoTiff" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.solar_v1.types.GetGeoTiffRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api.httpbody_pb2.HttpBody", + "shortName": "get_geo_tiff" + }, + "description": "Sample for GetGeoTiff", + "file": "solar_v1_generated_solar_get_geo_tiff_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "solar_v1_generated_Solar_GetGeoTiff_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": "solar_v1_generated_solar_get_geo_tiff_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.solar_v1.SolarClient", + "shortName": "SolarClient" + }, + "fullName": "google.maps.solar_v1.SolarClient.get_geo_tiff", + "method": { + "fullName": "google.maps.solar.v1.Solar.GetGeoTiff", + "service": { + "fullName": "google.maps.solar.v1.Solar", + "shortName": "Solar" + }, + "shortName": "GetGeoTiff" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.solar_v1.types.GetGeoTiffRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api.httpbody_pb2.HttpBody", + "shortName": "get_geo_tiff" + }, + "description": "Sample for GetGeoTiff", + "file": "solar_v1_generated_solar_get_geo_tiff_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "solar_v1_generated_Solar_GetGeoTiff_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": "solar_v1_generated_solar_get_geo_tiff_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_find_closest_building_insights_async.py b/owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_find_closest_building_insights_async.py new file mode 100644 index 000000000000..5058da619386 --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_find_closest_building_insights_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for FindClosestBuildingInsights +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-solar + + +# [START solar_v1_generated_Solar_FindClosestBuildingInsights_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.maps import solar_v1 + + +async def sample_find_closest_building_insights(): + # Create a client + client = solar_v1.SolarAsyncClient() + + # Initialize request argument(s) + request = solar_v1.FindClosestBuildingInsightsRequest( + ) + + # Make the request + response = await client.find_closest_building_insights(request=request) + + # Handle the response + print(response) + +# [END solar_v1_generated_Solar_FindClosestBuildingInsights_async] diff --git a/owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_find_closest_building_insights_sync.py b/owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_find_closest_building_insights_sync.py new file mode 100644 index 000000000000..a08c85dc78de --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_find_closest_building_insights_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for FindClosestBuildingInsights +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-solar + + +# [START solar_v1_generated_Solar_FindClosestBuildingInsights_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.maps import solar_v1 + + +def sample_find_closest_building_insights(): + # Create a client + client = solar_v1.SolarClient() + + # Initialize request argument(s) + request = solar_v1.FindClosestBuildingInsightsRequest( + ) + + # Make the request + response = client.find_closest_building_insights(request=request) + + # Handle the response + print(response) + +# [END solar_v1_generated_Solar_FindClosestBuildingInsights_sync] diff --git a/owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_get_data_layers_async.py b/owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_get_data_layers_async.py new file mode 100644 index 000000000000..c97710ca5564 --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_get_data_layers_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDataLayers +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-solar + + +# [START solar_v1_generated_Solar_GetDataLayers_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.maps import solar_v1 + + +async def sample_get_data_layers(): + # Create a client + client = solar_v1.SolarAsyncClient() + + # Initialize request argument(s) + request = solar_v1.GetDataLayersRequest( + radius_meters=0.1399, + ) + + # Make the request + response = await client.get_data_layers(request=request) + + # Handle the response + print(response) + +# [END solar_v1_generated_Solar_GetDataLayers_async] diff --git a/owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_get_data_layers_sync.py b/owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_get_data_layers_sync.py new file mode 100644 index 000000000000..d9d0aff7cef8 --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_get_data_layers_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDataLayers +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-solar + + +# [START solar_v1_generated_Solar_GetDataLayers_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.maps import solar_v1 + + +def sample_get_data_layers(): + # Create a client + client = solar_v1.SolarClient() + + # Initialize request argument(s) + request = solar_v1.GetDataLayersRequest( + radius_meters=0.1399, + ) + + # Make the request + response = client.get_data_layers(request=request) + + # Handle the response + print(response) + +# [END solar_v1_generated_Solar_GetDataLayers_sync] diff --git a/owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_get_geo_tiff_async.py b/owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_get_geo_tiff_async.py new file mode 100644 index 000000000000..7833a4f51179 --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_get_geo_tiff_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetGeoTiff +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-solar + + +# [START solar_v1_generated_Solar_GetGeoTiff_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.maps import solar_v1 + + +async def sample_get_geo_tiff(): + # Create a client + client = solar_v1.SolarAsyncClient() + + # Initialize request argument(s) + request = solar_v1.GetGeoTiffRequest( + id="id_value", + ) + + # Make the request + response = await client.get_geo_tiff(request=request) + + # Handle the response + print(response) + +# [END solar_v1_generated_Solar_GetGeoTiff_async] diff --git a/owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_get_geo_tiff_sync.py b/owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_get_geo_tiff_sync.py new file mode 100644 index 000000000000..1349f69d8c1f --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_get_geo_tiff_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetGeoTiff +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-solar + + +# [START solar_v1_generated_Solar_GetGeoTiff_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.maps import solar_v1 + + +def sample_get_geo_tiff(): + # Create a client + client = solar_v1.SolarClient() + + # Initialize request argument(s) + request = solar_v1.GetGeoTiffRequest( + id="id_value", + ) + + # Make the request + response = client.get_geo_tiff(request=request) + + # Handle the response + print(response) + +# [END solar_v1_generated_Solar_GetGeoTiff_sync] diff --git a/owl-bot-staging/google-maps-solar/v1/scripts/fixup_solar_v1_keywords.py b/owl-bot-staging/google-maps-solar/v1/scripts/fixup_solar_v1_keywords.py new file mode 100644 index 000000000000..4431e778567d --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/scripts/fixup_solar_v1_keywords.py @@ -0,0 +1,178 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 solarCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'find_closest_building_insights': ('location', 'required_quality', 'exact_quality_required', ), + 'get_data_layers': ('location', 'radius_meters', 'view', 'required_quality', 'pixel_size_meters', 'exact_quality_required', ), + 'get_geo_tiff': ('id', ), + } + + 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=solarCallTransformer(), +): + """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 solar 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-maps-solar/v1/setup.py b/owl-bot-staging/google-maps-solar/v1/setup.py new file mode 100644 index 000000000000..8032e03cfd67 --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/setup.py @@ -0,0 +1,98 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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-maps-solar' + + +description = "Google Maps Solar API client library" + +version = None + +with open(os.path.join(package_root, 'google/maps/solar/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.0dev,!=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.0dev,!=2.24.0,!=2.25.0", + "proto-plus >= 1.22.3, <2.0.0dev", + "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'", + "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", +] +extras = { +} +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-solar" + +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-maps-solar/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-maps-solar/v1/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/testing/constraints-3.10.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-maps-solar/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-maps-solar/v1/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/testing/constraints-3.11.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-maps-solar/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-maps-solar/v1/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/testing/constraints-3.12.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-maps-solar/v1/testing/constraints-3.13.txt b/owl-bot-staging/google-maps-solar/v1/testing/constraints-3.13.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/testing/constraints-3.13.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-maps-solar/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-maps-solar/v1/testing/constraints-3.7.txt new file mode 100644 index 000000000000..fc812592b0ee --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/testing/constraints-3.7.txt @@ -0,0 +1,10 @@ +# 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.0dev", +# 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 diff --git a/owl-bot-staging/google-maps-solar/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-maps-solar/v1/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/testing/constraints-3.8.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-maps-solar/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-maps-solar/v1/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/testing/constraints-3.9.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-maps-solar/v1/tests/__init__.py b/owl-bot-staging/google-maps-solar/v1/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-maps-solar/v1/tests/unit/__init__.py b/owl-bot-staging/google-maps-solar/v1/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-maps-solar/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-maps-solar/v1/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-maps-solar/v1/tests/unit/gapic/solar_v1/__init__.py b/owl-bot-staging/google-maps-solar/v1/tests/unit/gapic/solar_v1/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/tests/unit/gapic/solar_v1/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-maps-solar/v1/tests/unit/gapic/solar_v1/test_solar.py b/owl-bot-staging/google-maps-solar/v1/tests/unit/gapic/solar_v1/test_solar.py new file mode 100644 index 000000000000..6789c2cffbdc --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/tests/unit/gapic/solar_v1/test_solar.py @@ -0,0 +1,2872 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 import httpbody_pb2 # type: ignore +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.maps.solar_v1.services.solar import SolarAsyncClient +from google.maps.solar_v1.services.solar import SolarClient +from google.maps.solar_v1.services.solar import transports +from google.maps.solar_v1.types import solar_service +from google.oauth2 import service_account +from google.protobuf import any_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore +import google.auth + + +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 SolarClient._get_default_mtls_endpoint(None) is None + assert SolarClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert SolarClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert SolarClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert SolarClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert SolarClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert SolarClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert SolarClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert SolarClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + SolarClient._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 SolarClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert SolarClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert SolarClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + SolarClient._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 SolarClient._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 SolarClient._get_client_cert_source(None, False) is None + assert SolarClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert SolarClient._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 SolarClient._get_client_cert_source(None, True) is mock_default_cert_source + assert SolarClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(SolarClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SolarClient)) +@mock.patch.object(SolarAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SolarAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = SolarClient._DEFAULT_UNIVERSE + default_endpoint = SolarClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = SolarClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert SolarClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert SolarClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == SolarClient.DEFAULT_MTLS_ENDPOINT + assert SolarClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert SolarClient._get_api_endpoint(None, None, default_universe, "always") == SolarClient.DEFAULT_MTLS_ENDPOINT + assert SolarClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == SolarClient.DEFAULT_MTLS_ENDPOINT + assert SolarClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert SolarClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + SolarClient._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 SolarClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert SolarClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert SolarClient._get_universe_domain(None, None) == SolarClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + SolarClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize("client_class,transport_name", [ + (SolarClient, "grpc"), + (SolarAsyncClient, "grpc_asyncio"), + (SolarClient, "rest"), +]) +def test_solar_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 == ( + 'solar.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://solar.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.SolarGrpcTransport, "grpc"), + (transports.SolarGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.SolarRestTransport, "rest"), +]) +def test_solar_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", [ + (SolarClient, "grpc"), + (SolarAsyncClient, "grpc_asyncio"), + (SolarClient, "rest"), +]) +def test_solar_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 == ( + 'solar.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://solar.googleapis.com' + ) + + +def test_solar_client_get_transport_class(): + transport = SolarClient.get_transport_class() + available_transports = [ + transports.SolarGrpcTransport, + transports.SolarRestTransport, + ] + assert transport in available_transports + + transport = SolarClient.get_transport_class("grpc") + assert transport == transports.SolarGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SolarClient, transports.SolarGrpcTransport, "grpc"), + (SolarAsyncClient, transports.SolarGrpcAsyncIOTransport, "grpc_asyncio"), + (SolarClient, transports.SolarRestTransport, "rest"), +]) +@mock.patch.object(SolarClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SolarClient)) +@mock.patch.object(SolarAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SolarAsyncClient)) +def test_solar_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(SolarClient, '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(SolarClient, '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", [ + (SolarClient, transports.SolarGrpcTransport, "grpc", "true"), + (SolarAsyncClient, transports.SolarGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (SolarClient, transports.SolarGrpcTransport, "grpc", "false"), + (SolarAsyncClient, transports.SolarGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (SolarClient, transports.SolarRestTransport, "rest", "true"), + (SolarClient, transports.SolarRestTransport, "rest", "false"), +]) +@mock.patch.object(SolarClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SolarClient)) +@mock.patch.object(SolarAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SolarAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_solar_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", [ + SolarClient, SolarAsyncClient +]) +@mock.patch.object(SolarClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SolarClient)) +@mock.patch.object(SolarAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SolarAsyncClient)) +def test_solar_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", [ + SolarClient, SolarAsyncClient +]) +@mock.patch.object(SolarClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SolarClient)) +@mock.patch.object(SolarAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SolarAsyncClient)) +def test_solar_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = SolarClient._DEFAULT_UNIVERSE + default_endpoint = SolarClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = SolarClient._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", [ + (SolarClient, transports.SolarGrpcTransport, "grpc"), + (SolarAsyncClient, transports.SolarGrpcAsyncIOTransport, "grpc_asyncio"), + (SolarClient, transports.SolarRestTransport, "rest"), +]) +def test_solar_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", [ + (SolarClient, transports.SolarGrpcTransport, "grpc", grpc_helpers), + (SolarAsyncClient, transports.SolarGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (SolarClient, transports.SolarRestTransport, "rest", None), +]) +def test_solar_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_solar_client_client_options_from_dict(): + with mock.patch('google.maps.solar_v1.services.solar.transports.SolarGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = SolarClient( + 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", [ + (SolarClient, transports.SolarGrpcTransport, "grpc", grpc_helpers), + (SolarAsyncClient, transports.SolarGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_solar_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( + "solar.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=None, + default_host="solar.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + solar_service.FindClosestBuildingInsightsRequest, + dict, +]) +def test_find_closest_building_insights(request_type, transport: str = 'grpc'): + client = SolarClient( + 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_closest_building_insights), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = solar_service.BuildingInsights( + name='name_value', + postal_code='postal_code_value', + administrative_area='administrative_area_value', + statistical_area='statistical_area_value', + region_code='region_code_value', + imagery_quality=solar_service.ImageryQuality.HIGH, + ) + response = client.find_closest_building_insights(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = solar_service.FindClosestBuildingInsightsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, solar_service.BuildingInsights) + assert response.name == 'name_value' + assert response.postal_code == 'postal_code_value' + assert response.administrative_area == 'administrative_area_value' + assert response.statistical_area == 'statistical_area_value' + assert response.region_code == 'region_code_value' + assert response.imagery_quality == solar_service.ImageryQuality.HIGH + + +def test_find_closest_building_insights_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 = SolarClient( + 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 = solar_service.FindClosestBuildingInsightsRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.find_closest_building_insights), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.find_closest_building_insights(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == solar_service.FindClosestBuildingInsightsRequest( + ) + +def test_find_closest_building_insights_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SolarClient( + 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_closest_building_insights in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_closest_building_insights] = mock_rpc + request = {} + client.find_closest_building_insights(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.find_closest_building_insights(request) + + # Establish that a new wrapper 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_closest_building_insights_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = SolarAsyncClient( + 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_closest_building_insights in client._client._transport._wrapped_methods + + # 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_closest_building_insights] = mock_rpc + + request = {} + await client.find_closest_building_insights(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.find_closest_building_insights(request) + + # Establish that a new wrapper 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_closest_building_insights_async(transport: str = 'grpc_asyncio', request_type=solar_service.FindClosestBuildingInsightsRequest): + client = SolarAsyncClient( + 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_closest_building_insights), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(solar_service.BuildingInsights( + name='name_value', + postal_code='postal_code_value', + administrative_area='administrative_area_value', + statistical_area='statistical_area_value', + region_code='region_code_value', + imagery_quality=solar_service.ImageryQuality.HIGH, + )) + response = await client.find_closest_building_insights(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = solar_service.FindClosestBuildingInsightsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, solar_service.BuildingInsights) + assert response.name == 'name_value' + assert response.postal_code == 'postal_code_value' + assert response.administrative_area == 'administrative_area_value' + assert response.statistical_area == 'statistical_area_value' + assert response.region_code == 'region_code_value' + assert response.imagery_quality == solar_service.ImageryQuality.HIGH + + +@pytest.mark.asyncio +async def test_find_closest_building_insights_async_from_dict(): + await test_find_closest_building_insights_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + solar_service.GetDataLayersRequest, + dict, +]) +def test_get_data_layers(request_type, transport: str = 'grpc'): + client = SolarClient( + 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_data_layers), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = solar_service.DataLayers( + dsm_url='dsm_url_value', + rgb_url='rgb_url_value', + mask_url='mask_url_value', + annual_flux_url='annual_flux_url_value', + monthly_flux_url='monthly_flux_url_value', + hourly_shade_urls=['hourly_shade_urls_value'], + imagery_quality=solar_service.ImageryQuality.HIGH, + ) + response = client.get_data_layers(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = solar_service.GetDataLayersRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, solar_service.DataLayers) + assert response.dsm_url == 'dsm_url_value' + assert response.rgb_url == 'rgb_url_value' + assert response.mask_url == 'mask_url_value' + assert response.annual_flux_url == 'annual_flux_url_value' + assert response.monthly_flux_url == 'monthly_flux_url_value' + assert response.hourly_shade_urls == ['hourly_shade_urls_value'] + assert response.imagery_quality == solar_service.ImageryQuality.HIGH + + +def test_get_data_layers_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 = SolarClient( + 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 = solar_service.GetDataLayersRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_layers), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_data_layers(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == solar_service.GetDataLayersRequest( + ) + +def test_get_data_layers_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SolarClient( + 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_data_layers in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_data_layers] = mock_rpc + request = {} + client.get_data_layers(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_data_layers(request) + + # Establish that a new wrapper 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_data_layers_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = SolarAsyncClient( + 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_data_layers in client._client._transport._wrapped_methods + + # 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_data_layers] = mock_rpc + + request = {} + await client.get_data_layers(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_data_layers(request) + + # Establish that a new wrapper 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_data_layers_async(transport: str = 'grpc_asyncio', request_type=solar_service.GetDataLayersRequest): + client = SolarAsyncClient( + 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_data_layers), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(solar_service.DataLayers( + dsm_url='dsm_url_value', + rgb_url='rgb_url_value', + mask_url='mask_url_value', + annual_flux_url='annual_flux_url_value', + monthly_flux_url='monthly_flux_url_value', + hourly_shade_urls=['hourly_shade_urls_value'], + imagery_quality=solar_service.ImageryQuality.HIGH, + )) + response = await client.get_data_layers(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = solar_service.GetDataLayersRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, solar_service.DataLayers) + assert response.dsm_url == 'dsm_url_value' + assert response.rgb_url == 'rgb_url_value' + assert response.mask_url == 'mask_url_value' + assert response.annual_flux_url == 'annual_flux_url_value' + assert response.monthly_flux_url == 'monthly_flux_url_value' + assert response.hourly_shade_urls == ['hourly_shade_urls_value'] + assert response.imagery_quality == solar_service.ImageryQuality.HIGH + + +@pytest.mark.asyncio +async def test_get_data_layers_async_from_dict(): + await test_get_data_layers_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + solar_service.GetGeoTiffRequest, + dict, +]) +def test_get_geo_tiff(request_type, transport: str = 'grpc'): + client = SolarClient( + 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_geo_tiff), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = httpbody_pb2.HttpBody( + content_type='content_type_value', + data=b'data_blob', + ) + response = client.get_geo_tiff(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = solar_service.GetGeoTiffRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, httpbody_pb2.HttpBody) + assert response.content_type == 'content_type_value' + assert response.data == b'data_blob' + + +def test_get_geo_tiff_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 = SolarClient( + 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 = solar_service.GetGeoTiffRequest( + id='id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_geo_tiff), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_geo_tiff(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == solar_service.GetGeoTiffRequest( + id='id_value', + ) + +def test_get_geo_tiff_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SolarClient( + 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_geo_tiff in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_geo_tiff] = mock_rpc + request = {} + client.get_geo_tiff(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_geo_tiff(request) + + # Establish that a new wrapper 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_geo_tiff_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = SolarAsyncClient( + 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_geo_tiff in client._client._transport._wrapped_methods + + # 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_geo_tiff] = mock_rpc + + request = {} + await client.get_geo_tiff(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_geo_tiff(request) + + # Establish that a new wrapper 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_geo_tiff_async(transport: str = 'grpc_asyncio', request_type=solar_service.GetGeoTiffRequest): + client = SolarAsyncClient( + 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_geo_tiff), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody( + content_type='content_type_value', + data=b'data_blob', + )) + response = await client.get_geo_tiff(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = solar_service.GetGeoTiffRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, httpbody_pb2.HttpBody) + assert response.content_type == 'content_type_value' + assert response.data == b'data_blob' + + +@pytest.mark.asyncio +async def test_get_geo_tiff_async_from_dict(): + await test_get_geo_tiff_async(request_type=dict) + + +def test_find_closest_building_insights_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 = SolarClient( + 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_closest_building_insights in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_closest_building_insights] = mock_rpc + + request = {} + client.find_closest_building_insights(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.find_closest_building_insights(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_closest_building_insights_rest_required_fields(request_type=solar_service.FindClosestBuildingInsightsRequest): + transport_class = transports.SolarRestTransport + + 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()).find_closest_building_insights._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()).find_closest_building_insights._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("exact_quality_required", "location", "required_quality", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = SolarClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = solar_service.BuildingInsights() + # 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 = solar_service.BuildingInsights.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_closest_building_insights(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_find_closest_building_insights_rest_unset_required_fields(): + transport = transports.SolarRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.find_closest_building_insights._get_unset_required_fields({}) + assert set(unset_fields) == (set(("exactQualityRequired", "location", "requiredQuality", )) & set(("location", ))) + + +def test_get_data_layers_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 = SolarClient( + 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_data_layers in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_data_layers] = mock_rpc + + request = {} + client.get_data_layers(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_data_layers(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_data_layers_rest_required_fields(request_type=solar_service.GetDataLayersRequest): + transport_class = transports.SolarRestTransport + + request_init = {} + request_init["radius_meters"] = 0.0 + request = 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 "radiusMeters" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_data_layers._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "radiusMeters" in jsonified_request + assert jsonified_request["radiusMeters"] == request_init["radius_meters"] + + jsonified_request["radiusMeters"] = 0.1399 + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_data_layers._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("exact_quality_required", "location", "pixel_size_meters", "radius_meters", "required_quality", "view", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "radiusMeters" in jsonified_request + assert jsonified_request["radiusMeters"] == 0.1399 + + client = SolarClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = solar_service.DataLayers() + # 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 = solar_service.DataLayers.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_data_layers(request) + + expected_params = [ + ( + "radiusMeters", + str(0.0), + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_data_layers_rest_unset_required_fields(): + transport = transports.SolarRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_data_layers._get_unset_required_fields({}) + assert set(unset_fields) == (set(("exactQualityRequired", "location", "pixelSizeMeters", "radiusMeters", "requiredQuality", "view", )) & set(("location", "radiusMeters", ))) + + +def test_get_geo_tiff_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 = SolarClient( + 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_geo_tiff in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_geo_tiff] = mock_rpc + + request = {} + client.get_geo_tiff(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_geo_tiff(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_geo_tiff_rest_required_fields(request_type=solar_service.GetGeoTiffRequest): + transport_class = transports.SolarRestTransport + + request_init = {} + request_init["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 "id" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_geo_tiff._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "id" in jsonified_request + assert jsonified_request["id"] == request_init["id"] + + jsonified_request["id"] = 'id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_geo_tiff._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "id" in jsonified_request + assert jsonified_request["id"] == 'id_value' + + client = SolarClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = httpbody_pb2.HttpBody() + # 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 = json_format.MessageToJson(return_value) + + response_value._content = json_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_geo_tiff(request) + + expected_params = [ + ( + "id", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_geo_tiff_rest_unset_required_fields(): + transport = transports.SolarRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_geo_tiff._get_unset_required_fields({}) + assert set(unset_fields) == (set(("id", )) & set(("id", ))) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SolarGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SolarClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SolarGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SolarClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.SolarGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SolarClient( + 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 = SolarClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SolarGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SolarClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SolarGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SolarClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SolarGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SolarGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.SolarGrpcTransport, + transports.SolarGrpcAsyncIOTransport, + transports.SolarRestTransport, +]) +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 = SolarClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = SolarClient( + 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_closest_building_insights_empty_call_grpc(): + client = SolarClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.find_closest_building_insights), + '__call__') as call: + call.return_value = solar_service.BuildingInsights() + client.find_closest_building_insights(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = solar_service.FindClosestBuildingInsightsRequest() + + assert args[0] == request_msg + + +# This 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_data_layers_empty_call_grpc(): + client = SolarClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_data_layers), + '__call__') as call: + call.return_value = solar_service.DataLayers() + client.get_data_layers(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = solar_service.GetDataLayersRequest() + + assert args[0] == request_msg + + +# This 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_geo_tiff_empty_call_grpc(): + client = SolarClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_geo_tiff), + '__call__') as call: + call.return_value = httpbody_pb2.HttpBody() + client.get_geo_tiff(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = solar_service.GetGeoTiffRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = SolarAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = SolarAsyncClient( + 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_closest_building_insights_empty_call_grpc_asyncio(): + client = SolarAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.find_closest_building_insights), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(solar_service.BuildingInsights( + name='name_value', + postal_code='postal_code_value', + administrative_area='administrative_area_value', + statistical_area='statistical_area_value', + region_code='region_code_value', + imagery_quality=solar_service.ImageryQuality.HIGH, + )) + await client.find_closest_building_insights(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = solar_service.FindClosestBuildingInsightsRequest() + + assert args[0] == request_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_data_layers_empty_call_grpc_asyncio(): + client = SolarAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_data_layers), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(solar_service.DataLayers( + dsm_url='dsm_url_value', + rgb_url='rgb_url_value', + mask_url='mask_url_value', + annual_flux_url='annual_flux_url_value', + monthly_flux_url='monthly_flux_url_value', + hourly_shade_urls=['hourly_shade_urls_value'], + imagery_quality=solar_service.ImageryQuality.HIGH, + )) + await client.get_data_layers(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = solar_service.GetDataLayersRequest() + + assert args[0] == request_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_geo_tiff_empty_call_grpc_asyncio(): + client = SolarAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_geo_tiff), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody( + content_type='content_type_value', + data=b'data_blob', + )) + await client.get_geo_tiff(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = solar_service.GetGeoTiffRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = SolarClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_find_closest_building_insights_rest_bad_request(request_type=solar_service.FindClosestBuildingInsightsRequest): + client = SolarClient( + 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.find_closest_building_insights(request) + + +@pytest.mark.parametrize("request_type", [ + solar_service.FindClosestBuildingInsightsRequest, + dict, +]) +def test_find_closest_building_insights_rest_call_success(request_type): + client = SolarClient( + 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 = solar_service.BuildingInsights( + name='name_value', + postal_code='postal_code_value', + administrative_area='administrative_area_value', + statistical_area='statistical_area_value', + region_code='region_code_value', + imagery_quality=solar_service.ImageryQuality.HIGH, + ) + + # 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 = solar_service.BuildingInsights.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_closest_building_insights(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, solar_service.BuildingInsights) + assert response.name == 'name_value' + assert response.postal_code == 'postal_code_value' + assert response.administrative_area == 'administrative_area_value' + assert response.statistical_area == 'statistical_area_value' + assert response.region_code == 'region_code_value' + assert response.imagery_quality == solar_service.ImageryQuality.HIGH + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_find_closest_building_insights_rest_interceptors(null_interceptor): + transport = transports.SolarRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SolarRestInterceptor(), + ) + client = SolarClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SolarRestInterceptor, "post_find_closest_building_insights") as post, \ + mock.patch.object(transports.SolarRestInterceptor, "pre_find_closest_building_insights") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = solar_service.FindClosestBuildingInsightsRequest.pb(solar_service.FindClosestBuildingInsightsRequest()) + 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 = solar_service.BuildingInsights.to_json(solar_service.BuildingInsights()) + req.return_value.content = return_value + + request = solar_service.FindClosestBuildingInsightsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = solar_service.BuildingInsights() + + client.find_closest_building_insights(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_data_layers_rest_bad_request(request_type=solar_service.GetDataLayersRequest): + client = SolarClient( + 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.get_data_layers(request) + + +@pytest.mark.parametrize("request_type", [ + solar_service.GetDataLayersRequest, + dict, +]) +def test_get_data_layers_rest_call_success(request_type): + client = SolarClient( + 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 = solar_service.DataLayers( + dsm_url='dsm_url_value', + rgb_url='rgb_url_value', + mask_url='mask_url_value', + annual_flux_url='annual_flux_url_value', + monthly_flux_url='monthly_flux_url_value', + hourly_shade_urls=['hourly_shade_urls_value'], + imagery_quality=solar_service.ImageryQuality.HIGH, + ) + + # 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 = solar_service.DataLayers.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_data_layers(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, solar_service.DataLayers) + assert response.dsm_url == 'dsm_url_value' + assert response.rgb_url == 'rgb_url_value' + assert response.mask_url == 'mask_url_value' + assert response.annual_flux_url == 'annual_flux_url_value' + assert response.monthly_flux_url == 'monthly_flux_url_value' + assert response.hourly_shade_urls == ['hourly_shade_urls_value'] + assert response.imagery_quality == solar_service.ImageryQuality.HIGH + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_data_layers_rest_interceptors(null_interceptor): + transport = transports.SolarRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SolarRestInterceptor(), + ) + client = SolarClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SolarRestInterceptor, "post_get_data_layers") as post, \ + mock.patch.object(transports.SolarRestInterceptor, "pre_get_data_layers") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = solar_service.GetDataLayersRequest.pb(solar_service.GetDataLayersRequest()) + 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 = solar_service.DataLayers.to_json(solar_service.DataLayers()) + req.return_value.content = return_value + + request = solar_service.GetDataLayersRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = solar_service.DataLayers() + + client.get_data_layers(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_geo_tiff_rest_bad_request(request_type=solar_service.GetGeoTiffRequest): + client = SolarClient( + 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.get_geo_tiff(request) + + +@pytest.mark.parametrize("request_type", [ + solar_service.GetGeoTiffRequest, + dict, +]) +def test_get_geo_tiff_rest_call_success(request_type): + client = SolarClient( + 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 = httpbody_pb2.HttpBody( + content_type='content_type_value', + data=b'data_blob', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_geo_tiff(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, httpbody_pb2.HttpBody) + assert response.content_type == 'content_type_value' + assert response.data == b'data_blob' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_geo_tiff_rest_interceptors(null_interceptor): + transport = transports.SolarRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SolarRestInterceptor(), + ) + client = SolarClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SolarRestInterceptor, "post_get_geo_tiff") as post, \ + mock.patch.object(transports.SolarRestInterceptor, "pre_get_geo_tiff") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = solar_service.GetGeoTiffRequest.pb(solar_service.GetGeoTiffRequest()) + 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 = json_format.MessageToJson(httpbody_pb2.HttpBody()) + req.return_value.content = return_value + + request = solar_service.GetGeoTiffRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = httpbody_pb2.HttpBody() + + client.get_geo_tiff(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + +def test_initialize_client_w_rest(): + client = SolarClient( + 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_closest_building_insights_empty_call_rest(): + client = SolarClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.find_closest_building_insights), + '__call__') as call: + client.find_closest_building_insights(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = solar_service.FindClosestBuildingInsightsRequest() + + assert args[0] == request_msg + + +# This 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_data_layers_empty_call_rest(): + client = SolarClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_data_layers), + '__call__') as call: + client.get_data_layers(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = solar_service.GetDataLayersRequest() + + assert args[0] == request_msg + + +# This 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_geo_tiff_empty_call_rest(): + client = SolarClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_geo_tiff), + '__call__') as call: + client.get_geo_tiff(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = solar_service.GetGeoTiffRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = SolarClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SolarGrpcTransport, + ) + +def test_solar_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SolarTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_solar_base_transport(): + # Instantiate the base transport. + with mock.patch('google.maps.solar_v1.services.solar.transports.SolarTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.SolarTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'find_closest_building_insights', + 'get_data_layers', + 'get_geo_tiff', + ) + 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_solar_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.maps.solar_v1.services.solar.transports.SolarTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SolarTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_solar_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.maps.solar_v1.services.solar.transports.SolarTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SolarTransport() + adc.assert_called_once() + + +def test_solar_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) + SolarClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SolarGrpcTransport, + transports.SolarGrpcAsyncIOTransport, + ], +) +def test_solar_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SolarGrpcTransport, + transports.SolarGrpcAsyncIOTransport, + transports.SolarRestTransport, + ], +) +def test_solar_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.SolarGrpcTransport, grpc_helpers), + (transports.SolarGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_solar_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( + "solar.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=["1", "2"], + default_host="solar.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.SolarGrpcTransport, transports.SolarGrpcAsyncIOTransport]) +def test_solar_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_solar_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.SolarRestTransport ( + 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_solar_host_no_port(transport_name): + client = SolarClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='solar.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'solar.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://solar.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_solar_host_with_port(transport_name): + client = SolarClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='solar.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'solar.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://solar.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_solar_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = SolarClient( + credentials=creds1, + transport=transport_name, + ) + client2 = SolarClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.find_closest_building_insights._session + session2 = client2.transport.find_closest_building_insights._session + assert session1 != session2 + session1 = client1.transport.get_data_layers._session + session2 = client2.transport.get_data_layers._session + assert session1 != session2 + session1 = client1.transport.get_geo_tiff._session + session2 = client2.transport.get_geo_tiff._session + assert session1 != session2 +def test_solar_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SolarGrpcTransport( + 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_solar_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SolarGrpcAsyncIOTransport( + 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.SolarGrpcTransport, transports.SolarGrpcAsyncIOTransport]) +def test_solar_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.SolarGrpcTransport, transports.SolarGrpcAsyncIOTransport]) +def test_solar_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_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = SolarClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = SolarClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SolarClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = SolarClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = SolarClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SolarClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = SolarClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = SolarClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SolarClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = SolarClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = SolarClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SolarClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = SolarClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = SolarClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SolarClient.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.SolarTransport, '_prep_wrapped_messages') as prep: + client = SolarClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.SolarTransport, '_prep_wrapped_messages') as prep: + transport_class = SolarClient.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 = SolarClient( + 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 = SolarAsyncClient( + 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 = SolarClient( + 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 = SolarClient( + 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", [ + (SolarClient, transports.SolarGrpcTransport), + (SolarAsyncClient, transports.SolarGrpcAsyncIOTransport), +]) +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..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py 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..2d47c575078c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/shopping/merchant_accounts *.py +recursive-include google/shopping/merchant_accounts_v1beta *.py 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..7f9da4dde09e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/README.rst @@ -0,0 +1,49 @@ +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 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..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} 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..c05de3e02b27 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# 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.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +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"2023, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# 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 = 'en' + +# 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"] + +# 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 Python", + "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", + u"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", + u"google-shopping-merchant-accounts Documentation", + author, + "google-shopping-merchant-accounts", + "GAPIC library for Google Shopping Merchant Accounts API", + "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": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", 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..fc03b88376b9 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/index.rst @@ -0,0 +1,7 @@ +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/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/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/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/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..b9c209efb0f7 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/services_.rst @@ -0,0 +1,20 @@ +Services for Google Shopping Merchant Accounts v1beta API +========================================================= +.. toctree:: + :maxdepth: 2 + + account_issue_service + accounts_service + account_tax_service + autofeed_settings_service + business_identity_service + business_info_service + email_preferences_service + homepage_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/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..9e156f01c727 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts/__init__.py @@ -0,0 +1,271 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.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.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.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.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.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.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.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.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.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', + 'BusinessIdentityServiceClient', + 'BusinessIdentityServiceAsyncClient', + 'BusinessInfoServiceClient', + 'BusinessInfoServiceAsyncClient', + 'EmailPreferencesServiceClient', + 'EmailPreferencesServiceAsyncClient', + 'HomepageServiceClient', + 'HomepageServiceAsyncClient', + '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', + 'BusinessIdentity', + 'GetBusinessIdentityRequest', + 'UpdateBusinessIdentityRequest', + 'BusinessInfo', + 'GetBusinessInfoRequest', + 'UpdateBusinessInfoRequest', + 'CustomerService', + 'EmailPreferences', + 'GetEmailPreferencesRequest', + 'UpdateEmailPreferencesRequest', + 'ClaimHomepageRequest', + 'GetHomepageRequest', + 'Homepage', + 'UnclaimHomepageRequest', + 'UpdateHomepageRequest', + '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', + '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..558c8aab67c5 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..318d5a29d75e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/__init__.py @@ -0,0 +1,272 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.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.email_preferences_service import EmailPreferencesServiceClient +from .services.email_preferences_service import EmailPreferencesServiceAsyncClient +from .services.homepage_service import HomepageServiceClient +from .services.homepage_service import HomepageServiceAsyncClient +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.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.customerservice import CustomerService +from .types.emailpreferences import EmailPreferences +from .types.emailpreferences import GetEmailPreferencesRequest +from .types.emailpreferences import UpdateEmailPreferencesRequest +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.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.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', + 'BusinessIdentityServiceAsyncClient', + 'BusinessInfoServiceAsyncClient', + 'EmailPreferencesServiceAsyncClient', + 'HomepageServiceAsyncClient', + 'OnlineReturnPolicyServiceAsyncClient', + 'ProgramsServiceAsyncClient', + 'RegionsServiceAsyncClient', + 'ShippingSettingsServiceAsyncClient', + 'TermsOfServiceAgreementStateServiceAsyncClient', + 'TermsOfServiceServiceAsyncClient', + 'UserServiceAsyncClient', +'AcceptTermsOfServiceRequest', +'Accepted', +'AccessRight', +'Account', +'AccountAggregation', +'AccountIssue', +'AccountIssueServiceClient', +'AccountTax', +'AccountTaxServiceClient', +'AccountsServiceClient', +'Address', +'AutofeedSettings', +'AutofeedSettingsServiceClient', +'BusinessDayConfig', +'BusinessIdentity', +'BusinessIdentityServiceClient', +'BusinessInfo', +'BusinessInfoServiceClient', +'CarrierRate', +'ClaimHomepageRequest', +'CreateAndConfigureAccountRequest', +'CreateRegionRequest', +'CreateUserRequest', +'CustomerService', +'CutoffTime', +'DeleteAccountRequest', +'DeleteRegionRequest', +'DeleteUserRequest', +'DeliveryTime', +'DisableProgramRequest', +'Distance', +'EmailPreferences', +'EmailPreferencesServiceClient', +'EnableProgramRequest', +'GetAccountRequest', +'GetAccountTaxRequest', +'GetAutofeedSettingsRequest', +'GetBusinessIdentityRequest', +'GetBusinessInfoRequest', +'GetEmailPreferencesRequest', +'GetHomepageRequest', +'GetOnlineReturnPolicyRequest', +'GetProgramRequest', +'GetRegionRequest', +'GetShippingSettingsRequest', +'GetTermsOfServiceAgreementStateRequest', +'GetTermsOfServiceRequest', +'GetUserRequest', +'Headers', +'Homepage', +'HomepageServiceClient', +'InsertShippingSettingsRequest', +'ListAccountIssuesRequest', +'ListAccountIssuesResponse', +'ListAccountTaxRequest', +'ListAccountTaxResponse', +'ListAccountsRequest', +'ListAccountsResponse', +'ListOnlineReturnPoliciesRequest', +'ListOnlineReturnPoliciesResponse', +'ListProgramsRequest', +'ListProgramsResponse', +'ListRegionsRequest', +'ListRegionsResponse', +'ListSubAccountsRequest', +'ListSubAccountsResponse', +'ListUsersRequest', +'ListUsersResponse', +'LocationIdSet', +'MinimumOrderValueTable', +'OnlineReturnPolicy', +'OnlineReturnPolicyServiceClient', +'PhoneVerificationState', +'Program', +'ProgramsServiceClient', +'RateGroup', +'Region', +'RegionsServiceClient', +'Required', +'RetrieveForApplicationTermsOfServiceAgreementStateRequest', +'RetrieveLatestTermsOfServiceRequest', +'Row', +'Service', +'ShippingSettings', +'ShippingSettingsServiceClient', +'Table', +'TaxRule', +'TermsOfService', +'TermsOfServiceAgreementState', +'TermsOfServiceAgreementStateServiceClient', +'TermsOfServiceKind', +'TermsOfServiceServiceClient', +'TransitTable', +'UnclaimHomepageRequest', +'UpdateAccountRequest', +'UpdateAccountTaxRequest', +'UpdateAutofeedSettingsRequest', +'UpdateBusinessIdentityRequest', +'UpdateBusinessInfoRequest', +'UpdateEmailPreferencesRequest', +'UpdateHomepageRequest', +'UpdateRegionRequest', +'UpdateUserRequest', +'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..2e91ad70f4fb --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/gapic_metadata.json @@ -0,0 +1,969 @@ + { + "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" + ] + } + } + } + } + }, + "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" + ] + } + } + } + } + }, + "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" + ] + } + } + } + } + }, + "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" + ] + } + } + } + } + }, + "OnlineReturnPolicyService": { + "clients": { + "grpc": { + "libraryClient": "OnlineReturnPolicyServiceClient", + "rpcs": { + "GetOnlineReturnPolicy": { + "methods": [ + "get_online_return_policy" + ] + }, + "ListOnlineReturnPolicies": { + "methods": [ + "list_online_return_policies" + ] + } + } + }, + "grpc-async": { + "libraryClient": "OnlineReturnPolicyServiceAsyncClient", + "rpcs": { + "GetOnlineReturnPolicy": { + "methods": [ + "get_online_return_policy" + ] + }, + "ListOnlineReturnPolicies": { + "methods": [ + "list_online_return_policies" + ] + } + } + }, + "rest": { + "libraryClient": "OnlineReturnPolicyServiceClient", + "rpcs": { + "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/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..558c8aab67c5 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..8f6cf068242c --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..266769df6234 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..e9503e61c4e8 --- /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,381 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + + +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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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__) + + +__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..909711ad55d2 --- /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,725 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +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 + +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 + + @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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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__) + + +__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..ca38590648cd --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..7d3ac1a8d330 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..532331ca04e4 --- /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,154 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +from google.shopping.merchant_accounts_v1beta.types import accountissue + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__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..bb4547d3b27f --- /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,348 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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": 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..117c3d45e9cf --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..94e482233831 --- /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,326 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +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}", +) + + +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 + + Override in a subclass to manipulate the response + after it is returned by the AccountIssueService server but before + it is returned to user code. + """ + return response + + +@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) + 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..628a4b21d9db --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..dc7ccee2a580 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..9faa031fb5ed --- /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,616 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + + +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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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. + has_flattened_params = any([account_tax, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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__) + + +__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..0e8d18d36bd8 --- /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,949 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +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 + +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 + + @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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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. + has_flattened_params = any([account_tax, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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__) + + +__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..57914d3f1844 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..fd12652efc95 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..6ba9fea502e2 --- /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,183 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +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__) + + +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..21f42661e594 --- /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,408 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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": 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..17793cd138a7 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..70655f66c5d8 --- /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,648 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +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}", +) + + +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 + + Override in a subclass to manipulate the response + after it is returned by the AccountTaxService server but before + it is returned to user code. + """ + return response + + 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 + + Override in a subclass to manipulate the response + after it is returned by the AccountTaxService server but before + it is returned to user code. + """ + return response + + 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 + + Override in a subclass to manipulate the response + after it is returned by the AccountTaxService server but before + it is returned to user code. + """ + return response + + +@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) + 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) + 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) + 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..b59c5110eb06 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..cb03ea8db3a4 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..4cded9f2e2ae --- /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,886 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + + +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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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. + has_flattened_params = any([account, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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. + has_flattened_params = any([provider]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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__) + + +__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..07475ab32691 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/client.py @@ -0,0 +1,1236 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +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 + +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 + + @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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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. + has_flattened_params = any([account, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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. + has_flattened_params = any([provider]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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__) + + +__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..6356d2d27050 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..505cf532d8d3 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..7b3e8374c54b --- /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,225 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +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__) + + +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..8418472b4fd1 --- /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,502 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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": 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..a3ea31567fff --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..775fd9064497 --- /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,1040 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +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}", +) + + +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 + + Override in a subclass to manipulate the response + after it is returned by the AccountsService server but before + it is returned to user code. + """ + return response + + 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 + + Override in a subclass to manipulate the response + after it is returned by the AccountsService server but before + it is returned to user code. + """ + return response + + 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 + + Override in a subclass to manipulate the response + after it is returned by the AccountsService server but before + it is returned to user code. + """ + return response + + 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 + + Override in a subclass to manipulate the response + after it is returned by the AccountsService server but before + it is returned to user code. + """ + return response + + 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 + + Override in a subclass to manipulate the response + after it is returned by the AccountsService server but before + it is returned to user code. + """ + return response + + +@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) + 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) + 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) + 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) + 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) + 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..8a547efca106 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..079803161c63 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..af945a48f410 --- /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,487 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + + +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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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. + has_flattened_params = any([autofeed_settings, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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__) + + +__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..18ea9e4ac96a --- /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,821 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +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 + +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 + + @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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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. + has_flattened_params = any([autofeed_settings, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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__) + + +__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..f77c8df5619d --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..79fd8e040bd9 --- /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,168 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +from google.shopping.merchant_accounts_v1beta.types import autofeedsettings + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__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..a0358f56213b --- /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,375 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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": 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..705eacb0c8d5 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..8236dac96ef3 --- /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,488 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +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}", +) + + +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 + + Override in a subclass to manipulate the response + after it is returned by the AutofeedSettingsService server but before + it is returned to user code. + """ + return response + + 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 + + Override in a subclass to manipulate the response + after it is returned by the AutofeedSettingsService server but before + it is returned to user code. + """ + return response + + +@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) + 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) + 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..243dd3a73556 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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/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..c720f6ef6465 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..3fc16718c2dc --- /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,482 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + + +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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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. + has_flattened_params = any([business_identity, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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__) + + +__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..8c285b247d01 --- /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,816 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +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 + +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 + + @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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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. + has_flattened_params = any([business_identity, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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__) + + +__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..331360c90e76 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..04147a3cf376 --- /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,168 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +from google.shopping.merchant_accounts_v1beta.types import businessidentity + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__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..b842c052ef2f --- /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,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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": 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..0494ae9d2304 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..449743d9e404 --- /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,486 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +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}", +) + + +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 + + Override in a subclass to manipulate the response + after it is returned by the BusinessIdentityService server but before + it is returned to user code. + """ + return response + + 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 + + Override in a subclass to manipulate the response + after it is returned by the BusinessIdentityService server but before + it is returned to user code. + """ + return response + + +@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) + 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) + 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..dd2ca0b66710 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..ceb79842fbe1 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..101f2e6168bd --- /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,482 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + + +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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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. + has_flattened_params = any([business_info, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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__) + + +__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..a0f87fdc71e7 --- /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,816 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +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 + +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 + + @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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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. + has_flattened_params = any([business_info, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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__) + + +__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..274100f41ddd --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..7e60c990d585 --- /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,168 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +from google.shopping.merchant_accounts_v1beta.types import businessinfo + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__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..83df498315db --- /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,374 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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": 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..f5f481ad4dd3 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..bf369d8b06a5 --- /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,483 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +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}", +) + + +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 + + Override in a subclass to manipulate the response + after it is returned by the BusinessInfoService server but before + it is returned to user code. + """ + return response + + 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 + + Override in a subclass to manipulate the response + after it is returned by the BusinessInfoService server but before + it is returned to user code. + """ + return response + + +@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) + 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) + 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..9dd05d0d0e84 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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/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..3b89b734458b --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..2025e9f6ab65 --- /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,505 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + + +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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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. + has_flattened_params = any([email_preferences, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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__) + + +__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..9af5ad2142ad --- /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,839 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +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 + +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 + + @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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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. + has_flattened_params = any([email_preferences, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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__) + + +__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..bfac5d58e755 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..ec960b5edb80 --- /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,168 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +from google.shopping.merchant_accounts_v1beta.types import emailpreferences + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__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..437d3cfdfa0e --- /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,391 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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": 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..9f1da19e5162 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..e92910584cb3 --- /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,494 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +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}", +) + + +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 + + Override in a subclass to manipulate the response + after it is returned by the EmailPreferencesService server but before + it is returned to user code. + """ + return response + + 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 + + Override in a subclass to manipulate the response + after it is returned by the EmailPreferencesService server but before + it is returned to user code. + """ + return response + + +@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) + 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) + 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..68848b7d725f --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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/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..7663facd372f --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..f32e8c0c1c55 --- /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,652 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + + +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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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. + has_flattened_params = any([homepage, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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__) + + +__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..d08371ef6aa8 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/client.py @@ -0,0 +1,986 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +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 + +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 + + @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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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. + has_flattened_params = any([homepage, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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__) + + +__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..95447852f5f7 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..54662840fef4 --- /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,197 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +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__) + + +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..a78f5f24bddd --- /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,440 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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": 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..88fd8df21b64 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..dfe9e111d0a5 --- /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,786 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +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}", +) + + +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 + + Override in a subclass to manipulate the response + after it is returned by the HomepageService server but before + it is returned to user code. + """ + return response + + 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 + + Override in a subclass to manipulate the response + after it is returned by the HomepageService server but before + it is returned to user code. + """ + return response + + 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 + + Override in a subclass to manipulate the response + after it is returned by the HomepageService server but before + it is returned to user code. + """ + return response + + 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 + + Override in a subclass to manipulate the response + after it is returned by the HomepageService server but before + it is returned to user code. + """ + return response + + +@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) + 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) + 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) + 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) + 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..7a2a3cda1a43 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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/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..49d3ae985198 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..2f537ce3aec3 --- /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,495 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + + +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.online_return_policy_service import pagers +from google.shopping.merchant_accounts_v1beta.types import 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][google.shopping.merchant.accounts.v1.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. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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 __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__) + + +__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..55ded2bab7e1 --- /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,829 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +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 + +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.online_return_policy_service import pagers +from google.shopping.merchant_accounts_v1beta.types import 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][google.shopping.merchant.accounts.v1.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 + + @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. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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 __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__) + + +__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..03ddb28ea678 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..185a1b964bb8 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..a9cbe075a021 --- /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,168 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +from google.shopping.merchant_accounts_v1beta.types import online_return_policy + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__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, + ), + } + + 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 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..0c232f858e54 --- /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,380 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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": 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][google.shopping.merchant.accounts.v1.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. + + 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. + + 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'] + + 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..54ea1d39efee --- /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,405 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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][google.shopping.merchant.accounts.v1.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. + + 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. + + 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'] + + 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, + ), + } + + 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..ef4f8dd6fcc2 --- /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,492 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +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 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}", +) + + +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_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_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 + + Override in a subclass to manipulate the response + after it is returned by the OnlineReturnPolicyService server but before + it is returned to user code. + """ + return response + + 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 + + Override in a subclass to manipulate the response + after it is returned by the OnlineReturnPolicyService server but before + it is returned to user code. + """ + return response + + +@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][google.shopping.merchant.accounts.v1.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 _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) + 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) + 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 + + @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/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..d34308a0f56e --- /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,165 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.shopping.merchant_accounts_v1beta.types import 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 _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 + + +__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..54ae601f5e5f --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..ba66bd9b1c76 --- /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,732 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + + +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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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__) + + +__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..43046d235b6e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/client.py @@ -0,0 +1,1064 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +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 + +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 + + @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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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__) + + +__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..7e1cf40e5eb3 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..5346fb704ec9 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..d08a04b549f7 --- /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,196 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +from google.shopping.merchant_accounts_v1beta.types import programs + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__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..45c96b2f5d6d --- /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,438 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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": 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..05fb658e1ac8 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..6c37f016a260 --- /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,825 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +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}", +) + + +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 + + Override in a subclass to manipulate the response + after it is returned by the ProgramsService server but before + it is returned to user code. + """ + return response + + 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 + + Override in a subclass to manipulate the response + after it is returned by the ProgramsService server but before + it is returned to user code. + """ + return response + + 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 + + Override in a subclass to manipulate the response + after it is returned by the ProgramsService server but before + it is returned to user code. + """ + return response + + 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 + + Override in a subclass to manipulate the response + after it is returned by the ProgramsService server but before + it is returned to user code. + """ + return response + + +@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) + 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) + 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) + 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) + 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..d655a4dd9c23 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..3a01b7c4e379 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..aab517b9c5be --- /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,838 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + + +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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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. + has_flattened_params = any([parent, region, region_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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. + has_flattened_params = any([region, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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__) + + +__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..c525551dbb89 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/client.py @@ -0,0 +1,1178 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +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 + +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 + + @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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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. + has_flattened_params = any([parent, region, region_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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. + has_flattened_params = any([region, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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__) + + +__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..97a6b74f8db0 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..2a572b340874 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..4f87d6c90f91 --- /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,211 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +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__) + + +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..8c66faf52e80 --- /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,460 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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": 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..4e9d5ca02979 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..515315bffc21 --- /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,916 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +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}", +) + + +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 + + Override in a subclass to manipulate the response + after it is returned by the RegionsService server but before + it is returned to user code. + """ + return response + + 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 + + Override in a subclass to manipulate the response + after it is returned by the RegionsService server but before + it is returned to user code. + """ + return response + + 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 + + Override in a subclass to manipulate the response + after it is returned by the RegionsService server but before + it is returned to user code. + """ + return response + + 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 + + Override in a subclass to manipulate the response + after it is returned by the RegionsService server but before + it is returned to user code. + """ + return response + + +@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) + 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) + 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) + 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) + 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..5cc267d8dbfd --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..fa901053fc1c --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..1a45b3ddf30a --- /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,456 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + + +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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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__) + + +__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..7d5c4d4a00c4 --- /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,791 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +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 + +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 + + @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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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__) + + +__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..8aeb06735a46 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..ebd259ebf3f0 --- /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,168 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +from google.shopping.merchant_accounts_v1beta.types import shippingsettings + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__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..15c67b475038 --- /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,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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": 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..86019f047c2b --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..5117048f626b --- /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,485 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +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}", +) + + +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 + + Override in a subclass to manipulate the response + after it is returned by the ShippingSettingsService server but before + it is returned to user code. + """ + return response + + 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 + + Override in a subclass to manipulate the response + after it is returned by the ShippingSettingsService server but before + it is returned to user code. + """ + return response + + +@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) + 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) + 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..0bbaf23e8edc --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..cfe172e0b198 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..fc9d58453ea2 --- /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,530 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + + +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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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__) + + +__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..12c15168100e --- /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,882 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +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 + +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 + + @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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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__) + + +__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..4393be637fb9 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..f809d493d988 --- /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,168 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +from google.shopping.merchant_accounts_v1beta.types import termsofserviceagreementstate + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__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..27b8885f55d5 --- /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,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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": 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..3acaed44b44a --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..9558c58cfc1b --- /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,537 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +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}", +) + + +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 + + Override in a subclass to manipulate the response + after it is returned by the TermsOfServiceAgreementStateService server but before + it is returned to user code. + """ + return response + + 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 + + Override in a subclass to manipulate the response + after it is returned by the TermsOfServiceAgreementStateService server but before + it is returned to user code. + """ + return response + + +@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) + 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) + 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..7406306d5a45 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..0cfe241dba09 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..030a3dab3ead --- /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,537 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + + +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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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__) + + +__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..c15b6a74b682 --- /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,880 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +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 + +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 + + @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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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__) + + +__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..1f834296e0ab --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..1af8eed547b8 --- /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,183 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +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__) + + +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..43be17d82f5c --- /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,404 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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": 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..9b1c9d1a9baa --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..b401dd92c3b8 --- /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,584 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +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}", +) + + +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 + + Override in a subclass to manipulate the response + after it is returned by the TermsOfServiceService server but before + it is returned to user code. + """ + return response + + 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 + + Override in a subclass to manipulate the response + after it is returned by the TermsOfServiceService server but before + it is returned to user code. + """ + return response + + +@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) + 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) + 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..d61a64f98e4b --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..5367640a86a5 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..cfd38f521157 --- /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,818 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + + +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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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. + has_flattened_params = any([parent, user]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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. + has_flattened_params = any([user, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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__) + + +__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..c695f01ed825 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/client.py @@ -0,0 +1,1158 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +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 + +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 + + @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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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. + has_flattened_params = any([parent, user]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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. + has_flattened_params = any([user, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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__) + + +__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..b9cddefd01aa --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..028705f02f0c --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..7da483265bab --- /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,212 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +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__) + + +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..c85680b7e0ec --- /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,456 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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": 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..a9a8b7ddf427 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..a49dbc0f998d --- /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,895 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +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}", +) + + +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 + + Override in a subclass to manipulate the response + after it is returned by the UserService server but before + it is returned to user code. + """ + return response + + 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 + + Override in a subclass to manipulate the response + after it is returned by the UserService server but before + it is returned to user code. + """ + return response + + 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 + + Override in a subclass to manipulate the response + after it is returned by the UserService server but before + it is returned to user code. + """ + return response + + 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 + + Override in a subclass to manipulate the response + after it is returned by the UserService server but before + it is returned to user code. + """ + return response + + +@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) + 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) + 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) + 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) + 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..5e1474d1c78b --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..ea23eb6e2954 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/__init__.py @@ -0,0 +1,248 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 .businessidentity import ( + BusinessIdentity, + GetBusinessIdentityRequest, + UpdateBusinessIdentityRequest, +) +from .businessinfo import ( + BusinessInfo, + GetBusinessInfoRequest, + UpdateBusinessInfoRequest, +) +from .customerservice import ( + CustomerService, +) +from .emailpreferences import ( + EmailPreferences, + GetEmailPreferencesRequest, + UpdateEmailPreferencesRequest, +) +from .homepage import ( + ClaimHomepageRequest, + GetHomepageRequest, + Homepage, + UnclaimHomepageRequest, + UpdateHomepageRequest, +) +from .online_return_policy import ( + 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 .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', + 'BusinessIdentity', + 'GetBusinessIdentityRequest', + 'UpdateBusinessIdentityRequest', + 'BusinessInfo', + 'GetBusinessInfoRequest', + 'UpdateBusinessInfoRequest', + 'CustomerService', + 'EmailPreferences', + 'GetEmailPreferencesRequest', + 'UpdateEmailPreferencesRequest', + 'ClaimHomepageRequest', + 'GetHomepageRequest', + 'Homepage', + 'UnclaimHomepageRequest', + 'UpdateHomepageRequest', + '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', + '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..754ebc65ee0e --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..94795715b3e8 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..5883b13df300 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..0b3a362e2bef --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..b14c5cfc61a1 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..4383692d8ccd --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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/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..3e590207367f --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..f7a342780cbf --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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/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..09c919f682c2 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..61fea52c8d1f --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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/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..a8bfd8550b31 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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/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..1cb4f330d0b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/online_return_policy.py @@ -0,0 +1,405 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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={ + 'GetOnlineReturnPolicyRequest', + '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 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): + 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]): + 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): + The return policy. + restocking_fee (google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy.RestockingFee): + 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]): + 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]): + 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): + The return shipping fee. Should be set only + when customer need to download and print the + return label. + return_policy_uri (str): + 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): + This field specifies if merchant only accepts + defective products for returns, and this field + is required. + + This field is a member of `oneof`_ ``_accept_defective_only``. + process_refund_days (int): + The field specifies the number of days it + takes for merchants to process refunds, field is + optional. + + This field is a member of `oneof`_ ``_process_refund_days``. + accept_exchange (bool): + This field specifies if merchant allows + customers to exchange products, this field is + required. + + This field is a member of `oneof`_ ``_accept_exchange``. + """ + 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 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): + 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, + ) + + 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, + ) + 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, + ) + + +__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..65d576169d52 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..a4ff77a9cbd1 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..1d8c28848f9c --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..49cb31fe9c2b --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..28bee59aae61 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..99e929d02081 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..ca3a0d6ebb90 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..52f6fb1fa16a --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..b79f03472590 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..4263f2250023 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/noxfile.py @@ -0,0 +1,280 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = 'google-shopping-merchant-accounts' + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.13" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "prerelease_deps", +] + +@nox.session(python=ALL_PYTHON) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def unit(session, protobuf_implementation): + """Run the unit test suite.""" + + 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+") + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") + + # 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") + + session.run( + 'py.test', + '--quiet', + '--cov=google/shopping/merchant_accounts_v1beta/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)), + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + +@nox.session(python=ALL_PYTHON[-1]) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def prerelease_deps(session, protobuf_implementation): + """Run the unit test suite against pre-release versions of dependencies.""" + + 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 test environment dependencies + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + + # Install the package without dependencies + session.install('-e', '.', '--no-deps') + + # We test the minimum dependency versions using the minimum Python + # version so the lowest python runtime that we test has a corresponding constraints + # file, located at `testing/constraints--.txt`, which contains all of the + # 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 + ) + ] + + session.install(*constraints_deps) + + prerel_deps = [ + "googleapis-common-protos", + "google-api-core", + "google-auth", + # Exclude grpcio!=1.67.0rc1 which does not support python 3.13 + "grpcio!=1.67.0rc1", + "grpcio-status", + "protobuf", + "proto-plus", + ] + + for dep in prerel_deps: + session.install("--pre", "--no-deps", "--upgrade", dep) + + # Remaining dependencies + other_deps = [ + "requests", + ] + session.install(*other_deps) + + # Print out prerelease package versions + + session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") + session.run("python", "-c", "import google.auth; print(google.auth.__version__)") + session.run("python", "-c", "import grpc; print(grpc.__version__)") + session.run( + "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" + ) + session.run( + "python", "-c", "import proto; print(proto.__version__)" + ) + + session.run( + 'py.test', + '--quiet', + '--cov=google/shopping/merchant_accounts_v1beta/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)), + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + + +@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=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 docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==7.0.1", "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=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", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) 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..5722ba346d36 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..65df4005dfdf --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..72f642dd82c3 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..06126d7f847f --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..a33b7617b4d6 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..c03510d4a8d0 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..9e0fa6b733f1 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..d0fc79fce477 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..0f317ab185f3 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..7fc130048baa --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..5325080df363 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..e22bf5b78853 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..7df8d70104f2 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..bb4d4006ad51 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..490f8a95ab51 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..61e728a1ec1d --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..64c1620e14b1 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..f0e31a111510 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..ad622e5013b6 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..9d9c51fc483b --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..d207adb015ce --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..d0cadcbcce63 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..68d50c7746e8 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..98f5f24a8c97 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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..8637e25620b7 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..235ce1598afa --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..089129c55615 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..b44f9ec5d2bf --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..15a59aa09700 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..0e27da028a6e --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..fdefa869c879 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..27702757d482 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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..9f26a449a0c3 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..30fb5c58c714 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..24812e4eca3a --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..12030b2c4e83 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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..17dc74c7d647 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..1ba1650aaccc --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..b098778ce5f9 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..f61ef0d4a6ec --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..e8a1f01c1c48 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..3f1b53762486 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..46218f36725d --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..4e43a500a08e --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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..cb00645bdc37 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..c9390dec8f0f --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..0e74c48947e7 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..26e715bdb847 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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..8a9d70bedb0e --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..6c2c98163a78 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..819600faa170 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..99292b26bd59 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..970c08050862 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..3e9f77650ab4 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..d0db1b835c94 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..9adaa3cdd367 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..7780f650a625 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..ab3f7a11f344 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..56093b2280b2 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..551e26a180d2 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..d62409ec8d9c --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..55d6dd0fc8d4 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..a3e8a1dfdb63 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..bbe022c4a0d4 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..f81c160ad52a --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..d280034963fd --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..46fc3d734b0b --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..2d5a2e5a10ab --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..a2c94110d1ab --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..59a1ff9da8d8 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..1dc53b7d9cca --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..b9f49f6bf873 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..6920a1e22519 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..acd3fb9382ba --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..f5cb63fabba4 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..12311a6c102d --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..e6038b8b6dbf --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..9bcf47546578 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..918d61da5083 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..afb5673b7735 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..5d4bf482dfc6 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..7c17505acc95 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..34e267d75fb7 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..6cae572837e2 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..c41cdd33e146 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..6075da0fd471 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..cf6db7d5238e --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..b9a963bd4995 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..e8d801d3ffcb --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..e66e4bcdc87e --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..c736f9d3c831 --- /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,7284 @@ +{ + "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.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.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.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.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.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..a7c0d0a5f668 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/scripts/fixup_merchant_accounts_v1beta_keywords.py @@ -0,0 +1,220 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_region': ('parent', 'region_id', 'region', ), + 'create_user': ('parent', 'user_id', 'user', ), + 'delete_account': ('name', 'force', ), + 'delete_region': ('name', ), + 'delete_user': ('name', ), + 'disable_program': ('name', ), + 'enable_program': ('name', ), + 'get_account': ('name', ), + 'get_account_tax': ('name', ), + 'get_autofeed_settings': ('name', ), + 'get_business_identity': ('name', ), + 'get_business_info': ('name', ), + 'get_email_preferences': ('name', ), + 'get_homepage': ('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', ), + '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_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', ), + '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_business_identity': ('business_identity', 'update_mask', ), + 'update_business_info': ('business_info', 'update_mask', ), + 'update_email_preferences': ('email_preferences', 'update_mask', ), + 'update_homepage': ('homepage', '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..16452374d8e5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/setup.py @@ -0,0 +1,99 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.0dev,!=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.0dev,!=2.24.0,!=2.25.0", + "proto-plus >= 1.22.3, <2.0.0dev", + "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'", + "protobuf>=3.20.2,<6.0.0dev,!=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.0dev", +] +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..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/testing/constraints-3.13.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.7.txt b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/testing/constraints-3.7.txt new file mode 100644 index 000000000000..130a0c0f80ab --- /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.0dev", +# 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..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..7b3de3117f38 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..0613303422bb --- /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,2368 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + + +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("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, "pre_list_account_issues") as pre: + pre.assert_not_called() + post.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() + + client.list_account_issues(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.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..cdaf84a4908e --- /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,3745 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + + +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("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, "pre_get_account_tax") as pre: + pre.assert_not_called() + post.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() + + client.get_account_tax(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.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, "pre_list_account_tax") as pre: + pre.assert_not_called() + post.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() + + client.list_account_tax(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.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, "pre_update_account_tax") as pre: + pre.assert_not_called() + post.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() + + client.update_account_tax(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.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..bf85eeb78b34 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_accounts_service.py @@ -0,0 +1,5584 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + + +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("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, "pre_get_account") as pre: + pre.assert_not_called() + post.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() + + client.get_account(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.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, "pre_create_and_configure_account") as pre: + pre.assert_not_called() + post.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() + + client.create_and_configure_account(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.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, "pre_update_account") as pre: + pre.assert_not_called() + post.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() + + client.update_account(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.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, "pre_list_accounts") as pre: + pre.assert_not_called() + post.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() + + client.list_accounts(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.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, "pre_list_sub_accounts") as pre: + pre.assert_not_called() + post.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() + + client.list_sub_accounts(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.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..3b21d628d5b5 --- /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,2836 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + + +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("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, "pre_get_autofeed_settings") as pre: + pre.assert_not_called() + post.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() + + client.get_autofeed_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.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, "pre_update_autofeed_settings") as pre: + pre.assert_not_called() + post.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() + + client.update_autofeed_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.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_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..13d76968fa62 --- /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,2822 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + + +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("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, "pre_get_business_identity") as pre: + pre.assert_not_called() + post.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() + + client.get_business_identity(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.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, "pre_update_business_identity") as pre: + pre.assert_not_called() + post.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() + + client.update_business_identity(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.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..77de09debf4e --- /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,2840 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + + +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("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, "pre_get_business_info") as pre: + pre.assert_not_called() + post.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() + + client.get_business_info(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.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, "pre_update_business_info") as pre: + pre.assert_not_called() + post.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() + + client.update_business_info(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.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_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..211d200f402e --- /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,2824 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + + +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("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, "pre_get_email_preferences") as pre: + pre.assert_not_called() + post.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() + + client.get_email_preferences(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.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, "pre_update_email_preferences") as pre: + pre.assert_not_called() + post.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() + + client.update_email_preferences(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.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_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..c5594a3ab51b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_homepage_service.py @@ -0,0 +1,3903 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + + +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("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, "pre_get_homepage") as pre: + pre.assert_not_called() + post.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() + + client.get_homepage(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.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, "pre_update_homepage") as pre: + pre.assert_not_called() + post.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() + + client.update_homepage(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.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, "pre_claim_homepage") as pre: + pre.assert_not_called() + post.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() + + client.claim_homepage(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.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, "pre_unclaim_homepage") as pre: + pre.assert_not_called() + post.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() + + client.unclaim_homepage(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.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_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..a1577750c65b --- /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,3064 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.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 +import google.auth + + +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("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, + ) + 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 + + +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, + )) + 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 + + +@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 + + +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_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 + + +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, + )) + 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 + + +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, + ) + + # 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 + + +@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, "pre_get_online_return_policy") as pre: + pre.assert_not_called() + post.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() + + client.get_online_return_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.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, "pre_list_online_return_policies") as pre: + pre.assert_not_called() + post.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() + + client.list_online_return_policies(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.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 + + +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', + ) + 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 +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..fa7b0e226a28 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_programs_service.py @@ -0,0 +1,4373 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + + +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("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, "pre_get_program") as pre: + pre.assert_not_called() + post.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() + + client.get_program(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.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, "pre_list_programs") as pre: + pre.assert_not_called() + post.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() + + client.list_programs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.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, "pre_enable_program") as pre: + pre.assert_not_called() + post.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() + + client.enable_program(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.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, "pre_disable_program") as pre: + pre.assert_not_called() + post.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() + + client.disable_program(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.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..34411b7adaa9 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_regions_service.py @@ -0,0 +1,5154 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + + +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("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, "pre_get_region") as pre: + pre.assert_not_called() + post.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() + + client.get_region(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.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, "pre_create_region") as pre: + pre.assert_not_called() + post.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() + + client.create_region(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.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, "pre_update_region") as pre: + pre.assert_not_called() + post.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() + + client.update_region(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.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, "pre_list_regions") as pre: + pre.assert_not_called() + post.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() + + client.list_regions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.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..13390f0eef2e --- /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,2679 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + + +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("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, "pre_get_shipping_settings") as pre: + pre.assert_not_called() + post.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() + + client.get_shipping_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.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, "pre_insert_shipping_settings") as pre: + pre.assert_not_called() + post.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() + + client.insert_shipping_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.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..71aded2117e2 --- /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,2800 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + + +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("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, "pre_get_terms_of_service_agreement_state") as pre: + pre.assert_not_called() + post.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() + + client.get_terms_of_service_agreement_state(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.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, "pre_retrieve_for_application_terms_of_service_agreement_state") as pre: + pre.assert_not_called() + post.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() + + client.retrieve_for_application_terms_of_service_agreement_state(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.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..92972500297c --- /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,3277 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + + +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("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, "pre_get_terms_of_service") as pre: + pre.assert_not_called() + post.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() + + client.get_terms_of_service(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.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, "pre_retrieve_latest_terms_of_service") as pre: + pre.assert_not_called() + post.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() + + client.retrieve_latest_terms_of_service(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.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..a03be666c985 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_user_service.py @@ -0,0 +1,5164 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + + +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("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, "pre_get_user") as pre: + pre.assert_not_called() + post.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() + + client.get_user(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.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, "pre_create_user") as pre: + pre.assert_not_called() + post.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() + + client.create_user(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.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, "pre_update_user") as pre: + pre.assert_not_called() + post.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() + + client.update_user(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.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, "pre_list_users") as pre: + pre.assert_not_called() + post.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() + + client.list_users(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.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/owl-bot-staging/google-shopping-merchant-conversions/v1beta/.coveragerc b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/.coveragerc new file mode 100644 index 000000000000..e78537d68443 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/shopping/merchant_conversions/__init__.py + google/shopping/merchant_conversions/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-conversions/v1beta/.flake8 b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/MANIFEST.in b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/MANIFEST.in new file mode 100644 index 000000000000..ef3463ac8c12 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/shopping/merchant_conversions *.py +recursive-include google/shopping/merchant_conversions_v1beta *.py diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/README.rst b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/README.rst new file mode 100644 index 000000000000..66f641dd8095 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Shopping Merchant Conversions 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 Conversions 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 diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/_static/custom.css b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/conf.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/conf.py new file mode 100644 index 000000000000..a0a048b37435 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-conversions 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("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# 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.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +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-conversions" +copyright = u"2023, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# 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 = 'en' + +# 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"] + +# 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 Python", + "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-conversions-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-conversions.tex", + u"google-shopping-merchant-conversions 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-conversions", + u"Google Shopping Merchant Conversions 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-conversions", + u"google-shopping-merchant-conversions Documentation", + author, + "google-shopping-merchant-conversions", + "GAPIC library for Google Shopping Merchant Conversions API", + "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": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", 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-conversions/v1beta/docs/index.rst b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/index.rst new file mode 100644 index 000000000000..5a1068587e37 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + merchant_conversions_v1beta/services_ + merchant_conversions_v1beta/types_ diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/merchant_conversions_v1beta/conversion_sources_service.rst b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/merchant_conversions_v1beta/conversion_sources_service.rst new file mode 100644 index 000000000000..150c70129c9d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/merchant_conversions_v1beta/conversion_sources_service.rst @@ -0,0 +1,10 @@ +ConversionSourcesService +------------------------------------------ + +.. automodule:: google.shopping.merchant_conversions_v1beta.services.conversion_sources_service + :members: + :inherited-members: + +.. automodule:: google.shopping.merchant_conversions_v1beta.services.conversion_sources_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/merchant_conversions_v1beta/services_.rst b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/merchant_conversions_v1beta/services_.rst new file mode 100644 index 000000000000..20f2386f1792 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/merchant_conversions_v1beta/services_.rst @@ -0,0 +1,6 @@ +Services for Google Shopping Merchant Conversions v1beta API +============================================================ +.. toctree:: + :maxdepth: 2 + + conversion_sources_service diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/merchant_conversions_v1beta/types_.rst b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/merchant_conversions_v1beta/types_.rst new file mode 100644 index 000000000000..87217f29174d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/merchant_conversions_v1beta/types_.rst @@ -0,0 +1,6 @@ +Types for Google Shopping Merchant Conversions v1beta API +========================================================= + +.. automodule:: google.shopping.merchant_conversions_v1beta.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions/__init__.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions/__init__.py new file mode 100644 index 000000000000..74447f78c463 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions/__init__.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_conversions import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.shopping.merchant_conversions_v1beta.services.conversion_sources_service.client import ConversionSourcesServiceClient +from google.shopping.merchant_conversions_v1beta.services.conversion_sources_service.async_client import ConversionSourcesServiceAsyncClient + +from google.shopping.merchant_conversions_v1beta.types.conversionsources import AttributionSettings +from google.shopping.merchant_conversions_v1beta.types.conversionsources import ConversionSource +from google.shopping.merchant_conversions_v1beta.types.conversionsources import CreateConversionSourceRequest +from google.shopping.merchant_conversions_v1beta.types.conversionsources import DeleteConversionSourceRequest +from google.shopping.merchant_conversions_v1beta.types.conversionsources import GetConversionSourceRequest +from google.shopping.merchant_conversions_v1beta.types.conversionsources import GoogleAnalyticsLink +from google.shopping.merchant_conversions_v1beta.types.conversionsources import ListConversionSourcesRequest +from google.shopping.merchant_conversions_v1beta.types.conversionsources import ListConversionSourcesResponse +from google.shopping.merchant_conversions_v1beta.types.conversionsources import MerchantCenterDestination +from google.shopping.merchant_conversions_v1beta.types.conversionsources import UndeleteConversionSourceRequest +from google.shopping.merchant_conversions_v1beta.types.conversionsources import UpdateConversionSourceRequest + +__all__ = ('ConversionSourcesServiceClient', + 'ConversionSourcesServiceAsyncClient', + 'AttributionSettings', + 'ConversionSource', + 'CreateConversionSourceRequest', + 'DeleteConversionSourceRequest', + 'GetConversionSourceRequest', + 'GoogleAnalyticsLink', + 'ListConversionSourcesRequest', + 'ListConversionSourcesResponse', + 'MerchantCenterDestination', + 'UndeleteConversionSourceRequest', + 'UpdateConversionSourceRequest', +) diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions/gapic_version.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-conversions/v1beta/google/shopping/merchant_conversions/py.typed b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions/py.typed new file mode 100644 index 000000000000..5298041b15c6 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-shopping-merchant-conversions package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/__init__.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/__init__.py new file mode 100644 index 000000000000..eb3146fd7511 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/__init__.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_conversions_v1beta import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.conversion_sources_service import ConversionSourcesServiceClient +from .services.conversion_sources_service import ConversionSourcesServiceAsyncClient + +from .types.conversionsources import AttributionSettings +from .types.conversionsources import ConversionSource +from .types.conversionsources import CreateConversionSourceRequest +from .types.conversionsources import DeleteConversionSourceRequest +from .types.conversionsources import GetConversionSourceRequest +from .types.conversionsources import GoogleAnalyticsLink +from .types.conversionsources import ListConversionSourcesRequest +from .types.conversionsources import ListConversionSourcesResponse +from .types.conversionsources import MerchantCenterDestination +from .types.conversionsources import UndeleteConversionSourceRequest +from .types.conversionsources import UpdateConversionSourceRequest + +__all__ = ( + 'ConversionSourcesServiceAsyncClient', +'AttributionSettings', +'ConversionSource', +'ConversionSourcesServiceClient', +'CreateConversionSourceRequest', +'DeleteConversionSourceRequest', +'GetConversionSourceRequest', +'GoogleAnalyticsLink', +'ListConversionSourcesRequest', +'ListConversionSourcesResponse', +'MerchantCenterDestination', +'UndeleteConversionSourceRequest', +'UpdateConversionSourceRequest', +) diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/gapic_metadata.json b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/gapic_metadata.json new file mode 100644 index 000000000000..6f24b73d5d87 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/gapic_metadata.json @@ -0,0 +1,118 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.shopping.merchant_conversions_v1beta", + "protoPackage": "google.shopping.merchant.conversions.v1beta", + "schema": "1.0", + "services": { + "ConversionSourcesService": { + "clients": { + "grpc": { + "libraryClient": "ConversionSourcesServiceClient", + "rpcs": { + "CreateConversionSource": { + "methods": [ + "create_conversion_source" + ] + }, + "DeleteConversionSource": { + "methods": [ + "delete_conversion_source" + ] + }, + "GetConversionSource": { + "methods": [ + "get_conversion_source" + ] + }, + "ListConversionSources": { + "methods": [ + "list_conversion_sources" + ] + }, + "UndeleteConversionSource": { + "methods": [ + "undelete_conversion_source" + ] + }, + "UpdateConversionSource": { + "methods": [ + "update_conversion_source" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ConversionSourcesServiceAsyncClient", + "rpcs": { + "CreateConversionSource": { + "methods": [ + "create_conversion_source" + ] + }, + "DeleteConversionSource": { + "methods": [ + "delete_conversion_source" + ] + }, + "GetConversionSource": { + "methods": [ + "get_conversion_source" + ] + }, + "ListConversionSources": { + "methods": [ + "list_conversion_sources" + ] + }, + "UndeleteConversionSource": { + "methods": [ + "undelete_conversion_source" + ] + }, + "UpdateConversionSource": { + "methods": [ + "update_conversion_source" + ] + } + } + }, + "rest": { + "libraryClient": "ConversionSourcesServiceClient", + "rpcs": { + "CreateConversionSource": { + "methods": [ + "create_conversion_source" + ] + }, + "DeleteConversionSource": { + "methods": [ + "delete_conversion_source" + ] + }, + "GetConversionSource": { + "methods": [ + "get_conversion_source" + ] + }, + "ListConversionSources": { + "methods": [ + "list_conversion_sources" + ] + }, + "UndeleteConversionSource": { + "methods": [ + "undelete_conversion_source" + ] + }, + "UpdateConversionSource": { + "methods": [ + "update_conversion_source" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/gapic_version.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-conversions/v1beta/google/shopping/merchant_conversions_v1beta/py.typed b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/py.typed new file mode 100644 index 000000000000..5298041b15c6 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-shopping-merchant-conversions package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/__init__.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/__init__.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/__init__.py new file mode 100644 index 000000000000..25d8d15c4cc5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 ConversionSourcesServiceClient +from .async_client import ConversionSourcesServiceAsyncClient + +__all__ = ( + 'ConversionSourcesServiceClient', + 'ConversionSourcesServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/async_client.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/async_client.py new file mode 100644 index 000000000000..6a1a53b2bd0c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/async_client.py @@ -0,0 +1,928 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_conversions_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 + + +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 timestamp_pb2 # type: ignore +from google.shopping.merchant_conversions_v1beta.services.conversion_sources_service import pagers +from google.shopping.merchant_conversions_v1beta.types import conversionsources +from .transports.base import ConversionSourcesServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ConversionSourcesServiceGrpcAsyncIOTransport +from .client import ConversionSourcesServiceClient + +try: + from google.api_core import client_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 ConversionSourcesServiceAsyncClient: + """Service for managing conversion sources for a merchant + account. + """ + + _client: ConversionSourcesServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = ConversionSourcesServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ConversionSourcesServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = ConversionSourcesServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = ConversionSourcesServiceClient._DEFAULT_UNIVERSE + + conversion_source_path = staticmethod(ConversionSourcesServiceClient.conversion_source_path) + parse_conversion_source_path = staticmethod(ConversionSourcesServiceClient.parse_conversion_source_path) + common_billing_account_path = staticmethod(ConversionSourcesServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ConversionSourcesServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ConversionSourcesServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(ConversionSourcesServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(ConversionSourcesServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(ConversionSourcesServiceClient.parse_common_organization_path) + common_project_path = staticmethod(ConversionSourcesServiceClient.common_project_path) + parse_common_project_path = staticmethod(ConversionSourcesServiceClient.parse_common_project_path) + common_location_path = staticmethod(ConversionSourcesServiceClient.common_location_path) + parse_common_location_path = staticmethod(ConversionSourcesServiceClient.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: + ConversionSourcesServiceAsyncClient: The constructed client. + """ + return ConversionSourcesServiceClient.from_service_account_info.__func__(ConversionSourcesServiceAsyncClient, 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: + ConversionSourcesServiceAsyncClient: The constructed client. + """ + return ConversionSourcesServiceClient.from_service_account_file.__func__(ConversionSourcesServiceAsyncClient, 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 ConversionSourcesServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ConversionSourcesServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ConversionSourcesServiceTransport: 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 = ConversionSourcesServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, ConversionSourcesServiceTransport, Callable[..., ConversionSourcesServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the conversion sources 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,ConversionSourcesServiceTransport,Callable[..., ConversionSourcesServiceTransport]]]): + 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 ConversionSourcesServiceTransport 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 = ConversionSourcesServiceClient( + 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.conversions_v1beta.ConversionSourcesServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", + "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.conversions.v1beta.ConversionSourcesService", + "credentialsType": None, + } + ) + + async def create_conversion_source(self, + request: Optional[Union[conversionsources.CreateConversionSourceRequest, dict]] = None, + *, + parent: Optional[str] = None, + conversion_source: Optional[conversionsources.ConversionSource] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> conversionsources.ConversionSource: + r"""Creates a new conversion source. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_conversions_v1beta + + async def sample_create_conversion_source(): + # Create a client + client = merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient() + + # Initialize request argument(s) + conversion_source = merchant_conversions_v1beta.ConversionSource() + conversion_source.google_analytics_link.property_id = 1201 + + request = merchant_conversions_v1beta.CreateConversionSourceRequest( + parent="parent_value", + conversion_source=conversion_source, + ) + + # Make the request + response = await client.create_conversion_source(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_conversions_v1beta.types.CreateConversionSourceRequest, dict]]): + The request object. Request message for the + CreateConversionSource method. + parent (:class:`str`): + Required. The merchant account that + will own the new conversion source. + Format: accounts/{account} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + conversion_source (:class:`google.shopping.merchant_conversions_v1beta.types.ConversionSource`): + Required. The conversion source + description. A new ID will be + automatically assigned to it upon + creation. + + This corresponds to the ``conversion_source`` 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_conversions_v1beta.types.ConversionSource: + Represents a conversion source owned + by a Merchant account. A merchant + account can have up to 200 conversion + sources. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, conversion_source]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, conversionsources.CreateConversionSourceRequest): + request = conversionsources.CreateConversionSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if conversion_source is not None: + request.conversion_source = conversion_source + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_conversion_source] + + # Certain 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_conversion_source(self, + request: Optional[Union[conversionsources.UpdateConversionSourceRequest, dict]] = None, + *, + conversion_source: Optional[conversionsources.ConversionSource] = 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]]] = (), + ) -> conversionsources.ConversionSource: + r"""Updates information of an existing conversion source. + Available only for Merchant Center Destination + conversion sources. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_conversions_v1beta + + async def sample_update_conversion_source(): + # Create a client + client = merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient() + + # Initialize request argument(s) + conversion_source = merchant_conversions_v1beta.ConversionSource() + conversion_source.google_analytics_link.property_id = 1201 + + request = merchant_conversions_v1beta.UpdateConversionSourceRequest( + conversion_source=conversion_source, + ) + + # Make the request + response = await client.update_conversion_source(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_conversions_v1beta.types.UpdateConversionSourceRequest, dict]]): + The request object. Request message for the + UpdateConversionSource method. + conversion_source (:class:`google.shopping.merchant_conversions_v1beta.types.ConversionSource`): + Required. The new version of the conversion source data. + Format: + accounts/{account}/conversionSources/{conversion_source} + + This corresponds to the ``conversion_source`` 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_conversions_v1beta.types.ConversionSource: + Represents a conversion source owned + by a Merchant account. A merchant + account can have up to 200 conversion + sources. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([conversion_source, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, conversionsources.UpdateConversionSourceRequest): + request = conversionsources.UpdateConversionSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if conversion_source is not None: + request.conversion_source = conversion_source + 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_conversion_source] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("conversion_source.name", request.conversion_source.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_conversion_source(self, + request: Optional[Union[conversionsources.DeleteConversionSourceRequest, dict]] = None, + *, + name: Optional[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"""Archives an existing conversion source. If the + conversion source is a Merchant Center Destination, it + will be recoverable for 30 days. If the conversion + source is a Google Analytics Link, it will be deleted + immediately and can be restored by creating a new one. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_conversions_v1beta + + async def sample_delete_conversion_source(): + # Create a client + client = merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_conversions_v1beta.DeleteConversionSourceRequest( + name="name_value", + ) + + # Make the request + await client.delete_conversion_source(request=request) + + Args: + request (Optional[Union[google.shopping.merchant_conversions_v1beta.types.DeleteConversionSourceRequest, dict]]): + The request object. Request message for the + DeleteConversionSource method. + name (:class:`str`): + Required. The name of the conversion source to be + deleted. Format: + accounts/{account}/conversionSources/{conversion_source} + + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, conversionsources.DeleteConversionSourceRequest): + request = conversionsources.DeleteConversionSourceRequest(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_conversion_source] + + # Certain 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 undelete_conversion_source(self, + request: Optional[Union[conversionsources.UndeleteConversionSourceRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> conversionsources.ConversionSource: + r"""Re-enables an archived conversion source. Only + Available for Merchant Center Destination conversion + sources. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_conversions_v1beta + + async def sample_undelete_conversion_source(): + # Create a client + client = merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_conversions_v1beta.UndeleteConversionSourceRequest( + name="name_value", + ) + + # Make the request + response = await client.undelete_conversion_source(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_conversions_v1beta.types.UndeleteConversionSourceRequest, dict]]): + The request object. Request message for the + UndeleteConversionSource 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_conversions_v1beta.types.ConversionSource: + Represents a conversion source owned + by a Merchant account. A merchant + account can have up to 200 conversion + sources. + + """ + # 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, conversionsources.UndeleteConversionSourceRequest): + request = conversionsources.UndeleteConversionSourceRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.undelete_conversion_source] + + # Certain 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_conversion_source(self, + request: Optional[Union[conversionsources.GetConversionSourceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> conversionsources.ConversionSource: + r"""Fetches a conversion source. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_conversions_v1beta + + async def sample_get_conversion_source(): + # Create a client + client = merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_conversions_v1beta.GetConversionSourceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_conversion_source(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_conversions_v1beta.types.GetConversionSourceRequest, dict]]): + The request object. Request message for the + GetConversionSource method. + name (:class:`str`): + Required. The name of the conversion source to be + fetched. Format: + accounts/{account}/conversionsources/{conversion_source} + + 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_conversions_v1beta.types.ConversionSource: + Represents a conversion source owned + by a Merchant account. A merchant + account can have up to 200 conversion + sources. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, conversionsources.GetConversionSourceRequest): + request = conversionsources.GetConversionSourceRequest(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_conversion_source] + + # Certain 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_conversion_sources(self, + request: Optional[Union[conversionsources.ListConversionSourcesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListConversionSourcesAsyncPager: + r"""Retrieves the list of conversion sources the caller + has access 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_conversions_v1beta + + async def sample_list_conversion_sources(): + # Create a client + client = merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_conversions_v1beta.ListConversionSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_conversion_sources(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_conversions_v1beta.types.ListConversionSourcesRequest, dict]]): + The request object. Request message for the + ListConversionSources method. + parent (:class:`str`): + Required. The merchant account who + owns the collection of conversion + sources. 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_conversions_v1beta.services.conversion_sources_service.pagers.ListConversionSourcesAsyncPager: + Response message for the + ListConversionSources 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, conversionsources.ListConversionSourcesRequest): + request = conversionsources.ListConversionSourcesRequest(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_conversion_sources] + + # Certain 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.ListConversionSourcesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "ConversionSourcesServiceAsyncClient": + 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__) + + +__all__ = ( + "ConversionSourcesServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/client.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/client.py new file mode 100644 index 000000000000..c3e986575c99 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/client.py @@ -0,0 +1,1259 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +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_conversions_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 + +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 timestamp_pb2 # type: ignore +from google.shopping.merchant_conversions_v1beta.services.conversion_sources_service import pagers +from google.shopping.merchant_conversions_v1beta.types import conversionsources +from .transports.base import ConversionSourcesServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ConversionSourcesServiceGrpcTransport +from .transports.grpc_asyncio import ConversionSourcesServiceGrpcAsyncIOTransport +from .transports.rest import ConversionSourcesServiceRestTransport + + +class ConversionSourcesServiceClientMeta(type): + """Metaclass for the ConversionSourcesService 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[ConversionSourcesServiceTransport]] + _transport_registry["grpc"] = ConversionSourcesServiceGrpcTransport + _transport_registry["grpc_asyncio"] = ConversionSourcesServiceGrpcAsyncIOTransport + _transport_registry["rest"] = ConversionSourcesServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[ConversionSourcesServiceTransport]: + """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 ConversionSourcesServiceClient(metaclass=ConversionSourcesServiceClientMeta): + """Service for managing conversion sources for a merchant + account. + """ + + @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: + ConversionSourcesServiceClient: 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: + ConversionSourcesServiceClient: 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) -> ConversionSourcesServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ConversionSourcesServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def conversion_source_path(account: str,conversion_source: str,) -> str: + """Returns a fully-qualified conversion_source string.""" + return "accounts/{account}/conversionSources/{conversion_source}".format(account=account, conversion_source=conversion_source, ) + + @staticmethod + def parse_conversion_source_path(path: str) -> Dict[str,str]: + """Parses a conversion_source path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/conversionSources/(?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 = ConversionSourcesServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = ConversionSourcesServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ConversionSourcesServiceClient._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 = ConversionSourcesServiceClient._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 + + @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, ConversionSourcesServiceTransport, Callable[..., ConversionSourcesServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the conversion sources 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,ConversionSourcesServiceTransport,Callable[..., ConversionSourcesServiceTransport]]]): + 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 ConversionSourcesServiceTransport 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 = ConversionSourcesServiceClient._read_environment_variables() + self._client_cert_source = ConversionSourcesServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = ConversionSourcesServiceClient._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, ConversionSourcesServiceTransport) + if transport_provided: + # transport is a ConversionSourcesServiceTransport 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(ConversionSourcesServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + ConversionSourcesServiceClient._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[ConversionSourcesServiceTransport], Callable[..., ConversionSourcesServiceTransport]] = ( + ConversionSourcesServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., ConversionSourcesServiceTransport], 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.conversions_v1beta.ConversionSourcesServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", + "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.conversions.v1beta.ConversionSourcesService", + "credentialsType": None, + } + ) + + def create_conversion_source(self, + request: Optional[Union[conversionsources.CreateConversionSourceRequest, dict]] = None, + *, + parent: Optional[str] = None, + conversion_source: Optional[conversionsources.ConversionSource] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> conversionsources.ConversionSource: + r"""Creates a new conversion source. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_conversions_v1beta + + def sample_create_conversion_source(): + # Create a client + client = merchant_conversions_v1beta.ConversionSourcesServiceClient() + + # Initialize request argument(s) + conversion_source = merchant_conversions_v1beta.ConversionSource() + conversion_source.google_analytics_link.property_id = 1201 + + request = merchant_conversions_v1beta.CreateConversionSourceRequest( + parent="parent_value", + conversion_source=conversion_source, + ) + + # Make the request + response = client.create_conversion_source(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_conversions_v1beta.types.CreateConversionSourceRequest, dict]): + The request object. Request message for the + CreateConversionSource method. + parent (str): + Required. The merchant account that + will own the new conversion source. + Format: accounts/{account} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + conversion_source (google.shopping.merchant_conversions_v1beta.types.ConversionSource): + Required. The conversion source + description. A new ID will be + automatically assigned to it upon + creation. + + This corresponds to the ``conversion_source`` 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_conversions_v1beta.types.ConversionSource: + Represents a conversion source owned + by a Merchant account. A merchant + account can have up to 200 conversion + sources. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, conversion_source]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, conversionsources.CreateConversionSourceRequest): + request = conversionsources.CreateConversionSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if conversion_source is not None: + request.conversion_source = conversion_source + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_conversion_source] + + # Certain 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_conversion_source(self, + request: Optional[Union[conversionsources.UpdateConversionSourceRequest, dict]] = None, + *, + conversion_source: Optional[conversionsources.ConversionSource] = 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]]] = (), + ) -> conversionsources.ConversionSource: + r"""Updates information of an existing conversion source. + Available only for Merchant Center Destination + conversion sources. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_conversions_v1beta + + def sample_update_conversion_source(): + # Create a client + client = merchant_conversions_v1beta.ConversionSourcesServiceClient() + + # Initialize request argument(s) + conversion_source = merchant_conversions_v1beta.ConversionSource() + conversion_source.google_analytics_link.property_id = 1201 + + request = merchant_conversions_v1beta.UpdateConversionSourceRequest( + conversion_source=conversion_source, + ) + + # Make the request + response = client.update_conversion_source(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_conversions_v1beta.types.UpdateConversionSourceRequest, dict]): + The request object. Request message for the + UpdateConversionSource method. + conversion_source (google.shopping.merchant_conversions_v1beta.types.ConversionSource): + Required. The new version of the conversion source data. + Format: + accounts/{account}/conversionSources/{conversion_source} + + This corresponds to the ``conversion_source`` 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_conversions_v1beta.types.ConversionSource: + Represents a conversion source owned + by a Merchant account. A merchant + account can have up to 200 conversion + sources. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([conversion_source, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, conversionsources.UpdateConversionSourceRequest): + request = conversionsources.UpdateConversionSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if conversion_source is not None: + request.conversion_source = conversion_source + 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_conversion_source] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("conversion_source.name", request.conversion_source.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_conversion_source(self, + request: Optional[Union[conversionsources.DeleteConversionSourceRequest, dict]] = None, + *, + name: Optional[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"""Archives an existing conversion source. If the + conversion source is a Merchant Center Destination, it + will be recoverable for 30 days. If the conversion + source is a Google Analytics Link, it will be deleted + immediately and can be restored by creating a new one. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_conversions_v1beta + + def sample_delete_conversion_source(): + # Create a client + client = merchant_conversions_v1beta.ConversionSourcesServiceClient() + + # Initialize request argument(s) + request = merchant_conversions_v1beta.DeleteConversionSourceRequest( + name="name_value", + ) + + # Make the request + client.delete_conversion_source(request=request) + + Args: + request (Union[google.shopping.merchant_conversions_v1beta.types.DeleteConversionSourceRequest, dict]): + The request object. Request message for the + DeleteConversionSource method. + name (str): + Required. The name of the conversion source to be + deleted. Format: + accounts/{account}/conversionSources/{conversion_source} + + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, conversionsources.DeleteConversionSourceRequest): + request = conversionsources.DeleteConversionSourceRequest(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_conversion_source] + + # Certain 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 undelete_conversion_source(self, + request: Optional[Union[conversionsources.UndeleteConversionSourceRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> conversionsources.ConversionSource: + r"""Re-enables an archived conversion source. Only + Available for Merchant Center Destination conversion + sources. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_conversions_v1beta + + def sample_undelete_conversion_source(): + # Create a client + client = merchant_conversions_v1beta.ConversionSourcesServiceClient() + + # Initialize request argument(s) + request = merchant_conversions_v1beta.UndeleteConversionSourceRequest( + name="name_value", + ) + + # Make the request + response = client.undelete_conversion_source(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_conversions_v1beta.types.UndeleteConversionSourceRequest, dict]): + The request object. Request message for the + UndeleteConversionSource method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.shopping.merchant_conversions_v1beta.types.ConversionSource: + Represents a conversion source owned + by a Merchant account. A merchant + account can have up to 200 conversion + sources. + + """ + # 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, conversionsources.UndeleteConversionSourceRequest): + request = conversionsources.UndeleteConversionSourceRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.undelete_conversion_source] + + # Certain 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_conversion_source(self, + request: Optional[Union[conversionsources.GetConversionSourceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> conversionsources.ConversionSource: + r"""Fetches a conversion source. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_conversions_v1beta + + def sample_get_conversion_source(): + # Create a client + client = merchant_conversions_v1beta.ConversionSourcesServiceClient() + + # Initialize request argument(s) + request = merchant_conversions_v1beta.GetConversionSourceRequest( + name="name_value", + ) + + # Make the request + response = client.get_conversion_source(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_conversions_v1beta.types.GetConversionSourceRequest, dict]): + The request object. Request message for the + GetConversionSource method. + name (str): + Required. The name of the conversion source to be + fetched. Format: + accounts/{account}/conversionsources/{conversion_source} + + 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_conversions_v1beta.types.ConversionSource: + Represents a conversion source owned + by a Merchant account. A merchant + account can have up to 200 conversion + sources. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, conversionsources.GetConversionSourceRequest): + request = conversionsources.GetConversionSourceRequest(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_conversion_source] + + # Certain 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_conversion_sources(self, + request: Optional[Union[conversionsources.ListConversionSourcesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListConversionSourcesPager: + r"""Retrieves the list of conversion sources the caller + has access 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_conversions_v1beta + + def sample_list_conversion_sources(): + # Create a client + client = merchant_conversions_v1beta.ConversionSourcesServiceClient() + + # Initialize request argument(s) + request = merchant_conversions_v1beta.ListConversionSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_conversion_sources(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.shopping.merchant_conversions_v1beta.types.ListConversionSourcesRequest, dict]): + The request object. Request message for the + ListConversionSources method. + parent (str): + Required. The merchant account who + owns the collection of conversion + sources. 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_conversions_v1beta.services.conversion_sources_service.pagers.ListConversionSourcesPager: + Response message for the + ListConversionSources 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, conversionsources.ListConversionSourcesRequest): + request = conversionsources.ListConversionSourcesRequest(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_conversion_sources] + + # Certain 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.ListConversionSourcesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "ConversionSourcesServiceClient": + 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__) + + +__all__ = ( + "ConversionSourcesServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/pagers.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/pagers.py new file mode 100644 index 000000000000..13496d2bfaca --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/pagers.py @@ -0,0 +1,166 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_conversions_v1beta.types import conversionsources + + +class ListConversionSourcesPager: + """A pager for iterating through ``list_conversion_sources`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_conversions_v1beta.types.ListConversionSourcesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``conversion_sources`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListConversionSources`` requests and continue to iterate + through the ``conversion_sources`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_conversions_v1beta.types.ListConversionSourcesResponse` + 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[..., conversionsources.ListConversionSourcesResponse], + request: conversionsources.ListConversionSourcesRequest, + response: conversionsources.ListConversionSourcesResponse, + *, + 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_conversions_v1beta.types.ListConversionSourcesRequest): + The initial request object. + response (google.shopping.merchant_conversions_v1beta.types.ListConversionSourcesResponse): + 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 = conversionsources.ListConversionSourcesRequest(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[conversionsources.ListConversionSourcesResponse]: + 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[conversionsources.ConversionSource]: + for page in self.pages: + yield from page.conversion_sources + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListConversionSourcesAsyncPager: + """A pager for iterating through ``list_conversion_sources`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_conversions_v1beta.types.ListConversionSourcesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``conversion_sources`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListConversionSources`` requests and continue to iterate + through the ``conversion_sources`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_conversions_v1beta.types.ListConversionSourcesResponse` + 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[conversionsources.ListConversionSourcesResponse]], + request: conversionsources.ListConversionSourcesRequest, + response: conversionsources.ListConversionSourcesResponse, + *, + 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_conversions_v1beta.types.ListConversionSourcesRequest): + The initial request object. + response (google.shopping.merchant_conversions_v1beta.types.ListConversionSourcesResponse): + 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 = conversionsources.ListConversionSourcesRequest(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[conversionsources.ListConversionSourcesResponse]: + 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[conversionsources.ConversionSource]: + async def async_generator(): + async for page in self.pages: + for response in page.conversion_sources: + 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-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/README.rst new file mode 100644 index 000000000000..3ffc61f2806b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`ConversionSourcesServiceTransport` is the ABC for all transports. +- public child `ConversionSourcesServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `ConversionSourcesServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseConversionSourcesServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `ConversionSourcesServiceRestTransport` 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-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/__init__.py new file mode 100644 index 000000000000..fafe5db74b55 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 ConversionSourcesServiceTransport +from .grpc import ConversionSourcesServiceGrpcTransport +from .grpc_asyncio import ConversionSourcesServiceGrpcAsyncIOTransport +from .rest import ConversionSourcesServiceRestTransport +from .rest import ConversionSourcesServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ConversionSourcesServiceTransport]] +_transport_registry['grpc'] = ConversionSourcesServiceGrpcTransport +_transport_registry['grpc_asyncio'] = ConversionSourcesServiceGrpcAsyncIOTransport +_transport_registry['rest'] = ConversionSourcesServiceRestTransport + +__all__ = ( + 'ConversionSourcesServiceTransport', + 'ConversionSourcesServiceGrpcTransport', + 'ConversionSourcesServiceGrpcAsyncIOTransport', + 'ConversionSourcesServiceRestTransport', + 'ConversionSourcesServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/base.py new file mode 100644 index 000000000000..aab7dedcf3a7 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/base.py @@ -0,0 +1,225 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_conversions_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 + +from google.protobuf import empty_pb2 # type: ignore +from google.shopping.merchant_conversions_v1beta.types import conversionsources + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class ConversionSourcesServiceTransport(abc.ABC): + """Abstract transport class for ConversionSourcesService.""" + + 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.create_conversion_source: gapic_v1.method.wrap_method( + self.create_conversion_source, + default_timeout=None, + client_info=client_info, + ), + self.update_conversion_source: gapic_v1.method.wrap_method( + self.update_conversion_source, + default_timeout=None, + client_info=client_info, + ), + self.delete_conversion_source: gapic_v1.method.wrap_method( + self.delete_conversion_source, + default_timeout=None, + client_info=client_info, + ), + self.undelete_conversion_source: gapic_v1.method.wrap_method( + self.undelete_conversion_source, + default_timeout=None, + client_info=client_info, + ), + self.get_conversion_source: gapic_v1.method.wrap_method( + self.get_conversion_source, + default_timeout=None, + client_info=client_info, + ), + self.list_conversion_sources: gapic_v1.method.wrap_method( + self.list_conversion_sources, + 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 create_conversion_source(self) -> Callable[ + [conversionsources.CreateConversionSourceRequest], + Union[ + conversionsources.ConversionSource, + Awaitable[conversionsources.ConversionSource] + ]]: + raise NotImplementedError() + + @property + def update_conversion_source(self) -> Callable[ + [conversionsources.UpdateConversionSourceRequest], + Union[ + conversionsources.ConversionSource, + Awaitable[conversionsources.ConversionSource] + ]]: + raise NotImplementedError() + + @property + def delete_conversion_source(self) -> Callable[ + [conversionsources.DeleteConversionSourceRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def undelete_conversion_source(self) -> Callable[ + [conversionsources.UndeleteConversionSourceRequest], + Union[ + conversionsources.ConversionSource, + Awaitable[conversionsources.ConversionSource] + ]]: + raise NotImplementedError() + + @property + def get_conversion_source(self) -> Callable[ + [conversionsources.GetConversionSourceRequest], + Union[ + conversionsources.ConversionSource, + Awaitable[conversionsources.ConversionSource] + ]]: + raise NotImplementedError() + + @property + def list_conversion_sources(self) -> Callable[ + [conversionsources.ListConversionSourcesRequest], + Union[ + conversionsources.ListConversionSourcesResponse, + Awaitable[conversionsources.ListConversionSourcesResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'ConversionSourcesServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/grpc.py new file mode 100644 index 000000000000..257d0661419f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/grpc.py @@ -0,0 +1,488 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_conversions_v1beta.types import conversionsources +from .base import ConversionSourcesServiceTransport, 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.conversions.v1beta.ConversionSourcesService", + "rpcName": 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.conversions.v1beta.ConversionSourcesService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class ConversionSourcesServiceGrpcTransport(ConversionSourcesServiceTransport): + """gRPC backend transport for ConversionSourcesService. + + Service for managing conversion sources for a merchant + account. + + This 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 create_conversion_source(self) -> Callable[ + [conversionsources.CreateConversionSourceRequest], + conversionsources.ConversionSource]: + r"""Return a callable for the create conversion source method over gRPC. + + Creates a new conversion source. + + Returns: + Callable[[~.CreateConversionSourceRequest], + ~.ConversionSource]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversion_source' not in self._stubs: + self._stubs['create_conversion_source'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.conversions.v1beta.ConversionSourcesService/CreateConversionSource', + request_serializer=conversionsources.CreateConversionSourceRequest.serialize, + response_deserializer=conversionsources.ConversionSource.deserialize, + ) + return self._stubs['create_conversion_source'] + + @property + def update_conversion_source(self) -> Callable[ + [conversionsources.UpdateConversionSourceRequest], + conversionsources.ConversionSource]: + r"""Return a callable for the update conversion source method over gRPC. + + Updates information of an existing conversion source. + Available only for Merchant Center Destination + conversion sources. + + Returns: + Callable[[~.UpdateConversionSourceRequest], + ~.ConversionSource]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversion_source' not in self._stubs: + self._stubs['update_conversion_source'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.conversions.v1beta.ConversionSourcesService/UpdateConversionSource', + request_serializer=conversionsources.UpdateConversionSourceRequest.serialize, + response_deserializer=conversionsources.ConversionSource.deserialize, + ) + return self._stubs['update_conversion_source'] + + @property + def delete_conversion_source(self) -> Callable[ + [conversionsources.DeleteConversionSourceRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete conversion source method over gRPC. + + Archives an existing conversion source. If the + conversion source is a Merchant Center Destination, it + will be recoverable for 30 days. If the conversion + source is a Google Analytics Link, it will be deleted + immediately and can be restored by creating a new one. + + Returns: + Callable[[~.DeleteConversionSourceRequest], + ~.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_conversion_source' not in self._stubs: + self._stubs['delete_conversion_source'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.conversions.v1beta.ConversionSourcesService/DeleteConversionSource', + request_serializer=conversionsources.DeleteConversionSourceRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_conversion_source'] + + @property + def undelete_conversion_source(self) -> Callable[ + [conversionsources.UndeleteConversionSourceRequest], + conversionsources.ConversionSource]: + r"""Return a callable for the undelete conversion source method over gRPC. + + Re-enables an archived conversion source. Only + Available for Merchant Center Destination conversion + sources. + + Returns: + Callable[[~.UndeleteConversionSourceRequest], + ~.ConversionSource]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'undelete_conversion_source' not in self._stubs: + self._stubs['undelete_conversion_source'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.conversions.v1beta.ConversionSourcesService/UndeleteConversionSource', + request_serializer=conversionsources.UndeleteConversionSourceRequest.serialize, + response_deserializer=conversionsources.ConversionSource.deserialize, + ) + return self._stubs['undelete_conversion_source'] + + @property + def get_conversion_source(self) -> Callable[ + [conversionsources.GetConversionSourceRequest], + conversionsources.ConversionSource]: + r"""Return a callable for the get conversion source method over gRPC. + + Fetches a conversion source. + + Returns: + Callable[[~.GetConversionSourceRequest], + ~.ConversionSource]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversion_source' not in self._stubs: + self._stubs['get_conversion_source'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.conversions.v1beta.ConversionSourcesService/GetConversionSource', + request_serializer=conversionsources.GetConversionSourceRequest.serialize, + response_deserializer=conversionsources.ConversionSource.deserialize, + ) + return self._stubs['get_conversion_source'] + + @property + def list_conversion_sources(self) -> Callable[ + [conversionsources.ListConversionSourcesRequest], + conversionsources.ListConversionSourcesResponse]: + r"""Return a callable for the list conversion sources method over gRPC. + + Retrieves the list of conversion sources the caller + has access to. + + Returns: + Callable[[~.ListConversionSourcesRequest], + ~.ListConversionSourcesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversion_sources' not in self._stubs: + self._stubs['list_conversion_sources'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.conversions.v1beta.ConversionSourcesService/ListConversionSources', + request_serializer=conversionsources.ListConversionSourcesRequest.serialize, + response_deserializer=conversionsources.ListConversionSourcesResponse.deserialize, + ) + return self._stubs['list_conversion_sources'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'ConversionSourcesServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..64d901f88111 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/grpc_asyncio.py @@ -0,0 +1,533 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_conversions_v1beta.types import conversionsources +from .base import ConversionSourcesServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import ConversionSourcesServiceGrpcTransport + +try: + from google.api_core import client_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.conversions.v1beta.ConversionSourcesService", + "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.conversions.v1beta.ConversionSourcesService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class ConversionSourcesServiceGrpcAsyncIOTransport(ConversionSourcesServiceTransport): + """gRPC AsyncIO backend transport for ConversionSourcesService. + + Service for managing conversion sources for a merchant + account. + + This 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 create_conversion_source(self) -> Callable[ + [conversionsources.CreateConversionSourceRequest], + Awaitable[conversionsources.ConversionSource]]: + r"""Return a callable for the create conversion source method over gRPC. + + Creates a new conversion source. + + Returns: + Callable[[~.CreateConversionSourceRequest], + Awaitable[~.ConversionSource]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversion_source' not in self._stubs: + self._stubs['create_conversion_source'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.conversions.v1beta.ConversionSourcesService/CreateConversionSource', + request_serializer=conversionsources.CreateConversionSourceRequest.serialize, + response_deserializer=conversionsources.ConversionSource.deserialize, + ) + return self._stubs['create_conversion_source'] + + @property + def update_conversion_source(self) -> Callable[ + [conversionsources.UpdateConversionSourceRequest], + Awaitable[conversionsources.ConversionSource]]: + r"""Return a callable for the update conversion source method over gRPC. + + Updates information of an existing conversion source. + Available only for Merchant Center Destination + conversion sources. + + Returns: + Callable[[~.UpdateConversionSourceRequest], + Awaitable[~.ConversionSource]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversion_source' not in self._stubs: + self._stubs['update_conversion_source'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.conversions.v1beta.ConversionSourcesService/UpdateConversionSource', + request_serializer=conversionsources.UpdateConversionSourceRequest.serialize, + response_deserializer=conversionsources.ConversionSource.deserialize, + ) + return self._stubs['update_conversion_source'] + + @property + def delete_conversion_source(self) -> Callable[ + [conversionsources.DeleteConversionSourceRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete conversion source method over gRPC. + + Archives an existing conversion source. If the + conversion source is a Merchant Center Destination, it + will be recoverable for 30 days. If the conversion + source is a Google Analytics Link, it will be deleted + immediately and can be restored by creating a new one. + + Returns: + Callable[[~.DeleteConversionSourceRequest], + 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_conversion_source' not in self._stubs: + self._stubs['delete_conversion_source'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.conversions.v1beta.ConversionSourcesService/DeleteConversionSource', + request_serializer=conversionsources.DeleteConversionSourceRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_conversion_source'] + + @property + def undelete_conversion_source(self) -> Callable[ + [conversionsources.UndeleteConversionSourceRequest], + Awaitable[conversionsources.ConversionSource]]: + r"""Return a callable for the undelete conversion source method over gRPC. + + Re-enables an archived conversion source. Only + Available for Merchant Center Destination conversion + sources. + + Returns: + Callable[[~.UndeleteConversionSourceRequest], + Awaitable[~.ConversionSource]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'undelete_conversion_source' not in self._stubs: + self._stubs['undelete_conversion_source'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.conversions.v1beta.ConversionSourcesService/UndeleteConversionSource', + request_serializer=conversionsources.UndeleteConversionSourceRequest.serialize, + response_deserializer=conversionsources.ConversionSource.deserialize, + ) + return self._stubs['undelete_conversion_source'] + + @property + def get_conversion_source(self) -> Callable[ + [conversionsources.GetConversionSourceRequest], + Awaitable[conversionsources.ConversionSource]]: + r"""Return a callable for the get conversion source method over gRPC. + + Fetches a conversion source. + + Returns: + Callable[[~.GetConversionSourceRequest], + Awaitable[~.ConversionSource]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversion_source' not in self._stubs: + self._stubs['get_conversion_source'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.conversions.v1beta.ConversionSourcesService/GetConversionSource', + request_serializer=conversionsources.GetConversionSourceRequest.serialize, + response_deserializer=conversionsources.ConversionSource.deserialize, + ) + return self._stubs['get_conversion_source'] + + @property + def list_conversion_sources(self) -> Callable[ + [conversionsources.ListConversionSourcesRequest], + Awaitable[conversionsources.ListConversionSourcesResponse]]: + r"""Return a callable for the list conversion sources method over gRPC. + + Retrieves the list of conversion sources the caller + has access to. + + Returns: + Callable[[~.ListConversionSourcesRequest], + Awaitable[~.ListConversionSourcesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversion_sources' not in self._stubs: + self._stubs['list_conversion_sources'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.conversions.v1beta.ConversionSourcesService/ListConversionSources', + request_serializer=conversionsources.ListConversionSourcesRequest.serialize, + response_deserializer=conversionsources.ListConversionSourcesResponse.deserialize, + ) + return self._stubs['list_conversion_sources'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.create_conversion_source: self._wrap_method( + self.create_conversion_source, + default_timeout=None, + client_info=client_info, + ), + self.update_conversion_source: self._wrap_method( + self.update_conversion_source, + default_timeout=None, + client_info=client_info, + ), + self.delete_conversion_source: self._wrap_method( + self.delete_conversion_source, + default_timeout=None, + client_info=client_info, + ), + self.undelete_conversion_source: self._wrap_method( + self.undelete_conversion_source, + default_timeout=None, + client_info=client_info, + ), + self.get_conversion_source: self._wrap_method( + self.get_conversion_source, + default_timeout=None, + client_info=client_info, + ), + self.list_conversion_sources: self._wrap_method( + self.list_conversion_sources, + 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__ = ( + 'ConversionSourcesServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/rest.py new file mode 100644 index 000000000000..5331d5dab5af --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/rest.py @@ -0,0 +1,1067 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +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_conversions_v1beta.types import conversionsources + + +from .rest_base import _BaseConversionSourcesServiceRestTransport +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}", +) + + +class ConversionSourcesServiceRestInterceptor: + """Interceptor for ConversionSourcesService. + + 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 ConversionSourcesServiceRestTransport. + + .. code-block:: python + class MyCustomConversionSourcesServiceInterceptor(ConversionSourcesServiceRestInterceptor): + def pre_create_conversion_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_conversion_source(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_conversion_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_conversion_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_conversion_source(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_conversion_sources(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_conversion_sources(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_undelete_conversion_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_undelete_conversion_source(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_conversion_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_conversion_source(self, response): + logging.log(f"Received response: {response}") + return response + + transport = ConversionSourcesServiceRestTransport(interceptor=MyCustomConversionSourcesServiceInterceptor()) + client = ConversionSourcesServiceClient(transport=transport) + + + """ + def pre_create_conversion_source(self, request: conversionsources.CreateConversionSourceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[conversionsources.CreateConversionSourceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_conversion_source + + Override in a subclass to manipulate the request or metadata + before they are sent to the ConversionSourcesService server. + """ + return request, metadata + + def post_create_conversion_source(self, response: conversionsources.ConversionSource) -> conversionsources.ConversionSource: + """Post-rpc interceptor for create_conversion_source + + Override in a subclass to manipulate the response + after it is returned by the ConversionSourcesService server but before + it is returned to user code. + """ + return response + + def pre_delete_conversion_source(self, request: conversionsources.DeleteConversionSourceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[conversionsources.DeleteConversionSourceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_conversion_source + + Override in a subclass to manipulate the request or metadata + before they are sent to the ConversionSourcesService server. + """ + return request, metadata + + def pre_get_conversion_source(self, request: conversionsources.GetConversionSourceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[conversionsources.GetConversionSourceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_conversion_source + + Override in a subclass to manipulate the request or metadata + before they are sent to the ConversionSourcesService server. + """ + return request, metadata + + def post_get_conversion_source(self, response: conversionsources.ConversionSource) -> conversionsources.ConversionSource: + """Post-rpc interceptor for get_conversion_source + + Override in a subclass to manipulate the response + after it is returned by the ConversionSourcesService server but before + it is returned to user code. + """ + return response + + def pre_list_conversion_sources(self, request: conversionsources.ListConversionSourcesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[conversionsources.ListConversionSourcesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_conversion_sources + + Override in a subclass to manipulate the request or metadata + before they are sent to the ConversionSourcesService server. + """ + return request, metadata + + def post_list_conversion_sources(self, response: conversionsources.ListConversionSourcesResponse) -> conversionsources.ListConversionSourcesResponse: + """Post-rpc interceptor for list_conversion_sources + + Override in a subclass to manipulate the response + after it is returned by the ConversionSourcesService server but before + it is returned to user code. + """ + return response + + def pre_undelete_conversion_source(self, request: conversionsources.UndeleteConversionSourceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[conversionsources.UndeleteConversionSourceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for undelete_conversion_source + + Override in a subclass to manipulate the request or metadata + before they are sent to the ConversionSourcesService server. + """ + return request, metadata + + def post_undelete_conversion_source(self, response: conversionsources.ConversionSource) -> conversionsources.ConversionSource: + """Post-rpc interceptor for undelete_conversion_source + + Override in a subclass to manipulate the response + after it is returned by the ConversionSourcesService server but before + it is returned to user code. + """ + return response + + def pre_update_conversion_source(self, request: conversionsources.UpdateConversionSourceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[conversionsources.UpdateConversionSourceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_conversion_source + + Override in a subclass to manipulate the request or metadata + before they are sent to the ConversionSourcesService server. + """ + return request, metadata + + def post_update_conversion_source(self, response: conversionsources.ConversionSource) -> conversionsources.ConversionSource: + """Post-rpc interceptor for update_conversion_source + + Override in a subclass to manipulate the response + after it is returned by the ConversionSourcesService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class ConversionSourcesServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: ConversionSourcesServiceRestInterceptor + + +class ConversionSourcesServiceRestTransport(_BaseConversionSourcesServiceRestTransport): + """REST backend synchronous transport for ConversionSourcesService. + + Service for managing conversion sources for a merchant + account. + + This 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[ConversionSourcesServiceRestInterceptor] = 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 ConversionSourcesServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateConversionSource(_BaseConversionSourcesServiceRestTransport._BaseCreateConversionSource, ConversionSourcesServiceRestStub): + def __hash__(self): + return hash("ConversionSourcesServiceRestTransport.CreateConversionSource") + + @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: conversionsources.CreateConversionSourceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> conversionsources.ConversionSource: + r"""Call the create conversion source method over HTTP. + + Args: + request (~.conversionsources.CreateConversionSourceRequest): + The request object. Request message for the + CreateConversionSource method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.conversionsources.ConversionSource: + Represents a conversion source owned + by a Merchant account. A merchant + account can have up to 200 conversion + sources. + + """ + + http_options = _BaseConversionSourcesServiceRestTransport._BaseCreateConversionSource._get_http_options() + + request, metadata = self._interceptor.pre_create_conversion_source(request, metadata) + transcoded_request = _BaseConversionSourcesServiceRestTransport._BaseCreateConversionSource._get_transcoded_request(http_options, request) + + body = _BaseConversionSourcesServiceRestTransport._BaseCreateConversionSource._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseConversionSourcesServiceRestTransport._BaseCreateConversionSource._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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.conversions_v1beta.ConversionSourcesServiceClient.CreateConversionSource", + extra = { + "serviceName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", + "rpcName": "CreateConversionSource", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ConversionSourcesServiceRestTransport._CreateConversionSource._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 = conversionsources.ConversionSource() + pb_resp = conversionsources.ConversionSource.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_conversion_source(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = conversionsources.ConversionSource.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.conversions_v1beta.ConversionSourcesServiceClient.create_conversion_source", + extra = { + "serviceName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", + "rpcName": "CreateConversionSource", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteConversionSource(_BaseConversionSourcesServiceRestTransport._BaseDeleteConversionSource, ConversionSourcesServiceRestStub): + def __hash__(self): + return hash("ConversionSourcesServiceRestTransport.DeleteConversionSource") + + @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: conversionsources.DeleteConversionSourceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): + r"""Call the delete conversion source method over HTTP. + + Args: + request (~.conversionsources.DeleteConversionSourceRequest): + The request object. Request message for the + DeleteConversionSource method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 = _BaseConversionSourcesServiceRestTransport._BaseDeleteConversionSource._get_http_options() + + request, metadata = self._interceptor.pre_delete_conversion_source(request, metadata) + transcoded_request = _BaseConversionSourcesServiceRestTransport._BaseDeleteConversionSource._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseConversionSourcesServiceRestTransport._BaseDeleteConversionSource._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(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.conversions_v1beta.ConversionSourcesServiceClient.DeleteConversionSource", + extra = { + "serviceName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", + "rpcName": "DeleteConversionSource", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ConversionSourcesServiceRestTransport._DeleteConversionSource._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 _GetConversionSource(_BaseConversionSourcesServiceRestTransport._BaseGetConversionSource, ConversionSourcesServiceRestStub): + def __hash__(self): + return hash("ConversionSourcesServiceRestTransport.GetConversionSource") + + @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: conversionsources.GetConversionSourceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> conversionsources.ConversionSource: + r"""Call the get conversion source method over HTTP. + + Args: + request (~.conversionsources.GetConversionSourceRequest): + The request object. Request message for the + GetConversionSource method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.conversionsources.ConversionSource: + Represents a conversion source owned + by a Merchant account. A merchant + account can have up to 200 conversion + sources. + + """ + + http_options = _BaseConversionSourcesServiceRestTransport._BaseGetConversionSource._get_http_options() + + request, metadata = self._interceptor.pre_get_conversion_source(request, metadata) + transcoded_request = _BaseConversionSourcesServiceRestTransport._BaseGetConversionSource._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseConversionSourcesServiceRestTransport._BaseGetConversionSource._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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.conversions_v1beta.ConversionSourcesServiceClient.GetConversionSource", + extra = { + "serviceName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", + "rpcName": "GetConversionSource", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ConversionSourcesServiceRestTransport._GetConversionSource._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 = conversionsources.ConversionSource() + pb_resp = conversionsources.ConversionSource.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_conversion_source(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = conversionsources.ConversionSource.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.conversions_v1beta.ConversionSourcesServiceClient.get_conversion_source", + extra = { + "serviceName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", + "rpcName": "GetConversionSource", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListConversionSources(_BaseConversionSourcesServiceRestTransport._BaseListConversionSources, ConversionSourcesServiceRestStub): + def __hash__(self): + return hash("ConversionSourcesServiceRestTransport.ListConversionSources") + + @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: conversionsources.ListConversionSourcesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> conversionsources.ListConversionSourcesResponse: + r"""Call the list conversion sources method over HTTP. + + Args: + request (~.conversionsources.ListConversionSourcesRequest): + The request object. Request message for the + ListConversionSources method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.conversionsources.ListConversionSourcesResponse: + Response message for the + ListConversionSources method. + + """ + + http_options = _BaseConversionSourcesServiceRestTransport._BaseListConversionSources._get_http_options() + + request, metadata = self._interceptor.pre_list_conversion_sources(request, metadata) + transcoded_request = _BaseConversionSourcesServiceRestTransport._BaseListConversionSources._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseConversionSourcesServiceRestTransport._BaseListConversionSources._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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.conversions_v1beta.ConversionSourcesServiceClient.ListConversionSources", + extra = { + "serviceName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", + "rpcName": "ListConversionSources", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ConversionSourcesServiceRestTransport._ListConversionSources._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 = conversionsources.ListConversionSourcesResponse() + pb_resp = conversionsources.ListConversionSourcesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_conversion_sources(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = conversionsources.ListConversionSourcesResponse.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.conversions_v1beta.ConversionSourcesServiceClient.list_conversion_sources", + extra = { + "serviceName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", + "rpcName": "ListConversionSources", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UndeleteConversionSource(_BaseConversionSourcesServiceRestTransport._BaseUndeleteConversionSource, ConversionSourcesServiceRestStub): + def __hash__(self): + return hash("ConversionSourcesServiceRestTransport.UndeleteConversionSource") + + @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: conversionsources.UndeleteConversionSourceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> conversionsources.ConversionSource: + r"""Call the undelete conversion + source method over HTTP. + + Args: + request (~.conversionsources.UndeleteConversionSourceRequest): + The request object. Request message for the + UndeleteConversionSource method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.conversionsources.ConversionSource: + Represents a conversion source owned + by a Merchant account. A merchant + account can have up to 200 conversion + sources. + + """ + + http_options = _BaseConversionSourcesServiceRestTransport._BaseUndeleteConversionSource._get_http_options() + + request, metadata = self._interceptor.pre_undelete_conversion_source(request, metadata) + transcoded_request = _BaseConversionSourcesServiceRestTransport._BaseUndeleteConversionSource._get_transcoded_request(http_options, request) + + body = _BaseConversionSourcesServiceRestTransport._BaseUndeleteConversionSource._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseConversionSourcesServiceRestTransport._BaseUndeleteConversionSource._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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.conversions_v1beta.ConversionSourcesServiceClient.UndeleteConversionSource", + extra = { + "serviceName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", + "rpcName": "UndeleteConversionSource", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ConversionSourcesServiceRestTransport._UndeleteConversionSource._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 = conversionsources.ConversionSource() + pb_resp = conversionsources.ConversionSource.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_undelete_conversion_source(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = conversionsources.ConversionSource.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.conversions_v1beta.ConversionSourcesServiceClient.undelete_conversion_source", + extra = { + "serviceName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", + "rpcName": "UndeleteConversionSource", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateConversionSource(_BaseConversionSourcesServiceRestTransport._BaseUpdateConversionSource, ConversionSourcesServiceRestStub): + def __hash__(self): + return hash("ConversionSourcesServiceRestTransport.UpdateConversionSource") + + @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: conversionsources.UpdateConversionSourceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> conversionsources.ConversionSource: + r"""Call the update conversion source method over HTTP. + + Args: + request (~.conversionsources.UpdateConversionSourceRequest): + The request object. Request message for the + UpdateConversionSource method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.conversionsources.ConversionSource: + Represents a conversion source owned + by a Merchant account. A merchant + account can have up to 200 conversion + sources. + + """ + + http_options = _BaseConversionSourcesServiceRestTransport._BaseUpdateConversionSource._get_http_options() + + request, metadata = self._interceptor.pre_update_conversion_source(request, metadata) + transcoded_request = _BaseConversionSourcesServiceRestTransport._BaseUpdateConversionSource._get_transcoded_request(http_options, request) + + body = _BaseConversionSourcesServiceRestTransport._BaseUpdateConversionSource._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseConversionSourcesServiceRestTransport._BaseUpdateConversionSource._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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.conversions_v1beta.ConversionSourcesServiceClient.UpdateConversionSource", + extra = { + "serviceName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", + "rpcName": "UpdateConversionSource", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ConversionSourcesServiceRestTransport._UpdateConversionSource._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 = conversionsources.ConversionSource() + pb_resp = conversionsources.ConversionSource.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_conversion_source(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = conversionsources.ConversionSource.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.conversions_v1beta.ConversionSourcesServiceClient.update_conversion_source", + extra = { + "serviceName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", + "rpcName": "UpdateConversionSource", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_conversion_source(self) -> Callable[ + [conversionsources.CreateConversionSourceRequest], + conversionsources.ConversionSource]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateConversionSource(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_conversion_source(self) -> Callable[ + [conversionsources.DeleteConversionSourceRequest], + 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._DeleteConversionSource(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_conversion_source(self) -> Callable[ + [conversionsources.GetConversionSourceRequest], + conversionsources.ConversionSource]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetConversionSource(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_conversion_sources(self) -> Callable[ + [conversionsources.ListConversionSourcesRequest], + conversionsources.ListConversionSourcesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListConversionSources(self._session, self._host, self._interceptor) # type: ignore + + @property + def undelete_conversion_source(self) -> Callable[ + [conversionsources.UndeleteConversionSourceRequest], + conversionsources.ConversionSource]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UndeleteConversionSource(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_conversion_source(self) -> Callable[ + [conversionsources.UpdateConversionSourceRequest], + conversionsources.ConversionSource]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateConversionSource(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'ConversionSourcesServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/rest_base.py new file mode 100644 index 000000000000..cbb98c1531ce --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/rest_base.py @@ -0,0 +1,344 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 ConversionSourcesServiceTransport, 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_conversions_v1beta.types import conversionsources + + +class _BaseConversionSourcesServiceRestTransport(ConversionSourcesServiceTransport): + """Base REST backend transport for ConversionSourcesService. + + 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 _BaseCreateConversionSource: + 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': '/conversions/v1beta/{parent=accounts/*}/conversionSources', + 'body': 'conversion_source', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = conversionsources.CreateConversionSourceRequest.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(_BaseConversionSourcesServiceRestTransport._BaseCreateConversionSource._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteConversionSource: + 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': '/conversions/v1beta/{name=accounts/*/conversionSources/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = conversionsources.DeleteConversionSourceRequest.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(_BaseConversionSourcesServiceRestTransport._BaseDeleteConversionSource._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetConversionSource: + 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': '/conversions/v1beta/{name=accounts/*/conversionSources/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = conversionsources.GetConversionSourceRequest.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(_BaseConversionSourcesServiceRestTransport._BaseGetConversionSource._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListConversionSources: + 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': '/conversions/v1beta/{parent=accounts/*}/conversionSources', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = conversionsources.ListConversionSourcesRequest.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(_BaseConversionSourcesServiceRestTransport._BaseListConversionSources._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUndeleteConversionSource: + 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': '/conversions/v1beta/{name=accounts/*/conversionSources/*}:undelete', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = conversionsources.UndeleteConversionSourceRequest.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(_BaseConversionSourcesServiceRestTransport._BaseUndeleteConversionSource._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateConversionSource: + 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': '/conversions/v1beta/{conversion_source.name=accounts/*/conversionSources/*}', + 'body': 'conversion_source', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = conversionsources.UpdateConversionSourceRequest.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(_BaseConversionSourcesServiceRestTransport._BaseUpdateConversionSource._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseConversionSourcesServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/types/__init__.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/types/__init__.py new file mode 100644 index 000000000000..c14c1e980fae --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/types/__init__.py @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .conversionsources import ( + AttributionSettings, + ConversionSource, + CreateConversionSourceRequest, + DeleteConversionSourceRequest, + GetConversionSourceRequest, + GoogleAnalyticsLink, + ListConversionSourcesRequest, + ListConversionSourcesResponse, + MerchantCenterDestination, + UndeleteConversionSourceRequest, + UpdateConversionSourceRequest, +) + +__all__ = ( + 'AttributionSettings', + 'ConversionSource', + 'CreateConversionSourceRequest', + 'DeleteConversionSourceRequest', + 'GetConversionSourceRequest', + 'GoogleAnalyticsLink', + 'ListConversionSourcesRequest', + 'ListConversionSourcesResponse', + 'MerchantCenterDestination', + 'UndeleteConversionSourceRequest', + 'UpdateConversionSourceRequest', +) diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/types/conversionsources.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/types/conversionsources.py new file mode 100644 index 000000000000..f735abe384fe --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/types/conversionsources.py @@ -0,0 +1,484 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.shopping.merchant.conversions.v1beta', + manifest={ + 'ConversionSource', + 'AttributionSettings', + 'GoogleAnalyticsLink', + 'MerchantCenterDestination', + 'CreateConversionSourceRequest', + 'UpdateConversionSourceRequest', + 'DeleteConversionSourceRequest', + 'UndeleteConversionSourceRequest', + 'GetConversionSourceRequest', + 'ListConversionSourcesRequest', + 'ListConversionSourcesResponse', + }, +) + + +class ConversionSource(proto.Message): + r"""Represents a conversion source owned by a Merchant account. A + merchant account can have up to 200 conversion sources. + + 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: + google_analytics_link (google.shopping.merchant_conversions_v1beta.types.GoogleAnalyticsLink): + Immutable. Conversion Source of type "Link to + Google Analytics Property". + + This field is a member of `oneof`_ ``source_data``. + merchant_center_destination (google.shopping.merchant_conversions_v1beta.types.MerchantCenterDestination): + Conversion Source of type "Merchant Center + Tag Destination". + + This field is a member of `oneof`_ ``source_data``. + name (str): + Output only. Identifier. Generated by the Content API upon + creation of a new ``ConversionSource``. Format: [a-z]{4}:.+ + The four characters before the colon represent the type of + conversio source. Content after the colon represents the ID + of the conversion source within that type. The ID of two + different conversion sources might be the same across + different types. The following type prefixes are supported: + + - galk: For GoogleAnalyticsLink sources. + - mcdn: For MerchantCenterDestination sources. + state (google.shopping.merchant_conversions_v1beta.types.ConversionSource.State): + Output only. Current state of this conversion + source. Can't be edited through the API. + expire_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when an archived + conversion source becomes permanently deleted + and is no longer available to undelete. + controller (google.shopping.merchant_conversions_v1beta.types.ConversionSource.Controller): + Output only. Controller of the conversion + source. + """ + class State(proto.Enum): + r"""Represents state of the conversion source. + + Values: + STATE_UNSPECIFIED (0): + Conversion source has unspecified state. + ACTIVE (1): + Conversion source is fully functional. + ARCHIVED (2): + Conversion source has been archived in the + last 30 days and not currently functional. Can + be restored using the undelete method. + PENDING (3): + Conversion source creation has started but + not fully finished yet. + """ + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + ARCHIVED = 2 + PENDING = 3 + + class Controller(proto.Enum): + r"""Entity controlling the conversion source. + + Values: + CONTROLLER_UNSPECIFIED (0): + Default value. This value is unused. + MERCHANT (1): + Controlled by the Merchant who owns the + Conversion Source. + YOUTUBE_AFFILIATES (2): + Controlled by the YT Affiliates program. + """ + CONTROLLER_UNSPECIFIED = 0 + MERCHANT = 1 + YOUTUBE_AFFILIATES = 2 + + google_analytics_link: 'GoogleAnalyticsLink' = proto.Field( + proto.MESSAGE, + number=3, + oneof='source_data', + message='GoogleAnalyticsLink', + ) + merchant_center_destination: 'MerchantCenterDestination' = proto.Field( + proto.MESSAGE, + number=4, + oneof='source_data', + message='MerchantCenterDestination', + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + state: State = proto.Field( + proto.ENUM, + number=5, + enum=State, + ) + expire_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + controller: Controller = proto.Field( + proto.ENUM, + number=7, + enum=Controller, + ) + + +class AttributionSettings(proto.Message): + r"""Represents attribution settings for conversion sources + receiving pre-attribution data. + + Attributes: + attribution_lookback_window_days (int): + Required. Lookback windows (in days) used for + attribution in this source. Supported values are + 7, 30, 40. + attribution_model (google.shopping.merchant_conversions_v1beta.types.AttributionSettings.AttributionModel): + Required. Attribution model. + conversion_type (MutableSequence[google.shopping.merchant_conversions_v1beta.types.AttributionSettings.ConversionType]): + Immutable. Unordered list. List of different + conversion types a conversion event can be + classified as. A standard "purchase" type will + be automatically created if this list is empty + at creation time. + """ + class AttributionModel(proto.Enum): + r"""The attribution model used for this source. We support the + same set of models offered by Google Analytics 4, as described + in: + + https://support.google.com/analytics/answer/10596866. + + Values: + ATTRIBUTION_MODEL_UNSPECIFIED (0): + Unspecified model. + CROSS_CHANNEL_LAST_CLICK (1): + Cross-channel Last Click model. + ADS_PREFERRED_LAST_CLICK (2): + Ads-preferred Last Click model. + CROSS_CHANNEL_DATA_DRIVEN (5): + Cross-channel Data Driven model. + CROSS_CHANNEL_FIRST_CLICK (6): + Cross-channel First Click model. + CROSS_CHANNEL_LINEAR (7): + Cross-channel Linear model. + CROSS_CHANNEL_POSITION_BASED (8): + Cross-channel Position Based model. + CROSS_CHANNEL_TIME_DECAY (9): + Cross-channel Time Decay model. + """ + ATTRIBUTION_MODEL_UNSPECIFIED = 0 + CROSS_CHANNEL_LAST_CLICK = 1 + ADS_PREFERRED_LAST_CLICK = 2 + CROSS_CHANNEL_DATA_DRIVEN = 5 + CROSS_CHANNEL_FIRST_CLICK = 6 + CROSS_CHANNEL_LINEAR = 7 + CROSS_CHANNEL_POSITION_BASED = 8 + CROSS_CHANNEL_TIME_DECAY = 9 + + class ConversionType(proto.Message): + r"""Message representing a types of conversion events + + Attributes: + name (str): + Output only. Conversion event name, as it'll + be reported by the client. + report (bool): + Output only. Option indicating if the type + should be included in Merchant Center reporting. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + report: bool = proto.Field( + proto.BOOL, + number=2, + ) + + attribution_lookback_window_days: int = proto.Field( + proto.INT32, + number=1, + ) + attribution_model: AttributionModel = proto.Field( + proto.ENUM, + number=2, + enum=AttributionModel, + ) + conversion_type: MutableSequence[ConversionType] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=ConversionType, + ) + + +class GoogleAnalyticsLink(proto.Message): + r""""Google Analytics Link" sources can be used to get conversion + data from an existing Google Analytics property into the linked + Merchant Center account. + + Attributes: + property_id (int): + Required. Immutable. ID of the Google + Analytics property the merchant is linked to. + attribution_settings (google.shopping.merchant_conversions_v1beta.types.AttributionSettings): + Output only. Attribution settings for the + linked Google Analytics property. + property (str): + Output only. Name of the Google Analytics + property the merchant is linked to. + """ + + property_id: int = proto.Field( + proto.INT64, + number=1, + ) + attribution_settings: 'AttributionSettings' = proto.Field( + proto.MESSAGE, + number=2, + message='AttributionSettings', + ) + property: str = proto.Field( + proto.STRING, + number=3, + ) + + +class MerchantCenterDestination(proto.Message): + r""""Merchant Center Destination" sources can be used to send + conversion events from an online store using a Google tag + directly to a Merchant Center account where the source is + created. + + Attributes: + destination (str): + Output only. Merchant Center Destination ID. + attribution_settings (google.shopping.merchant_conversions_v1beta.types.AttributionSettings): + Required. Attribution settings being used for + the Merchant Center Destination. + display_name (str): + Required. Merchant-specified display name for + the destination. This is the name that + identifies the conversion source within the + Merchant Center UI. Limited to 64 characters. + currency_code (str): + Required. Three-letter currency code (ISO + 4217). The currency code defines in which + currency the conversions sent to this + destination will be reported in Merchant Center. + """ + + destination: str = proto.Field( + proto.STRING, + number=1, + ) + attribution_settings: 'AttributionSettings' = proto.Field( + proto.MESSAGE, + number=2, + message='AttributionSettings', + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + ) + currency_code: str = proto.Field( + proto.STRING, + number=4, + ) + + +class CreateConversionSourceRequest(proto.Message): + r"""Request message for the CreateConversionSource method. + + Attributes: + parent (str): + Required. The merchant account that will own + the new conversion source. Format: + accounts/{account} + conversion_source (google.shopping.merchant_conversions_v1beta.types.ConversionSource): + Required. The conversion source description. + A new ID will be automatically assigned to it + upon creation. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + conversion_source: 'ConversionSource' = proto.Field( + proto.MESSAGE, + number=2, + message='ConversionSource', + ) + + +class UpdateConversionSourceRequest(proto.Message): + r"""Request message for the UpdateConversionSource method. + + Attributes: + conversion_source (google.shopping.merchant_conversions_v1beta.types.ConversionSource): + Required. The new version of the conversion source data. + Format: + accounts/{account}/conversionSources/{conversion_source} + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields being updated. + """ + + conversion_source: 'ConversionSource' = proto.Field( + proto.MESSAGE, + number=1, + message='ConversionSource', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteConversionSourceRequest(proto.Message): + r"""Request message for the DeleteConversionSource method. + + Attributes: + name (str): + Required. The name of the conversion source to be deleted. + Format: + accounts/{account}/conversionSources/{conversion_source} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UndeleteConversionSourceRequest(proto.Message): + r"""Request message for the UndeleteConversionSource method. + + Attributes: + name (str): + Required. The name of the conversion source to be undeleted. + Format: + accounts/{account}/conversionSources/{conversion_source} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetConversionSourceRequest(proto.Message): + r"""Request message for the GetConversionSource method. + + Attributes: + name (str): + Required. The name of the conversion source to be fetched. + Format: + accounts/{account}/conversionsources/{conversion_source} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListConversionSourcesRequest(proto.Message): + r"""Request message for the ListConversionSources method. + + Attributes: + parent (str): + Required. The merchant account who owns the + collection of conversion sources. Format: + accounts/{account} + page_size (int): + Optional. The maximum number of conversion sources to return + in a page. If no ``page_size`` is specified, ``100`` is used + as the default value. The maximum value is ``200``. Values + above ``200`` will be coerced to ``200``. Regardless of + pagination, at most ``200`` conversion sources are returned + in total. + page_token (str): + Optional. Page token. + show_deleted (bool): + Optional. Show deleted (archived) option. + """ + + 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, + ) + show_deleted: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class ListConversionSourcesResponse(proto.Message): + r"""Response message for the ListConversionSources method. + + Attributes: + conversion_sources (MutableSequence[google.shopping.merchant_conversions_v1beta.types.ConversionSource]): + List of conversion sources. + next_page_token (str): + Token to be used to fetch the next results + page. + """ + + @property + def raw_page(self): + return self + + conversion_sources: MutableSequence['ConversionSource'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ConversionSource', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/mypy.ini b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/noxfile.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/noxfile.py new file mode 100644 index 000000000000..db4facae0620 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/noxfile.py @@ -0,0 +1,280 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = 'google-shopping-merchant-conversions' + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.13" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "prerelease_deps", +] + +@nox.session(python=ALL_PYTHON) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def unit(session, protobuf_implementation): + """Run the unit test suite.""" + + 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+") + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") + + # 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") + + session.run( + 'py.test', + '--quiet', + '--cov=google/shopping/merchant_conversions_v1beta/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)), + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + +@nox.session(python=ALL_PYTHON[-1]) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def prerelease_deps(session, protobuf_implementation): + """Run the unit test suite against pre-release versions of dependencies.""" + + 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 test environment dependencies + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + + # Install the package without dependencies + session.install('-e', '.', '--no-deps') + + # We test the minimum dependency versions using the minimum Python + # version so the lowest python runtime that we test has a corresponding constraints + # file, located at `testing/constraints--.txt`, which contains all of the + # 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 + ) + ] + + session.install(*constraints_deps) + + prerel_deps = [ + "googleapis-common-protos", + "google-api-core", + "google-auth", + # Exclude grpcio!=1.67.0rc1 which does not support python 3.13 + "grpcio!=1.67.0rc1", + "grpcio-status", + "protobuf", + "proto-plus", + ] + + for dep in prerel_deps: + session.install("--pre", "--no-deps", "--upgrade", dep) + + # Remaining dependencies + other_deps = [ + "requests", + ] + session.install(*other_deps) + + # Print out prerelease package versions + + session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") + session.run("python", "-c", "import google.auth; print(google.auth.__version__)") + session.run("python", "-c", "import grpc; print(grpc.__version__)") + session.run( + "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" + ) + session.run( + "python", "-c", "import proto; print(proto.__version__)" + ) + + session.run( + 'py.test', + '--quiet', + '--cov=google/shopping/merchant_conversions_v1beta/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)), + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + + +@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=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 docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==7.0.1", "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=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", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_create_conversion_source_async.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_create_conversion_source_async.py new file mode 100644 index 000000000000..a05ae178289a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_create_conversion_source_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateConversionSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-conversions + + +# [START merchantapi_v1beta_generated_ConversionSourcesService_CreateConversionSource_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_conversions_v1beta + + +async def sample_create_conversion_source(): + # Create a client + client = merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient() + + # Initialize request argument(s) + conversion_source = merchant_conversions_v1beta.ConversionSource() + conversion_source.google_analytics_link.property_id = 1201 + + request = merchant_conversions_v1beta.CreateConversionSourceRequest( + parent="parent_value", + conversion_source=conversion_source, + ) + + # Make the request + response = await client.create_conversion_source(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_ConversionSourcesService_CreateConversionSource_async] diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_create_conversion_source_sync.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_create_conversion_source_sync.py new file mode 100644 index 000000000000..dfb2495b2546 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_create_conversion_source_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateConversionSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-conversions + + +# [START merchantapi_v1beta_generated_ConversionSourcesService_CreateConversionSource_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_conversions_v1beta + + +def sample_create_conversion_source(): + # Create a client + client = merchant_conversions_v1beta.ConversionSourcesServiceClient() + + # Initialize request argument(s) + conversion_source = merchant_conversions_v1beta.ConversionSource() + conversion_source.google_analytics_link.property_id = 1201 + + request = merchant_conversions_v1beta.CreateConversionSourceRequest( + parent="parent_value", + conversion_source=conversion_source, + ) + + # Make the request + response = client.create_conversion_source(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_ConversionSourcesService_CreateConversionSource_sync] diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_delete_conversion_source_async.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_delete_conversion_source_async.py new file mode 100644 index 000000000000..784b513a30d4 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_delete_conversion_source_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteConversionSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-conversions + + +# [START merchantapi_v1beta_generated_ConversionSourcesService_DeleteConversionSource_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_conversions_v1beta + + +async def sample_delete_conversion_source(): + # Create a client + client = merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_conversions_v1beta.DeleteConversionSourceRequest( + name="name_value", + ) + + # Make the request + await client.delete_conversion_source(request=request) + + +# [END merchantapi_v1beta_generated_ConversionSourcesService_DeleteConversionSource_async] diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_delete_conversion_source_sync.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_delete_conversion_source_sync.py new file mode 100644 index 000000000000..b6b63cffc119 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_delete_conversion_source_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteConversionSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-conversions + + +# [START merchantapi_v1beta_generated_ConversionSourcesService_DeleteConversionSource_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_conversions_v1beta + + +def sample_delete_conversion_source(): + # Create a client + client = merchant_conversions_v1beta.ConversionSourcesServiceClient() + + # Initialize request argument(s) + request = merchant_conversions_v1beta.DeleteConversionSourceRequest( + name="name_value", + ) + + # Make the request + client.delete_conversion_source(request=request) + + +# [END merchantapi_v1beta_generated_ConversionSourcesService_DeleteConversionSource_sync] diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_get_conversion_source_async.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_get_conversion_source_async.py new file mode 100644 index 000000000000..b17fdeea8f22 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_get_conversion_source_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetConversionSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-conversions + + +# [START merchantapi_v1beta_generated_ConversionSourcesService_GetConversionSource_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_conversions_v1beta + + +async def sample_get_conversion_source(): + # Create a client + client = merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_conversions_v1beta.GetConversionSourceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_conversion_source(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_ConversionSourcesService_GetConversionSource_async] diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_get_conversion_source_sync.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_get_conversion_source_sync.py new file mode 100644 index 000000000000..b0d0a159fb04 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_get_conversion_source_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetConversionSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-conversions + + +# [START merchantapi_v1beta_generated_ConversionSourcesService_GetConversionSource_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_conversions_v1beta + + +def sample_get_conversion_source(): + # Create a client + client = merchant_conversions_v1beta.ConversionSourcesServiceClient() + + # Initialize request argument(s) + request = merchant_conversions_v1beta.GetConversionSourceRequest( + name="name_value", + ) + + # Make the request + response = client.get_conversion_source(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_ConversionSourcesService_GetConversionSource_sync] diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_list_conversion_sources_async.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_list_conversion_sources_async.py new file mode 100644 index 000000000000..9f9a8edd1630 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_list_conversion_sources_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListConversionSources +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-conversions + + +# [START merchantapi_v1beta_generated_ConversionSourcesService_ListConversionSources_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_conversions_v1beta + + +async def sample_list_conversion_sources(): + # Create a client + client = merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_conversions_v1beta.ListConversionSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_conversion_sources(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_ConversionSourcesService_ListConversionSources_async] diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_list_conversion_sources_sync.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_list_conversion_sources_sync.py new file mode 100644 index 000000000000..973a08726b22 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_list_conversion_sources_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListConversionSources +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-conversions + + +# [START merchantapi_v1beta_generated_ConversionSourcesService_ListConversionSources_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_conversions_v1beta + + +def sample_list_conversion_sources(): + # Create a client + client = merchant_conversions_v1beta.ConversionSourcesServiceClient() + + # Initialize request argument(s) + request = merchant_conversions_v1beta.ListConversionSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_conversion_sources(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_ConversionSourcesService_ListConversionSources_sync] diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_undelete_conversion_source_async.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_undelete_conversion_source_async.py new file mode 100644 index 000000000000..d2dad07c2a0a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_undelete_conversion_source_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UndeleteConversionSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-conversions + + +# [START merchantapi_v1beta_generated_ConversionSourcesService_UndeleteConversionSource_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_conversions_v1beta + + +async def sample_undelete_conversion_source(): + # Create a client + client = merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_conversions_v1beta.UndeleteConversionSourceRequest( + name="name_value", + ) + + # Make the request + response = await client.undelete_conversion_source(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_ConversionSourcesService_UndeleteConversionSource_async] diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_undelete_conversion_source_sync.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_undelete_conversion_source_sync.py new file mode 100644 index 000000000000..18218f0303c1 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_undelete_conversion_source_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UndeleteConversionSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-conversions + + +# [START merchantapi_v1beta_generated_ConversionSourcesService_UndeleteConversionSource_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_conversions_v1beta + + +def sample_undelete_conversion_source(): + # Create a client + client = merchant_conversions_v1beta.ConversionSourcesServiceClient() + + # Initialize request argument(s) + request = merchant_conversions_v1beta.UndeleteConversionSourceRequest( + name="name_value", + ) + + # Make the request + response = client.undelete_conversion_source(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_ConversionSourcesService_UndeleteConversionSource_sync] diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_update_conversion_source_async.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_update_conversion_source_async.py new file mode 100644 index 000000000000..b60633a60c41 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_update_conversion_source_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateConversionSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-conversions + + +# [START merchantapi_v1beta_generated_ConversionSourcesService_UpdateConversionSource_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_conversions_v1beta + + +async def sample_update_conversion_source(): + # Create a client + client = merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient() + + # Initialize request argument(s) + conversion_source = merchant_conversions_v1beta.ConversionSource() + conversion_source.google_analytics_link.property_id = 1201 + + request = merchant_conversions_v1beta.UpdateConversionSourceRequest( + conversion_source=conversion_source, + ) + + # Make the request + response = await client.update_conversion_source(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_ConversionSourcesService_UpdateConversionSource_async] diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_update_conversion_source_sync.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_update_conversion_source_sync.py new file mode 100644 index 000000000000..07cfe0bc26dd --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_update_conversion_source_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateConversionSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-conversions + + +# [START merchantapi_v1beta_generated_ConversionSourcesService_UpdateConversionSource_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_conversions_v1beta + + +def sample_update_conversion_source(): + # Create a client + client = merchant_conversions_v1beta.ConversionSourcesServiceClient() + + # Initialize request argument(s) + conversion_source = merchant_conversions_v1beta.ConversionSource() + conversion_source.google_analytics_link.property_id = 1201 + + request = merchant_conversions_v1beta.UpdateConversionSourceRequest( + conversion_source=conversion_source, + ) + + # Make the request + response = client.update_conversion_source(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_ConversionSourcesService_UpdateConversionSource_sync] diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.conversions.v1beta.json b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.conversions.v1beta.json new file mode 100644 index 000000000000..7b979a5c445b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.conversions.v1beta.json @@ -0,0 +1,983 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.shopping.merchant.conversions.v1beta", + "version": "v1beta" + } + ], + "language": "PYTHON", + "name": "google-shopping-merchant-conversions", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient", + "shortName": "ConversionSourcesServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient.create_conversion_source", + "method": { + "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService.CreateConversionSource", + "service": { + "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", + "shortName": "ConversionSourcesService" + }, + "shortName": "CreateConversionSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_conversions_v1beta.types.CreateConversionSourceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "conversion_source", + "type": "google.shopping.merchant_conversions_v1beta.types.ConversionSource" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.shopping.merchant_conversions_v1beta.types.ConversionSource", + "shortName": "create_conversion_source" + }, + "description": "Sample for CreateConversionSource", + "file": "merchantapi_v1beta_generated_conversion_sources_service_create_conversion_source_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_ConversionSourcesService_CreateConversionSource_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_conversion_sources_service_create_conversion_source_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceClient", + "shortName": "ConversionSourcesServiceClient" + }, + "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceClient.create_conversion_source", + "method": { + "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService.CreateConversionSource", + "service": { + "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", + "shortName": "ConversionSourcesService" + }, + "shortName": "CreateConversionSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_conversions_v1beta.types.CreateConversionSourceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "conversion_source", + "type": "google.shopping.merchant_conversions_v1beta.types.ConversionSource" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.shopping.merchant_conversions_v1beta.types.ConversionSource", + "shortName": "create_conversion_source" + }, + "description": "Sample for CreateConversionSource", + "file": "merchantapi_v1beta_generated_conversion_sources_service_create_conversion_source_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_ConversionSourcesService_CreateConversionSource_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_conversion_sources_service_create_conversion_source_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient", + "shortName": "ConversionSourcesServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient.delete_conversion_source", + "method": { + "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService.DeleteConversionSource", + "service": { + "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", + "shortName": "ConversionSourcesService" + }, + "shortName": "DeleteConversionSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_conversions_v1beta.types.DeleteConversionSourceRequest" + }, + { + "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_conversion_source" + }, + "description": "Sample for DeleteConversionSource", + "file": "merchantapi_v1beta_generated_conversion_sources_service_delete_conversion_source_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_ConversionSourcesService_DeleteConversionSource_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_conversion_sources_service_delete_conversion_source_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceClient", + "shortName": "ConversionSourcesServiceClient" + }, + "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceClient.delete_conversion_source", + "method": { + "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService.DeleteConversionSource", + "service": { + "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", + "shortName": "ConversionSourcesService" + }, + "shortName": "DeleteConversionSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_conversions_v1beta.types.DeleteConversionSourceRequest" + }, + { + "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_conversion_source" + }, + "description": "Sample for DeleteConversionSource", + "file": "merchantapi_v1beta_generated_conversion_sources_service_delete_conversion_source_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_ConversionSourcesService_DeleteConversionSource_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_conversion_sources_service_delete_conversion_source_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient", + "shortName": "ConversionSourcesServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient.get_conversion_source", + "method": { + "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService.GetConversionSource", + "service": { + "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", + "shortName": "ConversionSourcesService" + }, + "shortName": "GetConversionSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_conversions_v1beta.types.GetConversionSourceRequest" + }, + { + "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_conversions_v1beta.types.ConversionSource", + "shortName": "get_conversion_source" + }, + "description": "Sample for GetConversionSource", + "file": "merchantapi_v1beta_generated_conversion_sources_service_get_conversion_source_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_ConversionSourcesService_GetConversionSource_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_conversion_sources_service_get_conversion_source_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceClient", + "shortName": "ConversionSourcesServiceClient" + }, + "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceClient.get_conversion_source", + "method": { + "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService.GetConversionSource", + "service": { + "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", + "shortName": "ConversionSourcesService" + }, + "shortName": "GetConversionSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_conversions_v1beta.types.GetConversionSourceRequest" + }, + { + "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_conversions_v1beta.types.ConversionSource", + "shortName": "get_conversion_source" + }, + "description": "Sample for GetConversionSource", + "file": "merchantapi_v1beta_generated_conversion_sources_service_get_conversion_source_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_ConversionSourcesService_GetConversionSource_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_conversion_sources_service_get_conversion_source_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient", + "shortName": "ConversionSourcesServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient.list_conversion_sources", + "method": { + "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService.ListConversionSources", + "service": { + "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", + "shortName": "ConversionSourcesService" + }, + "shortName": "ListConversionSources" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_conversions_v1beta.types.ListConversionSourcesRequest" + }, + { + "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_conversions_v1beta.services.conversion_sources_service.pagers.ListConversionSourcesAsyncPager", + "shortName": "list_conversion_sources" + }, + "description": "Sample for ListConversionSources", + "file": "merchantapi_v1beta_generated_conversion_sources_service_list_conversion_sources_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_ConversionSourcesService_ListConversionSources_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_conversion_sources_service_list_conversion_sources_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceClient", + "shortName": "ConversionSourcesServiceClient" + }, + "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceClient.list_conversion_sources", + "method": { + "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService.ListConversionSources", + "service": { + "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", + "shortName": "ConversionSourcesService" + }, + "shortName": "ListConversionSources" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_conversions_v1beta.types.ListConversionSourcesRequest" + }, + { + "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_conversions_v1beta.services.conversion_sources_service.pagers.ListConversionSourcesPager", + "shortName": "list_conversion_sources" + }, + "description": "Sample for ListConversionSources", + "file": "merchantapi_v1beta_generated_conversion_sources_service_list_conversion_sources_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_ConversionSourcesService_ListConversionSources_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_conversion_sources_service_list_conversion_sources_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient", + "shortName": "ConversionSourcesServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient.undelete_conversion_source", + "method": { + "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService.UndeleteConversionSource", + "service": { + "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", + "shortName": "ConversionSourcesService" + }, + "shortName": "UndeleteConversionSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_conversions_v1beta.types.UndeleteConversionSourceRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.shopping.merchant_conversions_v1beta.types.ConversionSource", + "shortName": "undelete_conversion_source" + }, + "description": "Sample for UndeleteConversionSource", + "file": "merchantapi_v1beta_generated_conversion_sources_service_undelete_conversion_source_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_ConversionSourcesService_UndeleteConversionSource_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_conversion_sources_service_undelete_conversion_source_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceClient", + "shortName": "ConversionSourcesServiceClient" + }, + "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceClient.undelete_conversion_source", + "method": { + "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService.UndeleteConversionSource", + "service": { + "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", + "shortName": "ConversionSourcesService" + }, + "shortName": "UndeleteConversionSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_conversions_v1beta.types.UndeleteConversionSourceRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.shopping.merchant_conversions_v1beta.types.ConversionSource", + "shortName": "undelete_conversion_source" + }, + "description": "Sample for UndeleteConversionSource", + "file": "merchantapi_v1beta_generated_conversion_sources_service_undelete_conversion_source_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_ConversionSourcesService_UndeleteConversionSource_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_conversion_sources_service_undelete_conversion_source_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient", + "shortName": "ConversionSourcesServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient.update_conversion_source", + "method": { + "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService.UpdateConversionSource", + "service": { + "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", + "shortName": "ConversionSourcesService" + }, + "shortName": "UpdateConversionSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_conversions_v1beta.types.UpdateConversionSourceRequest" + }, + { + "name": "conversion_source", + "type": "google.shopping.merchant_conversions_v1beta.types.ConversionSource" + }, + { + "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_conversions_v1beta.types.ConversionSource", + "shortName": "update_conversion_source" + }, + "description": "Sample for UpdateConversionSource", + "file": "merchantapi_v1beta_generated_conversion_sources_service_update_conversion_source_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_ConversionSourcesService_UpdateConversionSource_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_conversion_sources_service_update_conversion_source_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceClient", + "shortName": "ConversionSourcesServiceClient" + }, + "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceClient.update_conversion_source", + "method": { + "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService.UpdateConversionSource", + "service": { + "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", + "shortName": "ConversionSourcesService" + }, + "shortName": "UpdateConversionSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_conversions_v1beta.types.UpdateConversionSourceRequest" + }, + { + "name": "conversion_source", + "type": "google.shopping.merchant_conversions_v1beta.types.ConversionSource" + }, + { + "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_conversions_v1beta.types.ConversionSource", + "shortName": "update_conversion_source" + }, + "description": "Sample for UpdateConversionSource", + "file": "merchantapi_v1beta_generated_conversion_sources_service_update_conversion_source_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_ConversionSourcesService_UpdateConversionSource_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_conversion_sources_service_update_conversion_source_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/scripts/fixup_merchant_conversions_v1beta_keywords.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/scripts/fixup_merchant_conversions_v1beta_keywords.py new file mode 100644 index 000000000000..e0b3604e0ad3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/scripts/fixup_merchant_conversions_v1beta_keywords.py @@ -0,0 +1,181 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_conversionsCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_conversion_source': ('parent', 'conversion_source', ), + 'delete_conversion_source': ('name', ), + 'get_conversion_source': ('name', ), + 'list_conversion_sources': ('parent', 'page_size', 'page_token', 'show_deleted', ), + 'undelete_conversion_source': ('name', ), + 'update_conversion_source': ('conversion_source', '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_conversionsCallTransformer(), +): + """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_conversions 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-conversions/v1beta/setup.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/setup.py new file mode 100644 index 000000000000..f3c03c6e0f40 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/setup.py @@ -0,0 +1,98 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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-conversions' + + +description = "Google Shopping Merchant Conversions API client library" + +version = None + +with open(os.path.join(package_root, 'google/shopping/merchant_conversions/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.0dev,!=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.0dev,!=2.24.0,!=2.25.0", + "proto-plus >= 1.22.3, <2.0.0dev", + "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'", + "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", +] +extras = { +} +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-conversions" + +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-conversions/v1beta/testing/constraints-3.10.txt b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.10.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.11.txt b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.11.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.12.txt b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.12.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.13.txt b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.13.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.13.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.7.txt b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.7.txt new file mode 100644 index 000000000000..fc812592b0ee --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.7.txt @@ -0,0 +1,10 @@ +# 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.0dev", +# 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 diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.8.txt b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.8.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.9.txt b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.9.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/tests/__init__.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-conversions/v1beta/tests/unit/__init__.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-conversions/v1beta/tests/unit/gapic/__init__.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-conversions/v1beta/tests/unit/gapic/merchant_conversions_v1beta/__init__.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/tests/unit/gapic/merchant_conversions_v1beta/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/tests/unit/gapic/merchant_conversions_v1beta/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-conversions/v1beta/tests/unit/gapic/merchant_conversions_v1beta/test_conversion_sources_service.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/tests/unit/gapic/merchant_conversions_v1beta/test_conversion_sources_service.py new file mode 100644 index 000000000000..01083599d323 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/tests/unit/gapic/merchant_conversions_v1beta/test_conversion_sources_service.py @@ -0,0 +1,5664 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_conversions_v1beta.services.conversion_sources_service import ConversionSourcesServiceAsyncClient +from google.shopping.merchant_conversions_v1beta.services.conversion_sources_service import ConversionSourcesServiceClient +from google.shopping.merchant_conversions_v1beta.services.conversion_sources_service import pagers +from google.shopping.merchant_conversions_v1beta.services.conversion_sources_service import transports +from google.shopping.merchant_conversions_v1beta.types import conversionsources +import google.auth + + +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 ConversionSourcesServiceClient._get_default_mtls_endpoint(None) is None + assert ConversionSourcesServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ConversionSourcesServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ConversionSourcesServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ConversionSourcesServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ConversionSourcesServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert ConversionSourcesServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert ConversionSourcesServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert ConversionSourcesServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + ConversionSourcesServiceClient._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 ConversionSourcesServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert ConversionSourcesServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert ConversionSourcesServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + ConversionSourcesServiceClient._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 ConversionSourcesServiceClient._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 ConversionSourcesServiceClient._get_client_cert_source(None, False) is None + assert ConversionSourcesServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert ConversionSourcesServiceClient._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 ConversionSourcesServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert ConversionSourcesServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(ConversionSourcesServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ConversionSourcesServiceClient)) +@mock.patch.object(ConversionSourcesServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ConversionSourcesServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = ConversionSourcesServiceClient._DEFAULT_UNIVERSE + default_endpoint = ConversionSourcesServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = ConversionSourcesServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert ConversionSourcesServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert ConversionSourcesServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == ConversionSourcesServiceClient.DEFAULT_MTLS_ENDPOINT + assert ConversionSourcesServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert ConversionSourcesServiceClient._get_api_endpoint(None, None, default_universe, "always") == ConversionSourcesServiceClient.DEFAULT_MTLS_ENDPOINT + assert ConversionSourcesServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == ConversionSourcesServiceClient.DEFAULT_MTLS_ENDPOINT + assert ConversionSourcesServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert ConversionSourcesServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + ConversionSourcesServiceClient._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 ConversionSourcesServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert ConversionSourcesServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert ConversionSourcesServiceClient._get_universe_domain(None, None) == ConversionSourcesServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + ConversionSourcesServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize("client_class,transport_name", [ + (ConversionSourcesServiceClient, "grpc"), + (ConversionSourcesServiceAsyncClient, "grpc_asyncio"), + (ConversionSourcesServiceClient, "rest"), +]) +def test_conversion_sources_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.ConversionSourcesServiceGrpcTransport, "grpc"), + (transports.ConversionSourcesServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.ConversionSourcesServiceRestTransport, "rest"), +]) +def test_conversion_sources_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", [ + (ConversionSourcesServiceClient, "grpc"), + (ConversionSourcesServiceAsyncClient, "grpc_asyncio"), + (ConversionSourcesServiceClient, "rest"), +]) +def test_conversion_sources_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_conversion_sources_service_client_get_transport_class(): + transport = ConversionSourcesServiceClient.get_transport_class() + available_transports = [ + transports.ConversionSourcesServiceGrpcTransport, + transports.ConversionSourcesServiceRestTransport, + ] + assert transport in available_transports + + transport = ConversionSourcesServiceClient.get_transport_class("grpc") + assert transport == transports.ConversionSourcesServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ConversionSourcesServiceClient, transports.ConversionSourcesServiceGrpcTransport, "grpc"), + (ConversionSourcesServiceAsyncClient, transports.ConversionSourcesServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (ConversionSourcesServiceClient, transports.ConversionSourcesServiceRestTransport, "rest"), +]) +@mock.patch.object(ConversionSourcesServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ConversionSourcesServiceClient)) +@mock.patch.object(ConversionSourcesServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ConversionSourcesServiceAsyncClient)) +def test_conversion_sources_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(ConversionSourcesServiceClient, '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(ConversionSourcesServiceClient, '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", [ + (ConversionSourcesServiceClient, transports.ConversionSourcesServiceGrpcTransport, "grpc", "true"), + (ConversionSourcesServiceAsyncClient, transports.ConversionSourcesServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ConversionSourcesServiceClient, transports.ConversionSourcesServiceGrpcTransport, "grpc", "false"), + (ConversionSourcesServiceAsyncClient, transports.ConversionSourcesServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (ConversionSourcesServiceClient, transports.ConversionSourcesServiceRestTransport, "rest", "true"), + (ConversionSourcesServiceClient, transports.ConversionSourcesServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(ConversionSourcesServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ConversionSourcesServiceClient)) +@mock.patch.object(ConversionSourcesServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ConversionSourcesServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_conversion_sources_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", [ + ConversionSourcesServiceClient, ConversionSourcesServiceAsyncClient +]) +@mock.patch.object(ConversionSourcesServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversionSourcesServiceClient)) +@mock.patch.object(ConversionSourcesServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversionSourcesServiceAsyncClient)) +def test_conversion_sources_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", [ + ConversionSourcesServiceClient, ConversionSourcesServiceAsyncClient +]) +@mock.patch.object(ConversionSourcesServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ConversionSourcesServiceClient)) +@mock.patch.object(ConversionSourcesServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ConversionSourcesServiceAsyncClient)) +def test_conversion_sources_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = ConversionSourcesServiceClient._DEFAULT_UNIVERSE + default_endpoint = ConversionSourcesServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = ConversionSourcesServiceClient._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", [ + (ConversionSourcesServiceClient, transports.ConversionSourcesServiceGrpcTransport, "grpc"), + (ConversionSourcesServiceAsyncClient, transports.ConversionSourcesServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (ConversionSourcesServiceClient, transports.ConversionSourcesServiceRestTransport, "rest"), +]) +def test_conversion_sources_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", [ + (ConversionSourcesServiceClient, transports.ConversionSourcesServiceGrpcTransport, "grpc", grpc_helpers), + (ConversionSourcesServiceAsyncClient, transports.ConversionSourcesServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (ConversionSourcesServiceClient, transports.ConversionSourcesServiceRestTransport, "rest", None), +]) +def test_conversion_sources_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_conversion_sources_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_conversions_v1beta.services.conversion_sources_service.transports.ConversionSourcesServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ConversionSourcesServiceClient( + 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", [ + (ConversionSourcesServiceClient, transports.ConversionSourcesServiceGrpcTransport, "grpc", grpc_helpers), + (ConversionSourcesServiceAsyncClient, transports.ConversionSourcesServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_conversion_sources_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", [ + conversionsources.CreateConversionSourceRequest, + dict, +]) +def test_create_conversion_source(request_type, transport: str = 'grpc'): + client = ConversionSourcesServiceClient( + 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_conversion_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversionsources.ConversionSource( + name='name_value', + state=conversionsources.ConversionSource.State.ACTIVE, + controller=conversionsources.ConversionSource.Controller.MERCHANT, + ) + response = client.create_conversion_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = conversionsources.CreateConversionSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, conversionsources.ConversionSource) + assert response.name == 'name_value' + assert response.state == conversionsources.ConversionSource.State.ACTIVE + assert response.controller == conversionsources.ConversionSource.Controller.MERCHANT + + +def test_create_conversion_source_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 = ConversionSourcesServiceClient( + 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 = conversionsources.CreateConversionSourceRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversion_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_conversion_source(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == conversionsources.CreateConversionSourceRequest( + parent='parent_value', + ) + +def test_create_conversion_source_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ConversionSourcesServiceClient( + 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_conversion_source in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_conversion_source] = mock_rpc + request = {} + client.create_conversion_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_conversion_source(request) + + # Establish that a new wrapper 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_conversion_source_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = ConversionSourcesServiceAsyncClient( + 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_conversion_source in client._client._transport._wrapped_methods + + # 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_conversion_source] = mock_rpc + + request = {} + await client.create_conversion_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_conversion_source(request) + + # Establish that a new wrapper 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_conversion_source_async(transport: str = 'grpc_asyncio', request_type=conversionsources.CreateConversionSourceRequest): + client = ConversionSourcesServiceAsyncClient( + 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_conversion_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversionsources.ConversionSource( + name='name_value', + state=conversionsources.ConversionSource.State.ACTIVE, + controller=conversionsources.ConversionSource.Controller.MERCHANT, + )) + response = await client.create_conversion_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = conversionsources.CreateConversionSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, conversionsources.ConversionSource) + assert response.name == 'name_value' + assert response.state == conversionsources.ConversionSource.State.ACTIVE + assert response.controller == conversionsources.ConversionSource.Controller.MERCHANT + + +@pytest.mark.asyncio +async def test_create_conversion_source_async_from_dict(): + await test_create_conversion_source_async(request_type=dict) + +def test_create_conversion_source_field_headers(): + client = ConversionSourcesServiceClient( + 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 = conversionsources.CreateConversionSourceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversion_source), + '__call__') as call: + call.return_value = conversionsources.ConversionSource() + client.create_conversion_source(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_conversion_source_field_headers_async(): + client = ConversionSourcesServiceAsyncClient( + 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 = conversionsources.CreateConversionSourceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversion_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversionsources.ConversionSource()) + await client.create_conversion_source(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_conversion_source_flattened(): + client = ConversionSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversion_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversionsources.ConversionSource() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_conversion_source( + parent='parent_value', + conversion_source=conversionsources.ConversionSource(google_analytics_link=conversionsources.GoogleAnalyticsLink(property_id=1201)), + ) + + # 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].conversion_source + mock_val = conversionsources.ConversionSource(google_analytics_link=conversionsources.GoogleAnalyticsLink(property_id=1201)) + assert arg == mock_val + + +def test_create_conversion_source_flattened_error(): + client = ConversionSourcesServiceClient( + 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_conversion_source( + conversionsources.CreateConversionSourceRequest(), + parent='parent_value', + conversion_source=conversionsources.ConversionSource(google_analytics_link=conversionsources.GoogleAnalyticsLink(property_id=1201)), + ) + +@pytest.mark.asyncio +async def test_create_conversion_source_flattened_async(): + client = ConversionSourcesServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversion_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversionsources.ConversionSource() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversionsources.ConversionSource()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_conversion_source( + parent='parent_value', + conversion_source=conversionsources.ConversionSource(google_analytics_link=conversionsources.GoogleAnalyticsLink(property_id=1201)), + ) + + # 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].conversion_source + mock_val = conversionsources.ConversionSource(google_analytics_link=conversionsources.GoogleAnalyticsLink(property_id=1201)) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_conversion_source_flattened_error_async(): + client = ConversionSourcesServiceAsyncClient( + 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_conversion_source( + conversionsources.CreateConversionSourceRequest(), + parent='parent_value', + conversion_source=conversionsources.ConversionSource(google_analytics_link=conversionsources.GoogleAnalyticsLink(property_id=1201)), + ) + + +@pytest.mark.parametrize("request_type", [ + conversionsources.UpdateConversionSourceRequest, + dict, +]) +def test_update_conversion_source(request_type, transport: str = 'grpc'): + client = ConversionSourcesServiceClient( + 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_conversion_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversionsources.ConversionSource( + name='name_value', + state=conversionsources.ConversionSource.State.ACTIVE, + controller=conversionsources.ConversionSource.Controller.MERCHANT, + ) + response = client.update_conversion_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = conversionsources.UpdateConversionSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, conversionsources.ConversionSource) + assert response.name == 'name_value' + assert response.state == conversionsources.ConversionSource.State.ACTIVE + assert response.controller == conversionsources.ConversionSource.Controller.MERCHANT + + +def test_update_conversion_source_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 = ConversionSourcesServiceClient( + 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 = conversionsources.UpdateConversionSourceRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_conversion_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_conversion_source(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == conversionsources.UpdateConversionSourceRequest( + ) + +def test_update_conversion_source_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ConversionSourcesServiceClient( + 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_conversion_source in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_conversion_source] = mock_rpc + request = {} + client.update_conversion_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_conversion_source(request) + + # Establish that a new wrapper 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_conversion_source_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = ConversionSourcesServiceAsyncClient( + 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_conversion_source in client._client._transport._wrapped_methods + + # 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_conversion_source] = mock_rpc + + request = {} + await client.update_conversion_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_conversion_source(request) + + # Establish that a new wrapper 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_conversion_source_async(transport: str = 'grpc_asyncio', request_type=conversionsources.UpdateConversionSourceRequest): + client = ConversionSourcesServiceAsyncClient( + 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_conversion_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversionsources.ConversionSource( + name='name_value', + state=conversionsources.ConversionSource.State.ACTIVE, + controller=conversionsources.ConversionSource.Controller.MERCHANT, + )) + response = await client.update_conversion_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = conversionsources.UpdateConversionSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, conversionsources.ConversionSource) + assert response.name == 'name_value' + assert response.state == conversionsources.ConversionSource.State.ACTIVE + assert response.controller == conversionsources.ConversionSource.Controller.MERCHANT + + +@pytest.mark.asyncio +async def test_update_conversion_source_async_from_dict(): + await test_update_conversion_source_async(request_type=dict) + +def test_update_conversion_source_field_headers(): + client = ConversionSourcesServiceClient( + 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 = conversionsources.UpdateConversionSourceRequest() + + request.conversion_source.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_conversion_source), + '__call__') as call: + call.return_value = conversionsources.ConversionSource() + client.update_conversion_source(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', + 'conversion_source.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_conversion_source_field_headers_async(): + client = ConversionSourcesServiceAsyncClient( + 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 = conversionsources.UpdateConversionSourceRequest() + + request.conversion_source.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_conversion_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversionsources.ConversionSource()) + await client.update_conversion_source(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', + 'conversion_source.name=name_value', + ) in kw['metadata'] + + +def test_update_conversion_source_flattened(): + client = ConversionSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_conversion_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversionsources.ConversionSource() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_conversion_source( + conversion_source=conversionsources.ConversionSource(google_analytics_link=conversionsources.GoogleAnalyticsLink(property_id=1201)), + 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].conversion_source + mock_val = conversionsources.ConversionSource(google_analytics_link=conversionsources.GoogleAnalyticsLink(property_id=1201)) + 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_conversion_source_flattened_error(): + client = ConversionSourcesServiceClient( + 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_conversion_source( + conversionsources.UpdateConversionSourceRequest(), + conversion_source=conversionsources.ConversionSource(google_analytics_link=conversionsources.GoogleAnalyticsLink(property_id=1201)), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_conversion_source_flattened_async(): + client = ConversionSourcesServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_conversion_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversionsources.ConversionSource() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversionsources.ConversionSource()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_conversion_source( + conversion_source=conversionsources.ConversionSource(google_analytics_link=conversionsources.GoogleAnalyticsLink(property_id=1201)), + 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].conversion_source + mock_val = conversionsources.ConversionSource(google_analytics_link=conversionsources.GoogleAnalyticsLink(property_id=1201)) + 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_conversion_source_flattened_error_async(): + client = ConversionSourcesServiceAsyncClient( + 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_conversion_source( + conversionsources.UpdateConversionSourceRequest(), + conversion_source=conversionsources.ConversionSource(google_analytics_link=conversionsources.GoogleAnalyticsLink(property_id=1201)), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + conversionsources.DeleteConversionSourceRequest, + dict, +]) +def test_delete_conversion_source(request_type, transport: str = 'grpc'): + client = ConversionSourcesServiceClient( + 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_conversion_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_conversion_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = conversionsources.DeleteConversionSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_conversion_source_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 = ConversionSourcesServiceClient( + 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 = conversionsources.DeleteConversionSourceRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversion_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_conversion_source(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == conversionsources.DeleteConversionSourceRequest( + name='name_value', + ) + +def test_delete_conversion_source_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ConversionSourcesServiceClient( + 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_conversion_source in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_conversion_source] = mock_rpc + request = {} + client.delete_conversion_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_conversion_source(request) + + # Establish that a new wrapper 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_conversion_source_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = ConversionSourcesServiceAsyncClient( + 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_conversion_source in client._client._transport._wrapped_methods + + # 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_conversion_source] = mock_rpc + + request = {} + await client.delete_conversion_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_conversion_source(request) + + # Establish that a new wrapper 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_conversion_source_async(transport: str = 'grpc_asyncio', request_type=conversionsources.DeleteConversionSourceRequest): + client = ConversionSourcesServiceAsyncClient( + 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_conversion_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_conversion_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = conversionsources.DeleteConversionSourceRequest() + 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_conversion_source_async_from_dict(): + await test_delete_conversion_source_async(request_type=dict) + +def test_delete_conversion_source_field_headers(): + client = ConversionSourcesServiceClient( + 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 = conversionsources.DeleteConversionSourceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversion_source), + '__call__') as call: + call.return_value = None + client.delete_conversion_source(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_conversion_source_field_headers_async(): + client = ConversionSourcesServiceAsyncClient( + 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 = conversionsources.DeleteConversionSourceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversion_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_conversion_source(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_conversion_source_flattened(): + client = ConversionSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversion_source), + '__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_conversion_source( + 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_conversion_source_flattened_error(): + client = ConversionSourcesServiceClient( + 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_conversion_source( + conversionsources.DeleteConversionSourceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_conversion_source_flattened_async(): + client = ConversionSourcesServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversion_source), + '__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_conversion_source( + 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_conversion_source_flattened_error_async(): + client = ConversionSourcesServiceAsyncClient( + 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_conversion_source( + conversionsources.DeleteConversionSourceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + conversionsources.UndeleteConversionSourceRequest, + dict, +]) +def test_undelete_conversion_source(request_type, transport: str = 'grpc'): + client = ConversionSourcesServiceClient( + 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.undelete_conversion_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversionsources.ConversionSource( + name='name_value', + state=conversionsources.ConversionSource.State.ACTIVE, + controller=conversionsources.ConversionSource.Controller.MERCHANT, + ) + response = client.undelete_conversion_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = conversionsources.UndeleteConversionSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, conversionsources.ConversionSource) + assert response.name == 'name_value' + assert response.state == conversionsources.ConversionSource.State.ACTIVE + assert response.controller == conversionsources.ConversionSource.Controller.MERCHANT + + +def test_undelete_conversion_source_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 = ConversionSourcesServiceClient( + 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 = conversionsources.UndeleteConversionSourceRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undelete_conversion_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.undelete_conversion_source(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == conversionsources.UndeleteConversionSourceRequest( + name='name_value', + ) + +def test_undelete_conversion_source_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ConversionSourcesServiceClient( + 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.undelete_conversion_source in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.undelete_conversion_source] = mock_rpc + request = {} + client.undelete_conversion_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.undelete_conversion_source(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_undelete_conversion_source_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = ConversionSourcesServiceAsyncClient( + 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.undelete_conversion_source in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.undelete_conversion_source] = mock_rpc + + request = {} + await client.undelete_conversion_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.undelete_conversion_source(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_undelete_conversion_source_async(transport: str = 'grpc_asyncio', request_type=conversionsources.UndeleteConversionSourceRequest): + client = ConversionSourcesServiceAsyncClient( + 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.undelete_conversion_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversionsources.ConversionSource( + name='name_value', + state=conversionsources.ConversionSource.State.ACTIVE, + controller=conversionsources.ConversionSource.Controller.MERCHANT, + )) + response = await client.undelete_conversion_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = conversionsources.UndeleteConversionSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, conversionsources.ConversionSource) + assert response.name == 'name_value' + assert response.state == conversionsources.ConversionSource.State.ACTIVE + assert response.controller == conversionsources.ConversionSource.Controller.MERCHANT + + +@pytest.mark.asyncio +async def test_undelete_conversion_source_async_from_dict(): + await test_undelete_conversion_source_async(request_type=dict) + +def test_undelete_conversion_source_field_headers(): + client = ConversionSourcesServiceClient( + 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 = conversionsources.UndeleteConversionSourceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undelete_conversion_source), + '__call__') as call: + call.return_value = conversionsources.ConversionSource() + client.undelete_conversion_source(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_undelete_conversion_source_field_headers_async(): + client = ConversionSourcesServiceAsyncClient( + 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 = conversionsources.UndeleteConversionSourceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undelete_conversion_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversionsources.ConversionSource()) + await client.undelete_conversion_source(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", [ + conversionsources.GetConversionSourceRequest, + dict, +]) +def test_get_conversion_source(request_type, transport: str = 'grpc'): + client = ConversionSourcesServiceClient( + 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_conversion_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversionsources.ConversionSource( + name='name_value', + state=conversionsources.ConversionSource.State.ACTIVE, + controller=conversionsources.ConversionSource.Controller.MERCHANT, + ) + response = client.get_conversion_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = conversionsources.GetConversionSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, conversionsources.ConversionSource) + assert response.name == 'name_value' + assert response.state == conversionsources.ConversionSource.State.ACTIVE + assert response.controller == conversionsources.ConversionSource.Controller.MERCHANT + + +def test_get_conversion_source_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 = ConversionSourcesServiceClient( + 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 = conversionsources.GetConversionSourceRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversion_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_conversion_source(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == conversionsources.GetConversionSourceRequest( + name='name_value', + ) + +def test_get_conversion_source_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ConversionSourcesServiceClient( + 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_conversion_source in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_conversion_source] = mock_rpc + request = {} + client.get_conversion_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_conversion_source(request) + + # Establish that a new wrapper 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_conversion_source_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = ConversionSourcesServiceAsyncClient( + 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_conversion_source in client._client._transport._wrapped_methods + + # 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_conversion_source] = mock_rpc + + request = {} + await client.get_conversion_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_conversion_source(request) + + # Establish that a new wrapper 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_conversion_source_async(transport: str = 'grpc_asyncio', request_type=conversionsources.GetConversionSourceRequest): + client = ConversionSourcesServiceAsyncClient( + 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_conversion_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversionsources.ConversionSource( + name='name_value', + state=conversionsources.ConversionSource.State.ACTIVE, + controller=conversionsources.ConversionSource.Controller.MERCHANT, + )) + response = await client.get_conversion_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = conversionsources.GetConversionSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, conversionsources.ConversionSource) + assert response.name == 'name_value' + assert response.state == conversionsources.ConversionSource.State.ACTIVE + assert response.controller == conversionsources.ConversionSource.Controller.MERCHANT + + +@pytest.mark.asyncio +async def test_get_conversion_source_async_from_dict(): + await test_get_conversion_source_async(request_type=dict) + +def test_get_conversion_source_field_headers(): + client = ConversionSourcesServiceClient( + 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 = conversionsources.GetConversionSourceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversion_source), + '__call__') as call: + call.return_value = conversionsources.ConversionSource() + client.get_conversion_source(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_conversion_source_field_headers_async(): + client = ConversionSourcesServiceAsyncClient( + 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 = conversionsources.GetConversionSourceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversion_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversionsources.ConversionSource()) + await client.get_conversion_source(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_conversion_source_flattened(): + client = ConversionSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversion_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversionsources.ConversionSource() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_conversion_source( + 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_conversion_source_flattened_error(): + client = ConversionSourcesServiceClient( + 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_conversion_source( + conversionsources.GetConversionSourceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_conversion_source_flattened_async(): + client = ConversionSourcesServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversion_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversionsources.ConversionSource() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversionsources.ConversionSource()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_conversion_source( + 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_conversion_source_flattened_error_async(): + client = ConversionSourcesServiceAsyncClient( + 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_conversion_source( + conversionsources.GetConversionSourceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + conversionsources.ListConversionSourcesRequest, + dict, +]) +def test_list_conversion_sources(request_type, transport: str = 'grpc'): + client = ConversionSourcesServiceClient( + 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_conversion_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversionsources.ListConversionSourcesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_conversion_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = conversionsources.ListConversionSourcesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListConversionSourcesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_conversion_sources_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 = ConversionSourcesServiceClient( + 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 = conversionsources.ListConversionSourcesRequest( + 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_conversion_sources), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_conversion_sources(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == conversionsources.ListConversionSourcesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_conversion_sources_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ConversionSourcesServiceClient( + 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_conversion_sources in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_conversion_sources] = mock_rpc + request = {} + client.list_conversion_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_conversion_sources(request) + + # Establish that a new wrapper 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_conversion_sources_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = ConversionSourcesServiceAsyncClient( + 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_conversion_sources in client._client._transport._wrapped_methods + + # 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_conversion_sources] = mock_rpc + + request = {} + await client.list_conversion_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_conversion_sources(request) + + # Establish that a new wrapper 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_conversion_sources_async(transport: str = 'grpc_asyncio', request_type=conversionsources.ListConversionSourcesRequest): + client = ConversionSourcesServiceAsyncClient( + 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_conversion_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversionsources.ListConversionSourcesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_conversion_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = conversionsources.ListConversionSourcesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListConversionSourcesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_conversion_sources_async_from_dict(): + await test_list_conversion_sources_async(request_type=dict) + +def test_list_conversion_sources_field_headers(): + client = ConversionSourcesServiceClient( + 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 = conversionsources.ListConversionSourcesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversion_sources), + '__call__') as call: + call.return_value = conversionsources.ListConversionSourcesResponse() + client.list_conversion_sources(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_conversion_sources_field_headers_async(): + client = ConversionSourcesServiceAsyncClient( + 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 = conversionsources.ListConversionSourcesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversion_sources), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversionsources.ListConversionSourcesResponse()) + await client.list_conversion_sources(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_conversion_sources_flattened(): + client = ConversionSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversion_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversionsources.ListConversionSourcesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_conversion_sources( + 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_conversion_sources_flattened_error(): + client = ConversionSourcesServiceClient( + 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_conversion_sources( + conversionsources.ListConversionSourcesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_conversion_sources_flattened_async(): + client = ConversionSourcesServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversion_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversionsources.ListConversionSourcesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversionsources.ListConversionSourcesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_conversion_sources( + 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_conversion_sources_flattened_error_async(): + client = ConversionSourcesServiceAsyncClient( + 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_conversion_sources( + conversionsources.ListConversionSourcesRequest(), + parent='parent_value', + ) + + +def test_list_conversion_sources_pager(transport_name: str = "grpc"): + client = ConversionSourcesServiceClient( + 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_conversion_sources), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + conversionsources.ListConversionSourcesResponse( + conversion_sources=[ + conversionsources.ConversionSource(), + conversionsources.ConversionSource(), + conversionsources.ConversionSource(), + ], + next_page_token='abc', + ), + conversionsources.ListConversionSourcesResponse( + conversion_sources=[], + next_page_token='def', + ), + conversionsources.ListConversionSourcesResponse( + conversion_sources=[ + conversionsources.ConversionSource(), + ], + next_page_token='ghi', + ), + conversionsources.ListConversionSourcesResponse( + conversion_sources=[ + conversionsources.ConversionSource(), + conversionsources.ConversionSource(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_conversion_sources(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, conversionsources.ConversionSource) + for i in results) +def test_list_conversion_sources_pages(transport_name: str = "grpc"): + client = ConversionSourcesServiceClient( + 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_conversion_sources), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + conversionsources.ListConversionSourcesResponse( + conversion_sources=[ + conversionsources.ConversionSource(), + conversionsources.ConversionSource(), + conversionsources.ConversionSource(), + ], + next_page_token='abc', + ), + conversionsources.ListConversionSourcesResponse( + conversion_sources=[], + next_page_token='def', + ), + conversionsources.ListConversionSourcesResponse( + conversion_sources=[ + conversionsources.ConversionSource(), + ], + next_page_token='ghi', + ), + conversionsources.ListConversionSourcesResponse( + conversion_sources=[ + conversionsources.ConversionSource(), + conversionsources.ConversionSource(), + ], + ), + RuntimeError, + ) + pages = list(client.list_conversion_sources(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_conversion_sources_async_pager(): + client = ConversionSourcesServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversion_sources), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + conversionsources.ListConversionSourcesResponse( + conversion_sources=[ + conversionsources.ConversionSource(), + conversionsources.ConversionSource(), + conversionsources.ConversionSource(), + ], + next_page_token='abc', + ), + conversionsources.ListConversionSourcesResponse( + conversion_sources=[], + next_page_token='def', + ), + conversionsources.ListConversionSourcesResponse( + conversion_sources=[ + conversionsources.ConversionSource(), + ], + next_page_token='ghi', + ), + conversionsources.ListConversionSourcesResponse( + conversion_sources=[ + conversionsources.ConversionSource(), + conversionsources.ConversionSource(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_conversion_sources(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, conversionsources.ConversionSource) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_conversion_sources_async_pages(): + client = ConversionSourcesServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversion_sources), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + conversionsources.ListConversionSourcesResponse( + conversion_sources=[ + conversionsources.ConversionSource(), + conversionsources.ConversionSource(), + conversionsources.ConversionSource(), + ], + next_page_token='abc', + ), + conversionsources.ListConversionSourcesResponse( + conversion_sources=[], + next_page_token='def', + ), + conversionsources.ListConversionSourcesResponse( + conversion_sources=[ + conversionsources.ConversionSource(), + ], + next_page_token='ghi', + ), + conversionsources.ListConversionSourcesResponse( + conversion_sources=[ + conversionsources.ConversionSource(), + conversionsources.ConversionSource(), + ], + ), + 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_conversion_sources(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_create_conversion_source_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 = ConversionSourcesServiceClient( + 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_conversion_source in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_conversion_source] = mock_rpc + + request = {} + client.create_conversion_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_conversion_source(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_conversion_source_rest_required_fields(request_type=conversionsources.CreateConversionSourceRequest): + transport_class = transports.ConversionSourcesServiceRestTransport + + 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_conversion_source._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_conversion_source._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 = ConversionSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = conversionsources.ConversionSource() + # 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 = conversionsources.ConversionSource.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_conversion_source(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_conversion_source_rest_unset_required_fields(): + transport = transports.ConversionSourcesServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_conversion_source._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "conversionSource", ))) + + +def test_create_conversion_source_rest_flattened(): + client = ConversionSourcesServiceClient( + 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 = conversionsources.ConversionSource() + + # 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', + conversion_source=conversionsources.ConversionSource(google_analytics_link=conversionsources.GoogleAnalyticsLink(property_id=1201)), + ) + 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 = conversionsources.ConversionSource.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_conversion_source(**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/conversions/v1beta/{parent=accounts/*}/conversionSources" % client.transport._host, args[1]) + + +def test_create_conversion_source_rest_flattened_error(transport: str = 'rest'): + client = ConversionSourcesServiceClient( + 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_conversion_source( + conversionsources.CreateConversionSourceRequest(), + parent='parent_value', + conversion_source=conversionsources.ConversionSource(google_analytics_link=conversionsources.GoogleAnalyticsLink(property_id=1201)), + ) + + +def test_update_conversion_source_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 = ConversionSourcesServiceClient( + 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_conversion_source in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_conversion_source] = mock_rpc + + request = {} + client.update_conversion_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_conversion_source(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_conversion_source_rest_required_fields(request_type=conversionsources.UpdateConversionSourceRequest): + transport_class = transports.ConversionSourcesServiceRestTransport + + 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_conversion_source._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_conversion_source._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 = ConversionSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = conversionsources.ConversionSource() + # 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 = conversionsources.ConversionSource.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_conversion_source(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_conversion_source_rest_unset_required_fields(): + transport = transports.ConversionSourcesServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_conversion_source._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("conversionSource", "updateMask", ))) + + +def test_update_conversion_source_rest_flattened(): + client = ConversionSourcesServiceClient( + 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 = conversionsources.ConversionSource() + + # get arguments that satisfy an http rule for this method + sample_request = {'conversion_source': {'name': 'accounts/sample1/conversionSources/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + conversion_source=conversionsources.ConversionSource(google_analytics_link=conversionsources.GoogleAnalyticsLink(property_id=1201)), + 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 = conversionsources.ConversionSource.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_conversion_source(**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/conversions/v1beta/{conversion_source.name=accounts/*/conversionSources/*}" % client.transport._host, args[1]) + + +def test_update_conversion_source_rest_flattened_error(transport: str = 'rest'): + client = ConversionSourcesServiceClient( + 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_conversion_source( + conversionsources.UpdateConversionSourceRequest(), + conversion_source=conversionsources.ConversionSource(google_analytics_link=conversionsources.GoogleAnalyticsLink(property_id=1201)), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_conversion_source_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 = ConversionSourcesServiceClient( + 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_conversion_source in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_conversion_source] = mock_rpc + + request = {} + client.delete_conversion_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_conversion_source(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_conversion_source_rest_required_fields(request_type=conversionsources.DeleteConversionSourceRequest): + transport_class = transports.ConversionSourcesServiceRestTransport + + 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_conversion_source._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_conversion_source._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 = ConversionSourcesServiceClient( + 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_conversion_source(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_conversion_source_rest_unset_required_fields(): + transport = transports.ConversionSourcesServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_conversion_source._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_delete_conversion_source_rest_flattened(): + client = ConversionSourcesServiceClient( + 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/conversionSources/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_conversion_source(**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/conversions/v1beta/{name=accounts/*/conversionSources/*}" % client.transport._host, args[1]) + + +def test_delete_conversion_source_rest_flattened_error(transport: str = 'rest'): + client = ConversionSourcesServiceClient( + 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_conversion_source( + conversionsources.DeleteConversionSourceRequest(), + name='name_value', + ) + + +def test_undelete_conversion_source_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 = ConversionSourcesServiceClient( + 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.undelete_conversion_source in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.undelete_conversion_source] = mock_rpc + + request = {} + client.undelete_conversion_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.undelete_conversion_source(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_undelete_conversion_source_rest_required_fields(request_type=conversionsources.UndeleteConversionSourceRequest): + transport_class = transports.ConversionSourcesServiceRestTransport + + 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()).undelete_conversion_source._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()).undelete_conversion_source._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 = ConversionSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = conversionsources.ConversionSource() + # 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 = conversionsources.ConversionSource.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.undelete_conversion_source(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_undelete_conversion_source_rest_unset_required_fields(): + transport = transports.ConversionSourcesServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.undelete_conversion_source._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_conversion_source_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 = ConversionSourcesServiceClient( + 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_conversion_source in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_conversion_source] = mock_rpc + + request = {} + client.get_conversion_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_conversion_source(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_conversion_source_rest_required_fields(request_type=conversionsources.GetConversionSourceRequest): + transport_class = transports.ConversionSourcesServiceRestTransport + + 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_conversion_source._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_conversion_source._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 = ConversionSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = conversionsources.ConversionSource() + # 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 = conversionsources.ConversionSource.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_conversion_source(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_conversion_source_rest_unset_required_fields(): + transport = transports.ConversionSourcesServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_conversion_source._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_conversion_source_rest_flattened(): + client = ConversionSourcesServiceClient( + 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 = conversionsources.ConversionSource() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/conversionSources/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 = conversionsources.ConversionSource.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_conversion_source(**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/conversions/v1beta/{name=accounts/*/conversionSources/*}" % client.transport._host, args[1]) + + +def test_get_conversion_source_rest_flattened_error(transport: str = 'rest'): + client = ConversionSourcesServiceClient( + 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_conversion_source( + conversionsources.GetConversionSourceRequest(), + name='name_value', + ) + + +def test_list_conversion_sources_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 = ConversionSourcesServiceClient( + 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_conversion_sources in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_conversion_sources] = mock_rpc + + request = {} + client.list_conversion_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_conversion_sources(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_conversion_sources_rest_required_fields(request_type=conversionsources.ListConversionSourcesRequest): + transport_class = transports.ConversionSourcesServiceRestTransport + + 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_conversion_sources._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_conversion_sources._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", "show_deleted", )) + 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 = ConversionSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = conversionsources.ListConversionSourcesResponse() + # 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 = conversionsources.ListConversionSourcesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_conversion_sources(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_conversion_sources_rest_unset_required_fields(): + transport = transports.ConversionSourcesServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_conversion_sources._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", "showDeleted", )) & set(("parent", ))) + + +def test_list_conversion_sources_rest_flattened(): + client = ConversionSourcesServiceClient( + 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 = conversionsources.ListConversionSourcesResponse() + + # 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 = conversionsources.ListConversionSourcesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_conversion_sources(**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/conversions/v1beta/{parent=accounts/*}/conversionSources" % client.transport._host, args[1]) + + +def test_list_conversion_sources_rest_flattened_error(transport: str = 'rest'): + client = ConversionSourcesServiceClient( + 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_conversion_sources( + conversionsources.ListConversionSourcesRequest(), + parent='parent_value', + ) + + +def test_list_conversion_sources_rest_pager(transport: str = 'rest'): + client = ConversionSourcesServiceClient( + 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 = ( + conversionsources.ListConversionSourcesResponse( + conversion_sources=[ + conversionsources.ConversionSource(), + conversionsources.ConversionSource(), + conversionsources.ConversionSource(), + ], + next_page_token='abc', + ), + conversionsources.ListConversionSourcesResponse( + conversion_sources=[], + next_page_token='def', + ), + conversionsources.ListConversionSourcesResponse( + conversion_sources=[ + conversionsources.ConversionSource(), + ], + next_page_token='ghi', + ), + conversionsources.ListConversionSourcesResponse( + conversion_sources=[ + conversionsources.ConversionSource(), + conversionsources.ConversionSource(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(conversionsources.ListConversionSourcesResponse.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_conversion_sources(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, conversionsources.ConversionSource) + for i in results) + + pages = list(client.list_conversion_sources(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.ConversionSourcesServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ConversionSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ConversionSourcesServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ConversionSourcesServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ConversionSourcesServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ConversionSourcesServiceClient( + 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 = ConversionSourcesServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ConversionSourcesServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ConversionSourcesServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ConversionSourcesServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ConversionSourcesServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ConversionSourcesServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ConversionSourcesServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ConversionSourcesServiceGrpcTransport, + transports.ConversionSourcesServiceGrpcAsyncIOTransport, + transports.ConversionSourcesServiceRestTransport, +]) +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 = ConversionSourcesServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = ConversionSourcesServiceClient( + 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_create_conversion_source_empty_call_grpc(): + client = ConversionSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_conversion_source), + '__call__') as call: + call.return_value = conversionsources.ConversionSource() + client.create_conversion_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = conversionsources.CreateConversionSourceRequest() + + assert args[0] == request_msg + + +# This 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_conversion_source_empty_call_grpc(): + client = ConversionSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_conversion_source), + '__call__') as call: + call.return_value = conversionsources.ConversionSource() + client.update_conversion_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = conversionsources.UpdateConversionSourceRequest() + + assert args[0] == request_msg + + +# This 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_conversion_source_empty_call_grpc(): + client = ConversionSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversion_source), + '__call__') as call: + call.return_value = None + client.delete_conversion_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = conversionsources.DeleteConversionSourceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_undelete_conversion_source_empty_call_grpc(): + client = ConversionSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.undelete_conversion_source), + '__call__') as call: + call.return_value = conversionsources.ConversionSource() + client.undelete_conversion_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = conversionsources.UndeleteConversionSourceRequest() + + assert args[0] == request_msg + + +# This 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_conversion_source_empty_call_grpc(): + client = ConversionSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_conversion_source), + '__call__') as call: + call.return_value = conversionsources.ConversionSource() + client.get_conversion_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = conversionsources.GetConversionSourceRequest() + + assert args[0] == request_msg + + +# This 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_conversion_sources_empty_call_grpc(): + client = ConversionSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_conversion_sources), + '__call__') as call: + call.return_value = conversionsources.ListConversionSourcesResponse() + client.list_conversion_sources(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = conversionsources.ListConversionSourcesRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = ConversionSourcesServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = ConversionSourcesServiceAsyncClient( + 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_create_conversion_source_empty_call_grpc_asyncio(): + client = ConversionSourcesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_conversion_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversionsources.ConversionSource( + name='name_value', + state=conversionsources.ConversionSource.State.ACTIVE, + controller=conversionsources.ConversionSource.Controller.MERCHANT, + )) + await client.create_conversion_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = conversionsources.CreateConversionSourceRequest() + + assert args[0] == request_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_conversion_source_empty_call_grpc_asyncio(): + client = ConversionSourcesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_conversion_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversionsources.ConversionSource( + name='name_value', + state=conversionsources.ConversionSource.State.ACTIVE, + controller=conversionsources.ConversionSource.Controller.MERCHANT, + )) + await client.update_conversion_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = conversionsources.UpdateConversionSourceRequest() + + assert args[0] == request_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_conversion_source_empty_call_grpc_asyncio(): + client = ConversionSourcesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversion_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_conversion_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = conversionsources.DeleteConversionSourceRequest() + + assert args[0] == request_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_undelete_conversion_source_empty_call_grpc_asyncio(): + client = ConversionSourcesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.undelete_conversion_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversionsources.ConversionSource( + name='name_value', + state=conversionsources.ConversionSource.State.ACTIVE, + controller=conversionsources.ConversionSource.Controller.MERCHANT, + )) + await client.undelete_conversion_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = conversionsources.UndeleteConversionSourceRequest() + + assert args[0] == request_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_conversion_source_empty_call_grpc_asyncio(): + client = ConversionSourcesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_conversion_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversionsources.ConversionSource( + name='name_value', + state=conversionsources.ConversionSource.State.ACTIVE, + controller=conversionsources.ConversionSource.Controller.MERCHANT, + )) + await client.get_conversion_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = conversionsources.GetConversionSourceRequest() + + assert args[0] == request_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_conversion_sources_empty_call_grpc_asyncio(): + client = ConversionSourcesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_conversion_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversionsources.ListConversionSourcesResponse( + next_page_token='next_page_token_value', + )) + await client.list_conversion_sources(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = conversionsources.ListConversionSourcesRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = ConversionSourcesServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_conversion_source_rest_bad_request(request_type=conversionsources.CreateConversionSourceRequest): + client = ConversionSourcesServiceClient( + 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_conversion_source(request) + + +@pytest.mark.parametrize("request_type", [ + conversionsources.CreateConversionSourceRequest, + dict, +]) +def test_create_conversion_source_rest_call_success(request_type): + client = ConversionSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + request_init["conversion_source"] = {'google_analytics_link': {'property_id': 1201, 'attribution_settings': {'attribution_lookback_window_days': 3425, 'attribution_model': 1, 'conversion_type': [{'name': 'name_value', 'report': True}]}, 'property': 'property_value'}, 'merchant_center_destination': {'destination': 'destination_value', 'attribution_settings': {}, 'display_name': 'display_name_value', 'currency_code': 'currency_code_value'}, 'name': 'name_value', 'state': 1, 'expire_time': {'seconds': 751, 'nanos': 543}, 'controller': 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 = conversionsources.CreateConversionSourceRequest.meta.fields["conversion_source"] + + 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["conversion_source"].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["conversion_source"][field])): + del request_init["conversion_source"][field][i][subfield] + else: + del request_init["conversion_source"][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 = conversionsources.ConversionSource( + name='name_value', + state=conversionsources.ConversionSource.State.ACTIVE, + controller=conversionsources.ConversionSource.Controller.MERCHANT, + ) + + # 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 = conversionsources.ConversionSource.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_conversion_source(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, conversionsources.ConversionSource) + assert response.name == 'name_value' + assert response.state == conversionsources.ConversionSource.State.ACTIVE + assert response.controller == conversionsources.ConversionSource.Controller.MERCHANT + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_conversion_source_rest_interceptors(null_interceptor): + transport = transports.ConversionSourcesServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConversionSourcesServiceRestInterceptor(), + ) + client = ConversionSourcesServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ConversionSourcesServiceRestInterceptor, "post_create_conversion_source") as post, \ + mock.patch.object(transports.ConversionSourcesServiceRestInterceptor, "pre_create_conversion_source") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = conversionsources.CreateConversionSourceRequest.pb(conversionsources.CreateConversionSourceRequest()) + 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 = conversionsources.ConversionSource.to_json(conversionsources.ConversionSource()) + req.return_value.content = return_value + + request = conversionsources.CreateConversionSourceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = conversionsources.ConversionSource() + + client.create_conversion_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_conversion_source_rest_bad_request(request_type=conversionsources.UpdateConversionSourceRequest): + client = ConversionSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'conversion_source': {'name': 'accounts/sample1/conversionSources/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_conversion_source(request) + + +@pytest.mark.parametrize("request_type", [ + conversionsources.UpdateConversionSourceRequest, + dict, +]) +def test_update_conversion_source_rest_call_success(request_type): + client = ConversionSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'conversion_source': {'name': 'accounts/sample1/conversionSources/sample2'}} + request_init["conversion_source"] = {'google_analytics_link': {'property_id': 1201, 'attribution_settings': {'attribution_lookback_window_days': 3425, 'attribution_model': 1, 'conversion_type': [{'name': 'name_value', 'report': True}]}, 'property': 'property_value'}, 'merchant_center_destination': {'destination': 'destination_value', 'attribution_settings': {}, 'display_name': 'display_name_value', 'currency_code': 'currency_code_value'}, 'name': 'accounts/sample1/conversionSources/sample2', 'state': 1, 'expire_time': {'seconds': 751, 'nanos': 543}, 'controller': 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 = conversionsources.UpdateConversionSourceRequest.meta.fields["conversion_source"] + + 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["conversion_source"].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["conversion_source"][field])): + del request_init["conversion_source"][field][i][subfield] + else: + del request_init["conversion_source"][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 = conversionsources.ConversionSource( + name='name_value', + state=conversionsources.ConversionSource.State.ACTIVE, + controller=conversionsources.ConversionSource.Controller.MERCHANT, + ) + + # 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 = conversionsources.ConversionSource.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_conversion_source(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, conversionsources.ConversionSource) + assert response.name == 'name_value' + assert response.state == conversionsources.ConversionSource.State.ACTIVE + assert response.controller == conversionsources.ConversionSource.Controller.MERCHANT + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_conversion_source_rest_interceptors(null_interceptor): + transport = transports.ConversionSourcesServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConversionSourcesServiceRestInterceptor(), + ) + client = ConversionSourcesServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ConversionSourcesServiceRestInterceptor, "post_update_conversion_source") as post, \ + mock.patch.object(transports.ConversionSourcesServiceRestInterceptor, "pre_update_conversion_source") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = conversionsources.UpdateConversionSourceRequest.pb(conversionsources.UpdateConversionSourceRequest()) + 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 = conversionsources.ConversionSource.to_json(conversionsources.ConversionSource()) + req.return_value.content = return_value + + request = conversionsources.UpdateConversionSourceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = conversionsources.ConversionSource() + + client.update_conversion_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_conversion_source_rest_bad_request(request_type=conversionsources.DeleteConversionSourceRequest): + client = ConversionSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/conversionSources/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_conversion_source(request) + + +@pytest.mark.parametrize("request_type", [ + conversionsources.DeleteConversionSourceRequest, + dict, +]) +def test_delete_conversion_source_rest_call_success(request_type): + client = ConversionSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/conversionSources/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_conversion_source(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_conversion_source_rest_interceptors(null_interceptor): + transport = transports.ConversionSourcesServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConversionSourcesServiceRestInterceptor(), + ) + client = ConversionSourcesServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ConversionSourcesServiceRestInterceptor, "pre_delete_conversion_source") as pre: + pre.assert_not_called() + pb_message = conversionsources.DeleteConversionSourceRequest.pb(conversionsources.DeleteConversionSourceRequest()) + 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 = conversionsources.DeleteConversionSourceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_conversion_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_undelete_conversion_source_rest_bad_request(request_type=conversionsources.UndeleteConversionSourceRequest): + client = ConversionSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/conversionSources/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.undelete_conversion_source(request) + + +@pytest.mark.parametrize("request_type", [ + conversionsources.UndeleteConversionSourceRequest, + dict, +]) +def test_undelete_conversion_source_rest_call_success(request_type): + client = ConversionSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/conversionSources/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 = conversionsources.ConversionSource( + name='name_value', + state=conversionsources.ConversionSource.State.ACTIVE, + controller=conversionsources.ConversionSource.Controller.MERCHANT, + ) + + # 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 = conversionsources.ConversionSource.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.undelete_conversion_source(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, conversionsources.ConversionSource) + assert response.name == 'name_value' + assert response.state == conversionsources.ConversionSource.State.ACTIVE + assert response.controller == conversionsources.ConversionSource.Controller.MERCHANT + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_undelete_conversion_source_rest_interceptors(null_interceptor): + transport = transports.ConversionSourcesServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConversionSourcesServiceRestInterceptor(), + ) + client = ConversionSourcesServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ConversionSourcesServiceRestInterceptor, "post_undelete_conversion_source") as post, \ + mock.patch.object(transports.ConversionSourcesServiceRestInterceptor, "pre_undelete_conversion_source") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = conversionsources.UndeleteConversionSourceRequest.pb(conversionsources.UndeleteConversionSourceRequest()) + 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 = conversionsources.ConversionSource.to_json(conversionsources.ConversionSource()) + req.return_value.content = return_value + + request = conversionsources.UndeleteConversionSourceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = conversionsources.ConversionSource() + + client.undelete_conversion_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_conversion_source_rest_bad_request(request_type=conversionsources.GetConversionSourceRequest): + client = ConversionSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/conversionSources/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_conversion_source(request) + + +@pytest.mark.parametrize("request_type", [ + conversionsources.GetConversionSourceRequest, + dict, +]) +def test_get_conversion_source_rest_call_success(request_type): + client = ConversionSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/conversionSources/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 = conversionsources.ConversionSource( + name='name_value', + state=conversionsources.ConversionSource.State.ACTIVE, + controller=conversionsources.ConversionSource.Controller.MERCHANT, + ) + + # 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 = conversionsources.ConversionSource.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_conversion_source(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, conversionsources.ConversionSource) + assert response.name == 'name_value' + assert response.state == conversionsources.ConversionSource.State.ACTIVE + assert response.controller == conversionsources.ConversionSource.Controller.MERCHANT + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_conversion_source_rest_interceptors(null_interceptor): + transport = transports.ConversionSourcesServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConversionSourcesServiceRestInterceptor(), + ) + client = ConversionSourcesServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ConversionSourcesServiceRestInterceptor, "post_get_conversion_source") as post, \ + mock.patch.object(transports.ConversionSourcesServiceRestInterceptor, "pre_get_conversion_source") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = conversionsources.GetConversionSourceRequest.pb(conversionsources.GetConversionSourceRequest()) + 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 = conversionsources.ConversionSource.to_json(conversionsources.ConversionSource()) + req.return_value.content = return_value + + request = conversionsources.GetConversionSourceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = conversionsources.ConversionSource() + + client.get_conversion_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_conversion_sources_rest_bad_request(request_type=conversionsources.ListConversionSourcesRequest): + client = ConversionSourcesServiceClient( + 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_conversion_sources(request) + + +@pytest.mark.parametrize("request_type", [ + conversionsources.ListConversionSourcesRequest, + dict, +]) +def test_list_conversion_sources_rest_call_success(request_type): + client = ConversionSourcesServiceClient( + 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 = conversionsources.ListConversionSourcesResponse( + 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 = conversionsources.ListConversionSourcesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_conversion_sources(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListConversionSourcesPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_conversion_sources_rest_interceptors(null_interceptor): + transport = transports.ConversionSourcesServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConversionSourcesServiceRestInterceptor(), + ) + client = ConversionSourcesServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ConversionSourcesServiceRestInterceptor, "post_list_conversion_sources") as post, \ + mock.patch.object(transports.ConversionSourcesServiceRestInterceptor, "pre_list_conversion_sources") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = conversionsources.ListConversionSourcesRequest.pb(conversionsources.ListConversionSourcesRequest()) + 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 = conversionsources.ListConversionSourcesResponse.to_json(conversionsources.ListConversionSourcesResponse()) + req.return_value.content = return_value + + request = conversionsources.ListConversionSourcesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = conversionsources.ListConversionSourcesResponse() + + client.list_conversion_sources(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + +def test_initialize_client_w_rest(): + client = ConversionSourcesServiceClient( + 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_create_conversion_source_empty_call_rest(): + client = ConversionSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_conversion_source), + '__call__') as call: + client.create_conversion_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = conversionsources.CreateConversionSourceRequest() + + assert args[0] == request_msg + + +# This 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_conversion_source_empty_call_rest(): + client = ConversionSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_conversion_source), + '__call__') as call: + client.update_conversion_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = conversionsources.UpdateConversionSourceRequest() + + assert args[0] == request_msg + + +# This 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_conversion_source_empty_call_rest(): + client = ConversionSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversion_source), + '__call__') as call: + client.delete_conversion_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = conversionsources.DeleteConversionSourceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_undelete_conversion_source_empty_call_rest(): + client = ConversionSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.undelete_conversion_source), + '__call__') as call: + client.undelete_conversion_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = conversionsources.UndeleteConversionSourceRequest() + + assert args[0] == request_msg + + +# This 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_conversion_source_empty_call_rest(): + client = ConversionSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_conversion_source), + '__call__') as call: + client.get_conversion_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = conversionsources.GetConversionSourceRequest() + + assert args[0] == request_msg + + +# This 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_conversion_sources_empty_call_rest(): + client = ConversionSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_conversion_sources), + '__call__') as call: + client.list_conversion_sources(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = conversionsources.ListConversionSourcesRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = ConversionSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ConversionSourcesServiceGrpcTransport, + ) + +def test_conversion_sources_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ConversionSourcesServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_conversion_sources_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_conversions_v1beta.services.conversion_sources_service.transports.ConversionSourcesServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ConversionSourcesServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_conversion_source', + 'update_conversion_source', + 'delete_conversion_source', + 'undelete_conversion_source', + 'get_conversion_source', + 'list_conversion_sources', + ) + 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_conversion_sources_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_conversions_v1beta.services.conversion_sources_service.transports.ConversionSourcesServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ConversionSourcesServiceTransport( + 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_conversion_sources_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_conversions_v1beta.services.conversion_sources_service.transports.ConversionSourcesServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ConversionSourcesServiceTransport() + adc.assert_called_once() + + +def test_conversion_sources_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) + ConversionSourcesServiceClient() + 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.ConversionSourcesServiceGrpcTransport, + transports.ConversionSourcesServiceGrpcAsyncIOTransport, + ], +) +def test_conversion_sources_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.ConversionSourcesServiceGrpcTransport, + transports.ConversionSourcesServiceGrpcAsyncIOTransport, + transports.ConversionSourcesServiceRestTransport, + ], +) +def test_conversion_sources_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.ConversionSourcesServiceGrpcTransport, grpc_helpers), + (transports.ConversionSourcesServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_conversion_sources_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.ConversionSourcesServiceGrpcTransport, transports.ConversionSourcesServiceGrpcAsyncIOTransport]) +def test_conversion_sources_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_conversion_sources_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.ConversionSourcesServiceRestTransport ( + 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_conversion_sources_service_host_no_port(transport_name): + client = ConversionSourcesServiceClient( + 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_conversion_sources_service_host_with_port(transport_name): + client = ConversionSourcesServiceClient( + 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_conversion_sources_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = ConversionSourcesServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = ConversionSourcesServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_conversion_source._session + session2 = client2.transport.create_conversion_source._session + assert session1 != session2 + session1 = client1.transport.update_conversion_source._session + session2 = client2.transport.update_conversion_source._session + assert session1 != session2 + session1 = client1.transport.delete_conversion_source._session + session2 = client2.transport.delete_conversion_source._session + assert session1 != session2 + session1 = client1.transport.undelete_conversion_source._session + session2 = client2.transport.undelete_conversion_source._session + assert session1 != session2 + session1 = client1.transport.get_conversion_source._session + session2 = client2.transport.get_conversion_source._session + assert session1 != session2 + session1 = client1.transport.list_conversion_sources._session + session2 = client2.transport.list_conversion_sources._session + assert session1 != session2 +def test_conversion_sources_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ConversionSourcesServiceGrpcTransport( + 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_conversion_sources_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ConversionSourcesServiceGrpcAsyncIOTransport( + 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.ConversionSourcesServiceGrpcTransport, transports.ConversionSourcesServiceGrpcAsyncIOTransport]) +def test_conversion_sources_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.ConversionSourcesServiceGrpcTransport, transports.ConversionSourcesServiceGrpcAsyncIOTransport]) +def test_conversion_sources_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_conversion_source_path(): + account = "squid" + conversion_source = "clam" + expected = "accounts/{account}/conversionSources/{conversion_source}".format(account=account, conversion_source=conversion_source, ) + actual = ConversionSourcesServiceClient.conversion_source_path(account, conversion_source) + assert expected == actual + + +def test_parse_conversion_source_path(): + expected = { + "account": "whelk", + "conversion_source": "octopus", + } + path = ConversionSourcesServiceClient.conversion_source_path(**expected) + + # Check that the path construction is reversible. + actual = ConversionSourcesServiceClient.parse_conversion_source_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ConversionSourcesServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = ConversionSourcesServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ConversionSourcesServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = ConversionSourcesServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = ConversionSourcesServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ConversionSourcesServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ConversionSourcesServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = ConversionSourcesServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ConversionSourcesServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = ConversionSourcesServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = ConversionSourcesServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ConversionSourcesServiceClient.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 = ConversionSourcesServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = ConversionSourcesServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ConversionSourcesServiceClient.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.ConversionSourcesServiceTransport, '_prep_wrapped_messages') as prep: + client = ConversionSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ConversionSourcesServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = ConversionSourcesServiceClient.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 = ConversionSourcesServiceClient( + 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 = ConversionSourcesServiceAsyncClient( + 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 = ConversionSourcesServiceClient( + 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 = ConversionSourcesServiceClient( + 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", [ + (ConversionSourcesServiceClient, transports.ConversionSourcesServiceGrpcTransport), + (ConversionSourcesServiceAsyncClient, transports.ConversionSourcesServiceGrpcAsyncIOTransport), +]) +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-datasources/v1beta/.coveragerc b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/.coveragerc new file mode 100644 index 000000000000..67aeac1093c8 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/shopping/merchant_datasources/__init__.py + google/shopping/merchant_datasources/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-datasources/v1beta/.flake8 b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/MANIFEST.in b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/MANIFEST.in new file mode 100644 index 000000000000..ab3bc5b3d4df --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/shopping/merchant_datasources *.py +recursive-include google/shopping/merchant_datasources_v1beta *.py diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/README.rst b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/README.rst new file mode 100644 index 000000000000..8a0e5d463dd0 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Shopping Merchant Datasources 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 Datasources 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 diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/_static/custom.css b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/conf.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/conf.py new file mode 100644 index 000000000000..52640877d629 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-datasources 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("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# 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.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +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-datasources" +copyright = u"2023, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# 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 = 'en' + +# 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"] + +# 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 Python", + "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-datasources-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-datasources.tex", + u"google-shopping-merchant-datasources 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-datasources", + u"Google Shopping Merchant Datasources 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-datasources", + u"google-shopping-merchant-datasources Documentation", + author, + "google-shopping-merchant-datasources", + "GAPIC library for Google Shopping Merchant Datasources API", + "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": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", 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-datasources/v1beta/docs/index.rst b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/index.rst new file mode 100644 index 000000000000..dd26af210690 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + merchant_datasources_v1beta/services_ + merchant_datasources_v1beta/types_ diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/merchant_datasources_v1beta/data_sources_service.rst b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/merchant_datasources_v1beta/data_sources_service.rst new file mode 100644 index 000000000000..0adda9607d6f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/merchant_datasources_v1beta/data_sources_service.rst @@ -0,0 +1,10 @@ +DataSourcesService +------------------------------------ + +.. automodule:: google.shopping.merchant_datasources_v1beta.services.data_sources_service + :members: + :inherited-members: + +.. automodule:: google.shopping.merchant_datasources_v1beta.services.data_sources_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/merchant_datasources_v1beta/file_uploads_service.rst b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/merchant_datasources_v1beta/file_uploads_service.rst new file mode 100644 index 000000000000..2cb7cfc2bd21 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/merchant_datasources_v1beta/file_uploads_service.rst @@ -0,0 +1,6 @@ +FileUploadsService +------------------------------------ + +.. automodule:: google.shopping.merchant_datasources_v1beta.services.file_uploads_service + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/merchant_datasources_v1beta/services_.rst b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/merchant_datasources_v1beta/services_.rst new file mode 100644 index 000000000000..c306312a77f1 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/merchant_datasources_v1beta/services_.rst @@ -0,0 +1,7 @@ +Services for Google Shopping Merchant Datasources v1beta API +============================================================ +.. toctree:: + :maxdepth: 2 + + data_sources_service + file_uploads_service diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/merchant_datasources_v1beta/types_.rst b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/merchant_datasources_v1beta/types_.rst new file mode 100644 index 000000000000..567ff11ee41e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/merchant_datasources_v1beta/types_.rst @@ -0,0 +1,6 @@ +Types for Google Shopping Merchant Datasources v1beta API +========================================================= + +.. automodule:: google.shopping.merchant_datasources_v1beta.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources/__init__.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources/__init__.py new file mode 100644 index 000000000000..9ce584515e52 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources/__init__.py @@ -0,0 +1,65 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_datasources import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.shopping.merchant_datasources_v1beta.services.data_sources_service.client import DataSourcesServiceClient +from google.shopping.merchant_datasources_v1beta.services.data_sources_service.async_client import DataSourcesServiceAsyncClient +from google.shopping.merchant_datasources_v1beta.services.file_uploads_service.client import FileUploadsServiceClient +from google.shopping.merchant_datasources_v1beta.services.file_uploads_service.async_client import FileUploadsServiceAsyncClient + +from google.shopping.merchant_datasources_v1beta.types.datasources import CreateDataSourceRequest +from google.shopping.merchant_datasources_v1beta.types.datasources import DataSource +from google.shopping.merchant_datasources_v1beta.types.datasources import DeleteDataSourceRequest +from google.shopping.merchant_datasources_v1beta.types.datasources import FetchDataSourceRequest +from google.shopping.merchant_datasources_v1beta.types.datasources import GetDataSourceRequest +from google.shopping.merchant_datasources_v1beta.types.datasources import ListDataSourcesRequest +from google.shopping.merchant_datasources_v1beta.types.datasources import ListDataSourcesResponse +from google.shopping.merchant_datasources_v1beta.types.datasources import UpdateDataSourceRequest +from google.shopping.merchant_datasources_v1beta.types.datasourcetypes import DataSourceReference +from google.shopping.merchant_datasources_v1beta.types.datasourcetypes import LocalInventoryDataSource +from google.shopping.merchant_datasources_v1beta.types.datasourcetypes import PrimaryProductDataSource +from google.shopping.merchant_datasources_v1beta.types.datasourcetypes import PromotionDataSource +from google.shopping.merchant_datasources_v1beta.types.datasourcetypes import RegionalInventoryDataSource +from google.shopping.merchant_datasources_v1beta.types.datasourcetypes import SupplementalProductDataSource +from google.shopping.merchant_datasources_v1beta.types.fileinputs import FileInput +from google.shopping.merchant_datasources_v1beta.types.fileuploads import FileUpload +from google.shopping.merchant_datasources_v1beta.types.fileuploads import GetFileUploadRequest + +__all__ = ('DataSourcesServiceClient', + 'DataSourcesServiceAsyncClient', + 'FileUploadsServiceClient', + 'FileUploadsServiceAsyncClient', + 'CreateDataSourceRequest', + 'DataSource', + 'DeleteDataSourceRequest', + 'FetchDataSourceRequest', + 'GetDataSourceRequest', + 'ListDataSourcesRequest', + 'ListDataSourcesResponse', + 'UpdateDataSourceRequest', + 'DataSourceReference', + 'LocalInventoryDataSource', + 'PrimaryProductDataSource', + 'PromotionDataSource', + 'RegionalInventoryDataSource', + 'SupplementalProductDataSource', + 'FileInput', + 'FileUpload', + 'GetFileUploadRequest', +) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources/gapic_version.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-datasources/v1beta/google/shopping/merchant_datasources/py.typed b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources/py.typed new file mode 100644 index 000000000000..035cdd22912c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-shopping-merchant-datasources package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/__init__.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/__init__.py new file mode 100644 index 000000000000..a4cce51e3871 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/__init__.py @@ -0,0 +1,66 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_datasources_v1beta import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.data_sources_service import DataSourcesServiceClient +from .services.data_sources_service import DataSourcesServiceAsyncClient +from .services.file_uploads_service import FileUploadsServiceClient +from .services.file_uploads_service import FileUploadsServiceAsyncClient + +from .types.datasources import CreateDataSourceRequest +from .types.datasources import DataSource +from .types.datasources import DeleteDataSourceRequest +from .types.datasources import FetchDataSourceRequest +from .types.datasources import GetDataSourceRequest +from .types.datasources import ListDataSourcesRequest +from .types.datasources import ListDataSourcesResponse +from .types.datasources import UpdateDataSourceRequest +from .types.datasourcetypes import DataSourceReference +from .types.datasourcetypes import LocalInventoryDataSource +from .types.datasourcetypes import PrimaryProductDataSource +from .types.datasourcetypes import PromotionDataSource +from .types.datasourcetypes import RegionalInventoryDataSource +from .types.datasourcetypes import SupplementalProductDataSource +from .types.fileinputs import FileInput +from .types.fileuploads import FileUpload +from .types.fileuploads import GetFileUploadRequest + +__all__ = ( + 'DataSourcesServiceAsyncClient', + 'FileUploadsServiceAsyncClient', +'CreateDataSourceRequest', +'DataSource', +'DataSourceReference', +'DataSourcesServiceClient', +'DeleteDataSourceRequest', +'FetchDataSourceRequest', +'FileInput', +'FileUpload', +'FileUploadsServiceClient', +'GetDataSourceRequest', +'GetFileUploadRequest', +'ListDataSourcesRequest', +'ListDataSourcesResponse', +'LocalInventoryDataSource', +'PrimaryProductDataSource', +'PromotionDataSource', +'RegionalInventoryDataSource', +'SupplementalProductDataSource', +'UpdateDataSourceRequest', +) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/gapic_metadata.json b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/gapic_metadata.json new file mode 100644 index 000000000000..ec4728128d9c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/gapic_metadata.json @@ -0,0 +1,152 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.shopping.merchant_datasources_v1beta", + "protoPackage": "google.shopping.merchant.datasources.v1beta", + "schema": "1.0", + "services": { + "DataSourcesService": { + "clients": { + "grpc": { + "libraryClient": "DataSourcesServiceClient", + "rpcs": { + "CreateDataSource": { + "methods": [ + "create_data_source" + ] + }, + "DeleteDataSource": { + "methods": [ + "delete_data_source" + ] + }, + "FetchDataSource": { + "methods": [ + "fetch_data_source" + ] + }, + "GetDataSource": { + "methods": [ + "get_data_source" + ] + }, + "ListDataSources": { + "methods": [ + "list_data_sources" + ] + }, + "UpdateDataSource": { + "methods": [ + "update_data_source" + ] + } + } + }, + "grpc-async": { + "libraryClient": "DataSourcesServiceAsyncClient", + "rpcs": { + "CreateDataSource": { + "methods": [ + "create_data_source" + ] + }, + "DeleteDataSource": { + "methods": [ + "delete_data_source" + ] + }, + "FetchDataSource": { + "methods": [ + "fetch_data_source" + ] + }, + "GetDataSource": { + "methods": [ + "get_data_source" + ] + }, + "ListDataSources": { + "methods": [ + "list_data_sources" + ] + }, + "UpdateDataSource": { + "methods": [ + "update_data_source" + ] + } + } + }, + "rest": { + "libraryClient": "DataSourcesServiceClient", + "rpcs": { + "CreateDataSource": { + "methods": [ + "create_data_source" + ] + }, + "DeleteDataSource": { + "methods": [ + "delete_data_source" + ] + }, + "FetchDataSource": { + "methods": [ + "fetch_data_source" + ] + }, + "GetDataSource": { + "methods": [ + "get_data_source" + ] + }, + "ListDataSources": { + "methods": [ + "list_data_sources" + ] + }, + "UpdateDataSource": { + "methods": [ + "update_data_source" + ] + } + } + } + } + }, + "FileUploadsService": { + "clients": { + "grpc": { + "libraryClient": "FileUploadsServiceClient", + "rpcs": { + "GetFileUpload": { + "methods": [ + "get_file_upload" + ] + } + } + }, + "grpc-async": { + "libraryClient": "FileUploadsServiceAsyncClient", + "rpcs": { + "GetFileUpload": { + "methods": [ + "get_file_upload" + ] + } + } + }, + "rest": { + "libraryClient": "FileUploadsServiceClient", + "rpcs": { + "GetFileUpload": { + "methods": [ + "get_file_upload" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/gapic_version.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-datasources/v1beta/google/shopping/merchant_datasources_v1beta/py.typed b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/py.typed new file mode 100644 index 000000000000..035cdd22912c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-shopping-merchant-datasources package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/__init__.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/__init__.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/__init__.py new file mode 100644 index 000000000000..359f46aef4ed --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 DataSourcesServiceClient +from .async_client import DataSourcesServiceAsyncClient + +__all__ = ( + 'DataSourcesServiceClient', + 'DataSourcesServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/async_client.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/async_client.py new file mode 100644 index 000000000000..9b8069d307d4 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/async_client.py @@ -0,0 +1,913 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_datasources_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 + + +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_datasources_v1beta.services.data_sources_service import pagers +from google.shopping.merchant_datasources_v1beta.types import datasources +from google.shopping.merchant_datasources_v1beta.types import datasourcetypes +from google.shopping.merchant_datasources_v1beta.types import fileinputs +from .transports.base import DataSourcesServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import DataSourcesServiceGrpcAsyncIOTransport +from .client import DataSourcesServiceClient + +try: + from google.api_core import client_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 DataSourcesServiceAsyncClient: + """Service to manage primary, supplemental, inventory and other data + sources. See more in the `Merchant + Center `__ help + article. + """ + + _client: DataSourcesServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = DataSourcesServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = DataSourcesServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = DataSourcesServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = DataSourcesServiceClient._DEFAULT_UNIVERSE + + data_source_path = staticmethod(DataSourcesServiceClient.data_source_path) + parse_data_source_path = staticmethod(DataSourcesServiceClient.parse_data_source_path) + common_billing_account_path = staticmethod(DataSourcesServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(DataSourcesServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(DataSourcesServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(DataSourcesServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(DataSourcesServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(DataSourcesServiceClient.parse_common_organization_path) + common_project_path = staticmethod(DataSourcesServiceClient.common_project_path) + parse_common_project_path = staticmethod(DataSourcesServiceClient.parse_common_project_path) + common_location_path = staticmethod(DataSourcesServiceClient.common_location_path) + parse_common_location_path = staticmethod(DataSourcesServiceClient.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: + DataSourcesServiceAsyncClient: The constructed client. + """ + return DataSourcesServiceClient.from_service_account_info.__func__(DataSourcesServiceAsyncClient, 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: + DataSourcesServiceAsyncClient: The constructed client. + """ + return DataSourcesServiceClient.from_service_account_file.__func__(DataSourcesServiceAsyncClient, 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 DataSourcesServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> DataSourcesServiceTransport: + """Returns the transport used by the client instance. + + Returns: + DataSourcesServiceTransport: 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 = DataSourcesServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, DataSourcesServiceTransport, Callable[..., DataSourcesServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the data sources 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,DataSourcesServiceTransport,Callable[..., DataSourcesServiceTransport]]]): + 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 DataSourcesServiceTransport 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 = DataSourcesServiceClient( + 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.datasources_v1beta.DataSourcesServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", + "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.datasources.v1beta.DataSourcesService", + "credentialsType": None, + } + ) + + async def get_data_source(self, + request: Optional[Union[datasources.GetDataSourceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> datasources.DataSource: + r"""Retrieves the data source configuration for the given + account. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_datasources_v1beta + + async def sample_get_data_source(): + # Create a client + client = merchant_datasources_v1beta.DataSourcesServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_datasources_v1beta.GetDataSourceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_data_source(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_datasources_v1beta.types.GetDataSourceRequest, dict]]): + The request object. Request message for the GetDataSource + method. + name (:class:`str`): + Required. The name of the data source to retrieve. + Format: ``accounts/{account}/dataSources/{datasource}`` + + 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_datasources_v1beta.types.DataSource: + The [data source](\ https://support.google.com/merchants/answer/7439058) for + the Merchant Center 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, datasources.GetDataSourceRequest): + request = datasources.GetDataSourceRequest(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_data_source] + + # Certain 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_data_sources(self, + request: Optional[Union[datasources.ListDataSourcesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListDataSourcesAsyncPager: + r"""Lists the configurations for data sources for the + given account. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_datasources_v1beta + + async def sample_list_data_sources(): + # Create a client + client = merchant_datasources_v1beta.DataSourcesServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_datasources_v1beta.ListDataSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_data_sources(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_datasources_v1beta.types.ListDataSourcesRequest, dict]]): + The request object. Request message for the + ListDataSources method. + parent (:class:`str`): + Required. The account to list data sources 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_datasources_v1beta.services.data_sources_service.pagers.ListDataSourcesAsyncPager: + Response message for the + ListDataSources 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, datasources.ListDataSourcesRequest): + request = datasources.ListDataSourcesRequest(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_data_sources] + + # Certain 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.ListDataSourcesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_data_source(self, + request: Optional[Union[datasources.CreateDataSourceRequest, dict]] = None, + *, + parent: Optional[str] = None, + data_source: Optional[datasources.DataSource] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> datasources.DataSource: + r"""Creates the new data source configuration for the + given account. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_datasources_v1beta + + async def sample_create_data_source(): + # Create a client + client = merchant_datasources_v1beta.DataSourcesServiceAsyncClient() + + # Initialize request argument(s) + data_source = merchant_datasources_v1beta.DataSource() + data_source.primary_product_data_source.channel = "PRODUCTS" + data_source.display_name = "display_name_value" + + request = merchant_datasources_v1beta.CreateDataSourceRequest( + parent="parent_value", + data_source=data_source, + ) + + # Make the request + response = await client.create_data_source(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_datasources_v1beta.types.CreateDataSourceRequest, dict]]): + The request object. Request message for the + CreateDataSource method. + parent (:class:`str`): + Required. The account where this data source 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. + data_source (:class:`google.shopping.merchant_datasources_v1beta.types.DataSource`): + Required. The data source to create. + This corresponds to the ``data_source`` 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_datasources_v1beta.types.DataSource: + The [data source](\ https://support.google.com/merchants/answer/7439058) for + the Merchant Center 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. + has_flattened_params = any([parent, data_source]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, datasources.CreateDataSourceRequest): + request = datasources.CreateDataSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if data_source is not None: + request.data_source = data_source + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_data_source] + + # Certain 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_data_source(self, + request: Optional[Union[datasources.UpdateDataSourceRequest, dict]] = None, + *, + data_source: Optional[datasources.DataSource] = 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]]] = (), + ) -> datasources.DataSource: + r"""Updates the existing data source configuration. The + fields that are set in the update mask but not provided + in the resource will be deleted. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_datasources_v1beta + + async def sample_update_data_source(): + # Create a client + client = merchant_datasources_v1beta.DataSourcesServiceAsyncClient() + + # Initialize request argument(s) + data_source = merchant_datasources_v1beta.DataSource() + data_source.primary_product_data_source.channel = "PRODUCTS" + data_source.display_name = "display_name_value" + + request = merchant_datasources_v1beta.UpdateDataSourceRequest( + data_source=data_source, + ) + + # Make the request + response = await client.update_data_source(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_datasources_v1beta.types.UpdateDataSourceRequest, dict]]): + The request object. Request message for the + UpdateDataSource method. + data_source (:class:`google.shopping.merchant_datasources_v1beta.types.DataSource`): + Required. The data source resource to + update. + + This corresponds to the ``data_source`` 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 data source fields to be updated. + + Fields specified in the update mask without a value + specified in the body will be deleted from the data + source. + + Providing special "*" value for full data source + replacement is not supported. + + 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_datasources_v1beta.types.DataSource: + The [data source](\ https://support.google.com/merchants/answer/7439058) for + the Merchant Center 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. + has_flattened_params = any([data_source, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, datasources.UpdateDataSourceRequest): + request = datasources.UpdateDataSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if data_source is not None: + request.data_source = data_source + 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_data_source] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("data_source.name", request.data_source.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_data_source(self, + request: Optional[Union[datasources.DeleteDataSourceRequest, dict]] = None, + *, + name: Optional[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 data source from 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_datasources_v1beta + + async def sample_delete_data_source(): + # Create a client + client = merchant_datasources_v1beta.DataSourcesServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_datasources_v1beta.DeleteDataSourceRequest( + name="name_value", + ) + + # Make the request + await client.delete_data_source(request=request) + + Args: + request (Optional[Union[google.shopping.merchant_datasources_v1beta.types.DeleteDataSourceRequest, dict]]): + The request object. Request message for the + DeleteDataSource method. + name (:class:`str`): + Required. The name of the data source to delete. Format: + ``accounts/{account}/dataSources/{datasource}`` + + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, datasources.DeleteDataSourceRequest): + request = datasources.DeleteDataSourceRequest(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_data_source] + + # Certain 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 fetch_data_source(self, + request: Optional[Union[datasources.FetchDataSourceRequest, 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"""Performs the data fetch immediately (even outside + fetch schedule) on a data source from your Merchant + Center Account. If you need to call this method more + than once per day, you should use the Products service + to update your product data instead. + This method only works on data sources with a file input + set. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_datasources_v1beta + + async def sample_fetch_data_source(): + # Create a client + client = merchant_datasources_v1beta.DataSourcesServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_datasources_v1beta.FetchDataSourceRequest( + name="name_value", + ) + + # Make the request + await client.fetch_data_source(request=request) + + Args: + request (Optional[Union[google.shopping.merchant_datasources_v1beta.types.FetchDataSourceRequest, dict]]): + The request object. Request message for the + FetchDataSource 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, datasources.FetchDataSourceRequest): + request = datasources.FetchDataSourceRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.fetch_data_source] + + # Certain 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) -> "DataSourcesServiceAsyncClient": + 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__) + + +__all__ = ( + "DataSourcesServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/client.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/client.py new file mode 100644 index 000000000000..0c4624333501 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/client.py @@ -0,0 +1,1244 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +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_datasources_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 + +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_datasources_v1beta.services.data_sources_service import pagers +from google.shopping.merchant_datasources_v1beta.types import datasources +from google.shopping.merchant_datasources_v1beta.types import datasourcetypes +from google.shopping.merchant_datasources_v1beta.types import fileinputs +from .transports.base import DataSourcesServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import DataSourcesServiceGrpcTransport +from .transports.grpc_asyncio import DataSourcesServiceGrpcAsyncIOTransport +from .transports.rest import DataSourcesServiceRestTransport + + +class DataSourcesServiceClientMeta(type): + """Metaclass for the DataSourcesService 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[DataSourcesServiceTransport]] + _transport_registry["grpc"] = DataSourcesServiceGrpcTransport + _transport_registry["grpc_asyncio"] = DataSourcesServiceGrpcAsyncIOTransport + _transport_registry["rest"] = DataSourcesServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[DataSourcesServiceTransport]: + """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 DataSourcesServiceClient(metaclass=DataSourcesServiceClientMeta): + """Service to manage primary, supplemental, inventory and other data + sources. See more in the `Merchant + Center `__ help + article. + """ + + @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: + DataSourcesServiceClient: 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: + DataSourcesServiceClient: 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) -> DataSourcesServiceTransport: + """Returns the transport used by the client instance. + + Returns: + DataSourcesServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def data_source_path(account: str,datasource: str,) -> str: + """Returns a fully-qualified data_source string.""" + return "accounts/{account}/dataSources/{datasource}".format(account=account, datasource=datasource, ) + + @staticmethod + def parse_data_source_path(path: str) -> Dict[str,str]: + """Parses a data_source path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/dataSources/(?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 = DataSourcesServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = DataSourcesServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = DataSourcesServiceClient._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 = DataSourcesServiceClient._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 + + @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, DataSourcesServiceTransport, Callable[..., DataSourcesServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the data sources 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,DataSourcesServiceTransport,Callable[..., DataSourcesServiceTransport]]]): + 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 DataSourcesServiceTransport 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 = DataSourcesServiceClient._read_environment_variables() + self._client_cert_source = DataSourcesServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = DataSourcesServiceClient._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, DataSourcesServiceTransport) + if transport_provided: + # transport is a DataSourcesServiceTransport 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(DataSourcesServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + DataSourcesServiceClient._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[DataSourcesServiceTransport], Callable[..., DataSourcesServiceTransport]] = ( + DataSourcesServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., DataSourcesServiceTransport], 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.datasources_v1beta.DataSourcesServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", + "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.datasources.v1beta.DataSourcesService", + "credentialsType": None, + } + ) + + def get_data_source(self, + request: Optional[Union[datasources.GetDataSourceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> datasources.DataSource: + r"""Retrieves the data source configuration for the given + account. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_datasources_v1beta + + def sample_get_data_source(): + # Create a client + client = merchant_datasources_v1beta.DataSourcesServiceClient() + + # Initialize request argument(s) + request = merchant_datasources_v1beta.GetDataSourceRequest( + name="name_value", + ) + + # Make the request + response = client.get_data_source(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_datasources_v1beta.types.GetDataSourceRequest, dict]): + The request object. Request message for the GetDataSource + method. + name (str): + Required. The name of the data source to retrieve. + Format: ``accounts/{account}/dataSources/{datasource}`` + + 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_datasources_v1beta.types.DataSource: + The [data source](\ https://support.google.com/merchants/answer/7439058) for + the Merchant Center 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, datasources.GetDataSourceRequest): + request = datasources.GetDataSourceRequest(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_data_source] + + # Certain 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_data_sources(self, + request: Optional[Union[datasources.ListDataSourcesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListDataSourcesPager: + r"""Lists the configurations for data sources for the + given account. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_datasources_v1beta + + def sample_list_data_sources(): + # Create a client + client = merchant_datasources_v1beta.DataSourcesServiceClient() + + # Initialize request argument(s) + request = merchant_datasources_v1beta.ListDataSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_data_sources(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.shopping.merchant_datasources_v1beta.types.ListDataSourcesRequest, dict]): + The request object. Request message for the + ListDataSources method. + parent (str): + Required. The account to list data sources 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_datasources_v1beta.services.data_sources_service.pagers.ListDataSourcesPager: + Response message for the + ListDataSources 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, datasources.ListDataSourcesRequest): + request = datasources.ListDataSourcesRequest(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_data_sources] + + # Certain 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.ListDataSourcesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_data_source(self, + request: Optional[Union[datasources.CreateDataSourceRequest, dict]] = None, + *, + parent: Optional[str] = None, + data_source: Optional[datasources.DataSource] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> datasources.DataSource: + r"""Creates the new data source configuration for the + given account. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_datasources_v1beta + + def sample_create_data_source(): + # Create a client + client = merchant_datasources_v1beta.DataSourcesServiceClient() + + # Initialize request argument(s) + data_source = merchant_datasources_v1beta.DataSource() + data_source.primary_product_data_source.channel = "PRODUCTS" + data_source.display_name = "display_name_value" + + request = merchant_datasources_v1beta.CreateDataSourceRequest( + parent="parent_value", + data_source=data_source, + ) + + # Make the request + response = client.create_data_source(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_datasources_v1beta.types.CreateDataSourceRequest, dict]): + The request object. Request message for the + CreateDataSource method. + parent (str): + Required. The account where this data source 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. + data_source (google.shopping.merchant_datasources_v1beta.types.DataSource): + Required. The data source to create. + This corresponds to the ``data_source`` 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_datasources_v1beta.types.DataSource: + The [data source](\ https://support.google.com/merchants/answer/7439058) for + the Merchant Center 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. + has_flattened_params = any([parent, data_source]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, datasources.CreateDataSourceRequest): + request = datasources.CreateDataSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if data_source is not None: + request.data_source = data_source + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_data_source] + + # Certain 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_data_source(self, + request: Optional[Union[datasources.UpdateDataSourceRequest, dict]] = None, + *, + data_source: Optional[datasources.DataSource] = 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]]] = (), + ) -> datasources.DataSource: + r"""Updates the existing data source configuration. The + fields that are set in the update mask but not provided + in the resource will be deleted. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_datasources_v1beta + + def sample_update_data_source(): + # Create a client + client = merchant_datasources_v1beta.DataSourcesServiceClient() + + # Initialize request argument(s) + data_source = merchant_datasources_v1beta.DataSource() + data_source.primary_product_data_source.channel = "PRODUCTS" + data_source.display_name = "display_name_value" + + request = merchant_datasources_v1beta.UpdateDataSourceRequest( + data_source=data_source, + ) + + # Make the request + response = client.update_data_source(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_datasources_v1beta.types.UpdateDataSourceRequest, dict]): + The request object. Request message for the + UpdateDataSource method. + data_source (google.shopping.merchant_datasources_v1beta.types.DataSource): + Required. The data source resource to + update. + + This corresponds to the ``data_source`` 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 data source fields to be updated. + + Fields specified in the update mask without a value + specified in the body will be deleted from the data + source. + + Providing special "*" value for full data source + replacement is not supported. + + 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_datasources_v1beta.types.DataSource: + The [data source](\ https://support.google.com/merchants/answer/7439058) for + the Merchant Center 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. + has_flattened_params = any([data_source, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, datasources.UpdateDataSourceRequest): + request = datasources.UpdateDataSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if data_source is not None: + request.data_source = data_source + 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_data_source] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("data_source.name", request.data_source.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_data_source(self, + request: Optional[Union[datasources.DeleteDataSourceRequest, dict]] = None, + *, + name: Optional[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 data source from 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_datasources_v1beta + + def sample_delete_data_source(): + # Create a client + client = merchant_datasources_v1beta.DataSourcesServiceClient() + + # Initialize request argument(s) + request = merchant_datasources_v1beta.DeleteDataSourceRequest( + name="name_value", + ) + + # Make the request + client.delete_data_source(request=request) + + Args: + request (Union[google.shopping.merchant_datasources_v1beta.types.DeleteDataSourceRequest, dict]): + The request object. Request message for the + DeleteDataSource method. + name (str): + Required. The name of the data source to delete. Format: + ``accounts/{account}/dataSources/{datasource}`` + + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, datasources.DeleteDataSourceRequest): + request = datasources.DeleteDataSourceRequest(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_data_source] + + # Certain 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 fetch_data_source(self, + request: Optional[Union[datasources.FetchDataSourceRequest, 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"""Performs the data fetch immediately (even outside + fetch schedule) on a data source from your Merchant + Center Account. If you need to call this method more + than once per day, you should use the Products service + to update your product data instead. + This method only works on data sources with a file input + set. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_datasources_v1beta + + def sample_fetch_data_source(): + # Create a client + client = merchant_datasources_v1beta.DataSourcesServiceClient() + + # Initialize request argument(s) + request = merchant_datasources_v1beta.FetchDataSourceRequest( + name="name_value", + ) + + # Make the request + client.fetch_data_source(request=request) + + Args: + request (Union[google.shopping.merchant_datasources_v1beta.types.FetchDataSourceRequest, dict]): + The request object. Request message for the + FetchDataSource method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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, datasources.FetchDataSourceRequest): + request = datasources.FetchDataSourceRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.fetch_data_source] + + # Certain 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) -> "DataSourcesServiceClient": + 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__) + + +__all__ = ( + "DataSourcesServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/pagers.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/pagers.py new file mode 100644 index 000000000000..47f429541905 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/pagers.py @@ -0,0 +1,166 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_datasources_v1beta.types import datasources + + +class ListDataSourcesPager: + """A pager for iterating through ``list_data_sources`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_datasources_v1beta.types.ListDataSourcesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``data_sources`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListDataSources`` requests and continue to iterate + through the ``data_sources`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_datasources_v1beta.types.ListDataSourcesResponse` + 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[..., datasources.ListDataSourcesResponse], + request: datasources.ListDataSourcesRequest, + response: datasources.ListDataSourcesResponse, + *, + 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_datasources_v1beta.types.ListDataSourcesRequest): + The initial request object. + response (google.shopping.merchant_datasources_v1beta.types.ListDataSourcesResponse): + 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 = datasources.ListDataSourcesRequest(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[datasources.ListDataSourcesResponse]: + 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[datasources.DataSource]: + for page in self.pages: + yield from page.data_sources + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDataSourcesAsyncPager: + """A pager for iterating through ``list_data_sources`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_datasources_v1beta.types.ListDataSourcesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``data_sources`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListDataSources`` requests and continue to iterate + through the ``data_sources`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_datasources_v1beta.types.ListDataSourcesResponse` + 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[datasources.ListDataSourcesResponse]], + request: datasources.ListDataSourcesRequest, + response: datasources.ListDataSourcesResponse, + *, + 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_datasources_v1beta.types.ListDataSourcesRequest): + The initial request object. + response (google.shopping.merchant_datasources_v1beta.types.ListDataSourcesResponse): + 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 = datasources.ListDataSourcesRequest(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[datasources.ListDataSourcesResponse]: + 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[datasources.DataSource]: + async def async_generator(): + async for page in self.pages: + for response in page.data_sources: + 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-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/README.rst new file mode 100644 index 000000000000..bed349bac943 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`DataSourcesServiceTransport` is the ABC for all transports. +- public child `DataSourcesServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `DataSourcesServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseDataSourcesServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `DataSourcesServiceRestTransport` 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-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/__init__.py new file mode 100644 index 000000000000..66c47267dddd --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 DataSourcesServiceTransport +from .grpc import DataSourcesServiceGrpcTransport +from .grpc_asyncio import DataSourcesServiceGrpcAsyncIOTransport +from .rest import DataSourcesServiceRestTransport +from .rest import DataSourcesServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[DataSourcesServiceTransport]] +_transport_registry['grpc'] = DataSourcesServiceGrpcTransport +_transport_registry['grpc_asyncio'] = DataSourcesServiceGrpcAsyncIOTransport +_transport_registry['rest'] = DataSourcesServiceRestTransport + +__all__ = ( + 'DataSourcesServiceTransport', + 'DataSourcesServiceGrpcTransport', + 'DataSourcesServiceGrpcAsyncIOTransport', + 'DataSourcesServiceRestTransport', + 'DataSourcesServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/base.py new file mode 100644 index 000000000000..91843154c040 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/base.py @@ -0,0 +1,225 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_datasources_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 + +from google.protobuf import empty_pb2 # type: ignore +from google.shopping.merchant_datasources_v1beta.types import datasources + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class DataSourcesServiceTransport(abc.ABC): + """Abstract transport class for DataSourcesService.""" + + 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_data_source: gapic_v1.method.wrap_method( + self.get_data_source, + default_timeout=None, + client_info=client_info, + ), + self.list_data_sources: gapic_v1.method.wrap_method( + self.list_data_sources, + default_timeout=None, + client_info=client_info, + ), + self.create_data_source: gapic_v1.method.wrap_method( + self.create_data_source, + default_timeout=None, + client_info=client_info, + ), + self.update_data_source: gapic_v1.method.wrap_method( + self.update_data_source, + default_timeout=None, + client_info=client_info, + ), + self.delete_data_source: gapic_v1.method.wrap_method( + self.delete_data_source, + default_timeout=None, + client_info=client_info, + ), + self.fetch_data_source: gapic_v1.method.wrap_method( + self.fetch_data_source, + 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_data_source(self) -> Callable[ + [datasources.GetDataSourceRequest], + Union[ + datasources.DataSource, + Awaitable[datasources.DataSource] + ]]: + raise NotImplementedError() + + @property + def list_data_sources(self) -> Callable[ + [datasources.ListDataSourcesRequest], + Union[ + datasources.ListDataSourcesResponse, + Awaitable[datasources.ListDataSourcesResponse] + ]]: + raise NotImplementedError() + + @property + def create_data_source(self) -> Callable[ + [datasources.CreateDataSourceRequest], + Union[ + datasources.DataSource, + Awaitable[datasources.DataSource] + ]]: + raise NotImplementedError() + + @property + def update_data_source(self) -> Callable[ + [datasources.UpdateDataSourceRequest], + Union[ + datasources.DataSource, + Awaitable[datasources.DataSource] + ]]: + raise NotImplementedError() + + @property + def delete_data_source(self) -> Callable[ + [datasources.DeleteDataSourceRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def fetch_data_source(self) -> Callable[ + [datasources.FetchDataSourceRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'DataSourcesServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/grpc.py new file mode 100644 index 000000000000..249da51b0608 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/grpc.py @@ -0,0 +1,493 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_datasources_v1beta.types import datasources +from .base import DataSourcesServiceTransport, 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.datasources.v1beta.DataSourcesService", + "rpcName": 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.datasources.v1beta.DataSourcesService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class DataSourcesServiceGrpcTransport(DataSourcesServiceTransport): + """gRPC backend transport for DataSourcesService. + + Service to manage primary, supplemental, inventory and other data + sources. See more in the `Merchant + Center `__ help + article. + + This 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_data_source(self) -> Callable[ + [datasources.GetDataSourceRequest], + datasources.DataSource]: + r"""Return a callable for the get data source method over gRPC. + + Retrieves the data source configuration for the given + account. + + Returns: + Callable[[~.GetDataSourceRequest], + ~.DataSource]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_data_source' not in self._stubs: + self._stubs['get_data_source'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.datasources.v1beta.DataSourcesService/GetDataSource', + request_serializer=datasources.GetDataSourceRequest.serialize, + response_deserializer=datasources.DataSource.deserialize, + ) + return self._stubs['get_data_source'] + + @property + def list_data_sources(self) -> Callable[ + [datasources.ListDataSourcesRequest], + datasources.ListDataSourcesResponse]: + r"""Return a callable for the list data sources method over gRPC. + + Lists the configurations for data sources for the + given account. + + Returns: + Callable[[~.ListDataSourcesRequest], + ~.ListDataSourcesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_data_sources' not in self._stubs: + self._stubs['list_data_sources'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.datasources.v1beta.DataSourcesService/ListDataSources', + request_serializer=datasources.ListDataSourcesRequest.serialize, + response_deserializer=datasources.ListDataSourcesResponse.deserialize, + ) + return self._stubs['list_data_sources'] + + @property + def create_data_source(self) -> Callable[ + [datasources.CreateDataSourceRequest], + datasources.DataSource]: + r"""Return a callable for the create data source method over gRPC. + + Creates the new data source configuration for the + given account. + + Returns: + Callable[[~.CreateDataSourceRequest], + ~.DataSource]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_data_source' not in self._stubs: + self._stubs['create_data_source'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.datasources.v1beta.DataSourcesService/CreateDataSource', + request_serializer=datasources.CreateDataSourceRequest.serialize, + response_deserializer=datasources.DataSource.deserialize, + ) + return self._stubs['create_data_source'] + + @property + def update_data_source(self) -> Callable[ + [datasources.UpdateDataSourceRequest], + datasources.DataSource]: + r"""Return a callable for the update data source method over gRPC. + + Updates the existing data source configuration. The + fields that are set in the update mask but not provided + in the resource will be deleted. + + Returns: + Callable[[~.UpdateDataSourceRequest], + ~.DataSource]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_data_source' not in self._stubs: + self._stubs['update_data_source'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.datasources.v1beta.DataSourcesService/UpdateDataSource', + request_serializer=datasources.UpdateDataSourceRequest.serialize, + response_deserializer=datasources.DataSource.deserialize, + ) + return self._stubs['update_data_source'] + + @property + def delete_data_source(self) -> Callable[ + [datasources.DeleteDataSourceRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete data source method over gRPC. + + Deletes a data source from your Merchant Center + account. + + Returns: + Callable[[~.DeleteDataSourceRequest], + ~.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_data_source' not in self._stubs: + self._stubs['delete_data_source'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.datasources.v1beta.DataSourcesService/DeleteDataSource', + request_serializer=datasources.DeleteDataSourceRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_data_source'] + + @property + def fetch_data_source(self) -> Callable[ + [datasources.FetchDataSourceRequest], + empty_pb2.Empty]: + r"""Return a callable for the fetch data source method over gRPC. + + Performs the data fetch immediately (even outside + fetch schedule) on a data source from your Merchant + Center Account. If you need to call this method more + than once per day, you should use the Products service + to update your product data instead. + This method only works on data sources with a file input + set. + + Returns: + Callable[[~.FetchDataSourceRequest], + ~.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 'fetch_data_source' not in self._stubs: + self._stubs['fetch_data_source'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.datasources.v1beta.DataSourcesService/FetchDataSource', + request_serializer=datasources.FetchDataSourceRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['fetch_data_source'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'DataSourcesServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..5af9b5cb8e6c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/grpc_asyncio.py @@ -0,0 +1,538 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_datasources_v1beta.types import datasources +from .base import DataSourcesServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import DataSourcesServiceGrpcTransport + +try: + from google.api_core import client_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.datasources.v1beta.DataSourcesService", + "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.datasources.v1beta.DataSourcesService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class DataSourcesServiceGrpcAsyncIOTransport(DataSourcesServiceTransport): + """gRPC AsyncIO backend transport for DataSourcesService. + + Service to manage primary, supplemental, inventory and other data + sources. See more in the `Merchant + Center `__ help + article. + + This 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_data_source(self) -> Callable[ + [datasources.GetDataSourceRequest], + Awaitable[datasources.DataSource]]: + r"""Return a callable for the get data source method over gRPC. + + Retrieves the data source configuration for the given + account. + + Returns: + Callable[[~.GetDataSourceRequest], + Awaitable[~.DataSource]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_data_source' not in self._stubs: + self._stubs['get_data_source'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.datasources.v1beta.DataSourcesService/GetDataSource', + request_serializer=datasources.GetDataSourceRequest.serialize, + response_deserializer=datasources.DataSource.deserialize, + ) + return self._stubs['get_data_source'] + + @property + def list_data_sources(self) -> Callable[ + [datasources.ListDataSourcesRequest], + Awaitable[datasources.ListDataSourcesResponse]]: + r"""Return a callable for the list data sources method over gRPC. + + Lists the configurations for data sources for the + given account. + + Returns: + Callable[[~.ListDataSourcesRequest], + Awaitable[~.ListDataSourcesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_data_sources' not in self._stubs: + self._stubs['list_data_sources'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.datasources.v1beta.DataSourcesService/ListDataSources', + request_serializer=datasources.ListDataSourcesRequest.serialize, + response_deserializer=datasources.ListDataSourcesResponse.deserialize, + ) + return self._stubs['list_data_sources'] + + @property + def create_data_source(self) -> Callable[ + [datasources.CreateDataSourceRequest], + Awaitable[datasources.DataSource]]: + r"""Return a callable for the create data source method over gRPC. + + Creates the new data source configuration for the + given account. + + Returns: + Callable[[~.CreateDataSourceRequest], + Awaitable[~.DataSource]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_data_source' not in self._stubs: + self._stubs['create_data_source'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.datasources.v1beta.DataSourcesService/CreateDataSource', + request_serializer=datasources.CreateDataSourceRequest.serialize, + response_deserializer=datasources.DataSource.deserialize, + ) + return self._stubs['create_data_source'] + + @property + def update_data_source(self) -> Callable[ + [datasources.UpdateDataSourceRequest], + Awaitable[datasources.DataSource]]: + r"""Return a callable for the update data source method over gRPC. + + Updates the existing data source configuration. The + fields that are set in the update mask but not provided + in the resource will be deleted. + + Returns: + Callable[[~.UpdateDataSourceRequest], + Awaitable[~.DataSource]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_data_source' not in self._stubs: + self._stubs['update_data_source'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.datasources.v1beta.DataSourcesService/UpdateDataSource', + request_serializer=datasources.UpdateDataSourceRequest.serialize, + response_deserializer=datasources.DataSource.deserialize, + ) + return self._stubs['update_data_source'] + + @property + def delete_data_source(self) -> Callable[ + [datasources.DeleteDataSourceRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete data source method over gRPC. + + Deletes a data source from your Merchant Center + account. + + Returns: + Callable[[~.DeleteDataSourceRequest], + 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_data_source' not in self._stubs: + self._stubs['delete_data_source'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.datasources.v1beta.DataSourcesService/DeleteDataSource', + request_serializer=datasources.DeleteDataSourceRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_data_source'] + + @property + def fetch_data_source(self) -> Callable[ + [datasources.FetchDataSourceRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the fetch data source method over gRPC. + + Performs the data fetch immediately (even outside + fetch schedule) on a data source from your Merchant + Center Account. If you need to call this method more + than once per day, you should use the Products service + to update your product data instead. + This method only works on data sources with a file input + set. + + Returns: + Callable[[~.FetchDataSourceRequest], + 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 'fetch_data_source' not in self._stubs: + self._stubs['fetch_data_source'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.datasources.v1beta.DataSourcesService/FetchDataSource', + request_serializer=datasources.FetchDataSourceRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['fetch_data_source'] + + 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_data_source: self._wrap_method( + self.get_data_source, + default_timeout=None, + client_info=client_info, + ), + self.list_data_sources: self._wrap_method( + self.list_data_sources, + default_timeout=None, + client_info=client_info, + ), + self.create_data_source: self._wrap_method( + self.create_data_source, + default_timeout=None, + client_info=client_info, + ), + self.update_data_source: self._wrap_method( + self.update_data_source, + default_timeout=None, + client_info=client_info, + ), + self.delete_data_source: self._wrap_method( + self.delete_data_source, + default_timeout=None, + client_info=client_info, + ), + self.fetch_data_source: self._wrap_method( + self.fetch_data_source, + 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__ = ( + 'DataSourcesServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/rest.py new file mode 100644 index 000000000000..bde98ec2e52e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/rest.py @@ -0,0 +1,1016 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +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_datasources_v1beta.types import datasources + + +from .rest_base import _BaseDataSourcesServiceRestTransport +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}", +) + + +class DataSourcesServiceRestInterceptor: + """Interceptor for DataSourcesService. + + 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 DataSourcesServiceRestTransport. + + .. code-block:: python + class MyCustomDataSourcesServiceInterceptor(DataSourcesServiceRestInterceptor): + def pre_create_data_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_data_source(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_data_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_fetch_data_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_data_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_data_source(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_data_sources(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_data_sources(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_data_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_data_source(self, response): + logging.log(f"Received response: {response}") + return response + + transport = DataSourcesServiceRestTransport(interceptor=MyCustomDataSourcesServiceInterceptor()) + client = DataSourcesServiceClient(transport=transport) + + + """ + def pre_create_data_source(self, request: datasources.CreateDataSourceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[datasources.CreateDataSourceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_data_source + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataSourcesService server. + """ + return request, metadata + + def post_create_data_source(self, response: datasources.DataSource) -> datasources.DataSource: + """Post-rpc interceptor for create_data_source + + Override in a subclass to manipulate the response + after it is returned by the DataSourcesService server but before + it is returned to user code. + """ + return response + + def pre_delete_data_source(self, request: datasources.DeleteDataSourceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[datasources.DeleteDataSourceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_data_source + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataSourcesService server. + """ + return request, metadata + + def pre_fetch_data_source(self, request: datasources.FetchDataSourceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[datasources.FetchDataSourceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for fetch_data_source + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataSourcesService server. + """ + return request, metadata + + def pre_get_data_source(self, request: datasources.GetDataSourceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[datasources.GetDataSourceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_data_source + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataSourcesService server. + """ + return request, metadata + + def post_get_data_source(self, response: datasources.DataSource) -> datasources.DataSource: + """Post-rpc interceptor for get_data_source + + Override in a subclass to manipulate the response + after it is returned by the DataSourcesService server but before + it is returned to user code. + """ + return response + + def pre_list_data_sources(self, request: datasources.ListDataSourcesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[datasources.ListDataSourcesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_data_sources + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataSourcesService server. + """ + return request, metadata + + def post_list_data_sources(self, response: datasources.ListDataSourcesResponse) -> datasources.ListDataSourcesResponse: + """Post-rpc interceptor for list_data_sources + + Override in a subclass to manipulate the response + after it is returned by the DataSourcesService server but before + it is returned to user code. + """ + return response + + def pre_update_data_source(self, request: datasources.UpdateDataSourceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[datasources.UpdateDataSourceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_data_source + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataSourcesService server. + """ + return request, metadata + + def post_update_data_source(self, response: datasources.DataSource) -> datasources.DataSource: + """Post-rpc interceptor for update_data_source + + Override in a subclass to manipulate the response + after it is returned by the DataSourcesService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class DataSourcesServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: DataSourcesServiceRestInterceptor + + +class DataSourcesServiceRestTransport(_BaseDataSourcesServiceRestTransport): + """REST backend synchronous transport for DataSourcesService. + + Service to manage primary, supplemental, inventory and other data + sources. See more in the `Merchant + Center `__ help + article. + + This 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[DataSourcesServiceRestInterceptor] = 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 DataSourcesServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateDataSource(_BaseDataSourcesServiceRestTransport._BaseCreateDataSource, DataSourcesServiceRestStub): + def __hash__(self): + return hash("DataSourcesServiceRestTransport.CreateDataSource") + + @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: datasources.CreateDataSourceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> datasources.DataSource: + r"""Call the create data source method over HTTP. + + Args: + request (~.datasources.CreateDataSourceRequest): + The request object. Request message for the + CreateDataSource method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.datasources.DataSource: + The `data + source `__ + for the Merchant Center account. + + """ + + http_options = _BaseDataSourcesServiceRestTransport._BaseCreateDataSource._get_http_options() + + request, metadata = self._interceptor.pre_create_data_source(request, metadata) + transcoded_request = _BaseDataSourcesServiceRestTransport._BaseCreateDataSource._get_transcoded_request(http_options, request) + + body = _BaseDataSourcesServiceRestTransport._BaseCreateDataSource._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseDataSourcesServiceRestTransport._BaseCreateDataSource._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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.datasources_v1beta.DataSourcesServiceClient.CreateDataSource", + extra = { + "serviceName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", + "rpcName": "CreateDataSource", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DataSourcesServiceRestTransport._CreateDataSource._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 = datasources.DataSource() + pb_resp = datasources.DataSource.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_data_source(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = datasources.DataSource.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.datasources_v1beta.DataSourcesServiceClient.create_data_source", + extra = { + "serviceName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", + "rpcName": "CreateDataSource", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteDataSource(_BaseDataSourcesServiceRestTransport._BaseDeleteDataSource, DataSourcesServiceRestStub): + def __hash__(self): + return hash("DataSourcesServiceRestTransport.DeleteDataSource") + + @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: datasources.DeleteDataSourceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): + r"""Call the delete data source method over HTTP. + + Args: + request (~.datasources.DeleteDataSourceRequest): + The request object. Request message for the + DeleteDataSource method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 = _BaseDataSourcesServiceRestTransport._BaseDeleteDataSource._get_http_options() + + request, metadata = self._interceptor.pre_delete_data_source(request, metadata) + transcoded_request = _BaseDataSourcesServiceRestTransport._BaseDeleteDataSource._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseDataSourcesServiceRestTransport._BaseDeleteDataSource._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(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.datasources_v1beta.DataSourcesServiceClient.DeleteDataSource", + extra = { + "serviceName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", + "rpcName": "DeleteDataSource", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DataSourcesServiceRestTransport._DeleteDataSource._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 _FetchDataSource(_BaseDataSourcesServiceRestTransport._BaseFetchDataSource, DataSourcesServiceRestStub): + def __hash__(self): + return hash("DataSourcesServiceRestTransport.FetchDataSource") + + @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: datasources.FetchDataSourceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): + r"""Call the fetch data source method over HTTP. + + Args: + request (~.datasources.FetchDataSourceRequest): + The request object. Request message for the + FetchDataSource method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 = _BaseDataSourcesServiceRestTransport._BaseFetchDataSource._get_http_options() + + request, metadata = self._interceptor.pre_fetch_data_source(request, metadata) + transcoded_request = _BaseDataSourcesServiceRestTransport._BaseFetchDataSource._get_transcoded_request(http_options, request) + + body = _BaseDataSourcesServiceRestTransport._BaseFetchDataSource._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseDataSourcesServiceRestTransport._BaseFetchDataSource._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(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.datasources_v1beta.DataSourcesServiceClient.FetchDataSource", + extra = { + "serviceName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", + "rpcName": "FetchDataSource", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DataSourcesServiceRestTransport._FetchDataSource._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _GetDataSource(_BaseDataSourcesServiceRestTransport._BaseGetDataSource, DataSourcesServiceRestStub): + def __hash__(self): + return hash("DataSourcesServiceRestTransport.GetDataSource") + + @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: datasources.GetDataSourceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> datasources.DataSource: + r"""Call the get data source method over HTTP. + + Args: + request (~.datasources.GetDataSourceRequest): + The request object. Request message for the GetDataSource + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.datasources.DataSource: + The `data + source `__ + for the Merchant Center account. + + """ + + http_options = _BaseDataSourcesServiceRestTransport._BaseGetDataSource._get_http_options() + + request, metadata = self._interceptor.pre_get_data_source(request, metadata) + transcoded_request = _BaseDataSourcesServiceRestTransport._BaseGetDataSource._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseDataSourcesServiceRestTransport._BaseGetDataSource._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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.datasources_v1beta.DataSourcesServiceClient.GetDataSource", + extra = { + "serviceName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", + "rpcName": "GetDataSource", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DataSourcesServiceRestTransport._GetDataSource._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 = datasources.DataSource() + pb_resp = datasources.DataSource.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_data_source(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = datasources.DataSource.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.datasources_v1beta.DataSourcesServiceClient.get_data_source", + extra = { + "serviceName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", + "rpcName": "GetDataSource", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListDataSources(_BaseDataSourcesServiceRestTransport._BaseListDataSources, DataSourcesServiceRestStub): + def __hash__(self): + return hash("DataSourcesServiceRestTransport.ListDataSources") + + @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: datasources.ListDataSourcesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> datasources.ListDataSourcesResponse: + r"""Call the list data sources method over HTTP. + + Args: + request (~.datasources.ListDataSourcesRequest): + The request object. Request message for the + ListDataSources method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.datasources.ListDataSourcesResponse: + Response message for the + ListDataSources method. + + """ + + http_options = _BaseDataSourcesServiceRestTransport._BaseListDataSources._get_http_options() + + request, metadata = self._interceptor.pre_list_data_sources(request, metadata) + transcoded_request = _BaseDataSourcesServiceRestTransport._BaseListDataSources._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseDataSourcesServiceRestTransport._BaseListDataSources._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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.datasources_v1beta.DataSourcesServiceClient.ListDataSources", + extra = { + "serviceName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", + "rpcName": "ListDataSources", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DataSourcesServiceRestTransport._ListDataSources._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 = datasources.ListDataSourcesResponse() + pb_resp = datasources.ListDataSourcesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_data_sources(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = datasources.ListDataSourcesResponse.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.datasources_v1beta.DataSourcesServiceClient.list_data_sources", + extra = { + "serviceName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", + "rpcName": "ListDataSources", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateDataSource(_BaseDataSourcesServiceRestTransport._BaseUpdateDataSource, DataSourcesServiceRestStub): + def __hash__(self): + return hash("DataSourcesServiceRestTransport.UpdateDataSource") + + @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: datasources.UpdateDataSourceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> datasources.DataSource: + r"""Call the update data source method over HTTP. + + Args: + request (~.datasources.UpdateDataSourceRequest): + The request object. Request message for the + UpdateDataSource method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.datasources.DataSource: + The `data + source `__ + for the Merchant Center account. + + """ + + http_options = _BaseDataSourcesServiceRestTransport._BaseUpdateDataSource._get_http_options() + + request, metadata = self._interceptor.pre_update_data_source(request, metadata) + transcoded_request = _BaseDataSourcesServiceRestTransport._BaseUpdateDataSource._get_transcoded_request(http_options, request) + + body = _BaseDataSourcesServiceRestTransport._BaseUpdateDataSource._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseDataSourcesServiceRestTransport._BaseUpdateDataSource._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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.datasources_v1beta.DataSourcesServiceClient.UpdateDataSource", + extra = { + "serviceName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", + "rpcName": "UpdateDataSource", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DataSourcesServiceRestTransport._UpdateDataSource._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 = datasources.DataSource() + pb_resp = datasources.DataSource.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_data_source(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = datasources.DataSource.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.datasources_v1beta.DataSourcesServiceClient.update_data_source", + extra = { + "serviceName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", + "rpcName": "UpdateDataSource", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_data_source(self) -> Callable[ + [datasources.CreateDataSourceRequest], + datasources.DataSource]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateDataSource(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_data_source(self) -> Callable[ + [datasources.DeleteDataSourceRequest], + 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._DeleteDataSource(self._session, self._host, self._interceptor) # type: ignore + + @property + def fetch_data_source(self) -> Callable[ + [datasources.FetchDataSourceRequest], + 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._FetchDataSource(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_data_source(self) -> Callable[ + [datasources.GetDataSourceRequest], + datasources.DataSource]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetDataSource(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_data_sources(self) -> Callable[ + [datasources.ListDataSourcesRequest], + datasources.ListDataSourcesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListDataSources(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_data_source(self) -> Callable[ + [datasources.UpdateDataSourceRequest], + datasources.DataSource]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateDataSource(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'DataSourcesServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/rest_base.py new file mode 100644 index 000000000000..241c9ea5e7aa --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/rest_base.py @@ -0,0 +1,344 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 DataSourcesServiceTransport, 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_datasources_v1beta.types import datasources + + +class _BaseDataSourcesServiceRestTransport(DataSourcesServiceTransport): + """Base REST backend transport for DataSourcesService. + + 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 _BaseCreateDataSource: + 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': '/datasources/v1beta/{parent=accounts/*}/dataSources', + 'body': 'data_source', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = datasources.CreateDataSourceRequest.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(_BaseDataSourcesServiceRestTransport._BaseCreateDataSource._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteDataSource: + 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': '/datasources/v1beta/{name=accounts/*/dataSources/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = datasources.DeleteDataSourceRequest.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(_BaseDataSourcesServiceRestTransport._BaseDeleteDataSource._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseFetchDataSource: + 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': '/datasources/v1beta/{name=accounts/*/dataSources/*}:fetch', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = datasources.FetchDataSourceRequest.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(_BaseDataSourcesServiceRestTransport._BaseFetchDataSource._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetDataSource: + 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': '/datasources/v1beta/{name=accounts/*/dataSources/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = datasources.GetDataSourceRequest.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(_BaseDataSourcesServiceRestTransport._BaseGetDataSource._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListDataSources: + 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': '/datasources/v1beta/{parent=accounts/*}/dataSources', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = datasources.ListDataSourcesRequest.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(_BaseDataSourcesServiceRestTransport._BaseListDataSources._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateDataSource: + 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': '/datasources/v1beta/{data_source.name=accounts/*/dataSources/*}', + 'body': 'data_source', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = datasources.UpdateDataSourceRequest.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(_BaseDataSourcesServiceRestTransport._BaseUpdateDataSource._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseDataSourcesServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/__init__.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/__init__.py new file mode 100644 index 000000000000..654b958c5a64 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 FileUploadsServiceClient +from .async_client import FileUploadsServiceAsyncClient + +__all__ = ( + 'FileUploadsServiceClient', + 'FileUploadsServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/async_client.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/async_client.py new file mode 100644 index 000000000000..acdb53d2490c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/async_client.py @@ -0,0 +1,372 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_datasources_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 + + +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 timestamp_pb2 # type: ignore +from google.shopping.merchant_datasources_v1beta.types import fileuploads +from .transports.base import FileUploadsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import FileUploadsServiceGrpcAsyncIOTransport +from .client import FileUploadsServiceClient + +try: + from google.api_core import client_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 FileUploadsServiceAsyncClient: + """Service to manage data source file uploads.""" + + _client: FileUploadsServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = FileUploadsServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = FileUploadsServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = FileUploadsServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = FileUploadsServiceClient._DEFAULT_UNIVERSE + + file_upload_path = staticmethod(FileUploadsServiceClient.file_upload_path) + parse_file_upload_path = staticmethod(FileUploadsServiceClient.parse_file_upload_path) + common_billing_account_path = staticmethod(FileUploadsServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(FileUploadsServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(FileUploadsServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(FileUploadsServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(FileUploadsServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(FileUploadsServiceClient.parse_common_organization_path) + common_project_path = staticmethod(FileUploadsServiceClient.common_project_path) + parse_common_project_path = staticmethod(FileUploadsServiceClient.parse_common_project_path) + common_location_path = staticmethod(FileUploadsServiceClient.common_location_path) + parse_common_location_path = staticmethod(FileUploadsServiceClient.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: + FileUploadsServiceAsyncClient: The constructed client. + """ + return FileUploadsServiceClient.from_service_account_info.__func__(FileUploadsServiceAsyncClient, 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: + FileUploadsServiceAsyncClient: The constructed client. + """ + return FileUploadsServiceClient.from_service_account_file.__func__(FileUploadsServiceAsyncClient, 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 FileUploadsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> FileUploadsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + FileUploadsServiceTransport: 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 = FileUploadsServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, FileUploadsServiceTransport, Callable[..., FileUploadsServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the file uploads 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,FileUploadsServiceTransport,Callable[..., FileUploadsServiceTransport]]]): + 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 FileUploadsServiceTransport 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 = FileUploadsServiceClient( + 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.datasources_v1beta.FileUploadsServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.datasources.v1beta.FileUploadsService", + "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.datasources.v1beta.FileUploadsService", + "credentialsType": None, + } + ) + + async def get_file_upload(self, + request: Optional[Union[fileuploads.GetFileUploadRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> fileuploads.FileUpload: + r"""Gets the latest data source file upload. Only the ``latest`` + alias is accepted for a file upload. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_datasources_v1beta + + async def sample_get_file_upload(): + # Create a client + client = merchant_datasources_v1beta.FileUploadsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_datasources_v1beta.GetFileUploadRequest( + name="name_value", + ) + + # Make the request + response = await client.get_file_upload(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_datasources_v1beta.types.GetFileUploadRequest, dict]]): + The request object. Request message for the + GetFileUploadRequest method. + name (:class:`str`): + Required. The name of the data source file upload to + retrieve. Format: + ``accounts/{account}/dataSources/{datasource}/fileUploads/latest`` + + 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_datasources_v1beta.types.FileUpload: + The file upload of a specific data + source, that is, the result of the + retrieval of the data source at a + certain timestamp computed + asynchronously when the data source + processing is finished. Only applicable + to file data sources. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, fileuploads.GetFileUploadRequest): + request = fileuploads.GetFileUploadRequest(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_file_upload] + + # Certain 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) -> "FileUploadsServiceAsyncClient": + 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__) + + +__all__ = ( + "FileUploadsServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/client.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/client.py new file mode 100644 index 000000000000..a4913f7434e6 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/client.py @@ -0,0 +1,707 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +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_datasources_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 + +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 timestamp_pb2 # type: ignore +from google.shopping.merchant_datasources_v1beta.types import fileuploads +from .transports.base import FileUploadsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import FileUploadsServiceGrpcTransport +from .transports.grpc_asyncio import FileUploadsServiceGrpcAsyncIOTransport +from .transports.rest import FileUploadsServiceRestTransport + + +class FileUploadsServiceClientMeta(type): + """Metaclass for the FileUploadsService 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[FileUploadsServiceTransport]] + _transport_registry["grpc"] = FileUploadsServiceGrpcTransport + _transport_registry["grpc_asyncio"] = FileUploadsServiceGrpcAsyncIOTransport + _transport_registry["rest"] = FileUploadsServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[FileUploadsServiceTransport]: + """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 FileUploadsServiceClient(metaclass=FileUploadsServiceClientMeta): + """Service to manage data source file uploads.""" + + @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: + FileUploadsServiceClient: 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: + FileUploadsServiceClient: 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) -> FileUploadsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + FileUploadsServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def file_upload_path(account: str,datasource: str,fileupload: str,) -> str: + """Returns a fully-qualified file_upload string.""" + return "accounts/{account}/dataSources/{datasource}/fileUploads/{fileupload}".format(account=account, datasource=datasource, fileupload=fileupload, ) + + @staticmethod + def parse_file_upload_path(path: str) -> Dict[str,str]: + """Parses a file_upload path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/dataSources/(?P.+?)/fileUploads/(?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 = FileUploadsServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = FileUploadsServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = FileUploadsServiceClient._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 = FileUploadsServiceClient._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 + + @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, FileUploadsServiceTransport, Callable[..., FileUploadsServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the file uploads 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,FileUploadsServiceTransport,Callable[..., FileUploadsServiceTransport]]]): + 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 FileUploadsServiceTransport 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 = FileUploadsServiceClient._read_environment_variables() + self._client_cert_source = FileUploadsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = FileUploadsServiceClient._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, FileUploadsServiceTransport) + if transport_provided: + # transport is a FileUploadsServiceTransport 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(FileUploadsServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + FileUploadsServiceClient._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[FileUploadsServiceTransport], Callable[..., FileUploadsServiceTransport]] = ( + FileUploadsServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., FileUploadsServiceTransport], 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.datasources_v1beta.FileUploadsServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.datasources.v1beta.FileUploadsService", + "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.datasources.v1beta.FileUploadsService", + "credentialsType": None, + } + ) + + def get_file_upload(self, + request: Optional[Union[fileuploads.GetFileUploadRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> fileuploads.FileUpload: + r"""Gets the latest data source file upload. Only the ``latest`` + alias is accepted for a file upload. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_datasources_v1beta + + def sample_get_file_upload(): + # Create a client + client = merchant_datasources_v1beta.FileUploadsServiceClient() + + # Initialize request argument(s) + request = merchant_datasources_v1beta.GetFileUploadRequest( + name="name_value", + ) + + # Make the request + response = client.get_file_upload(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_datasources_v1beta.types.GetFileUploadRequest, dict]): + The request object. Request message for the + GetFileUploadRequest method. + name (str): + Required. The name of the data source file upload to + retrieve. Format: + ``accounts/{account}/dataSources/{datasource}/fileUploads/latest`` + + 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_datasources_v1beta.types.FileUpload: + The file upload of a specific data + source, that is, the result of the + retrieval of the data source at a + certain timestamp computed + asynchronously when the data source + processing is finished. Only applicable + to file data sources. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, fileuploads.GetFileUploadRequest): + request = fileuploads.GetFileUploadRequest(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_file_upload] + + # Certain 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) -> "FileUploadsServiceClient": + 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__) + + +__all__ = ( + "FileUploadsServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/README.rst new file mode 100644 index 000000000000..950ff4a21abd --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`FileUploadsServiceTransport` is the ABC for all transports. +- public child `FileUploadsServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `FileUploadsServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseFileUploadsServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `FileUploadsServiceRestTransport` 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-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/__init__.py new file mode 100644 index 000000000000..a25a3f24c7be --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 FileUploadsServiceTransport +from .grpc import FileUploadsServiceGrpcTransport +from .grpc_asyncio import FileUploadsServiceGrpcAsyncIOTransport +from .rest import FileUploadsServiceRestTransport +from .rest import FileUploadsServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[FileUploadsServiceTransport]] +_transport_registry['grpc'] = FileUploadsServiceGrpcTransport +_transport_registry['grpc_asyncio'] = FileUploadsServiceGrpcAsyncIOTransport +_transport_registry['rest'] = FileUploadsServiceRestTransport + +__all__ = ( + 'FileUploadsServiceTransport', + 'FileUploadsServiceGrpcTransport', + 'FileUploadsServiceGrpcAsyncIOTransport', + 'FileUploadsServiceRestTransport', + 'FileUploadsServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/base.py new file mode 100644 index 000000000000..f2ec31cc2944 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/base.py @@ -0,0 +1,154 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_datasources_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 + +from google.shopping.merchant_datasources_v1beta.types import fileuploads + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class FileUploadsServiceTransport(abc.ABC): + """Abstract transport class for FileUploadsService.""" + + 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_file_upload: gapic_v1.method.wrap_method( + self.get_file_upload, + 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_file_upload(self) -> Callable[ + [fileuploads.GetFileUploadRequest], + Union[ + fileuploads.FileUpload, + Awaitable[fileuploads.FileUpload] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'FileUploadsServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/grpc.py new file mode 100644 index 000000000000..9b117a33dc20 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/grpc.py @@ -0,0 +1,348 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_datasources_v1beta.types import fileuploads +from .base import FileUploadsServiceTransport, 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.datasources.v1beta.FileUploadsService", + "rpcName": 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.datasources.v1beta.FileUploadsService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class FileUploadsServiceGrpcTransport(FileUploadsServiceTransport): + """gRPC backend transport for FileUploadsService. + + Service to manage data source file uploads. + + This 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_file_upload(self) -> Callable[ + [fileuploads.GetFileUploadRequest], + fileuploads.FileUpload]: + r"""Return a callable for the get file upload method over gRPC. + + Gets the latest data source file upload. Only the ``latest`` + alias is accepted for a file upload. + + Returns: + Callable[[~.GetFileUploadRequest], + ~.FileUpload]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_file_upload' not in self._stubs: + self._stubs['get_file_upload'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.datasources.v1beta.FileUploadsService/GetFileUpload', + request_serializer=fileuploads.GetFileUploadRequest.serialize, + response_deserializer=fileuploads.FileUpload.deserialize, + ) + return self._stubs['get_file_upload'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'FileUploadsServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..3b0b5d4fab73 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/grpc_asyncio.py @@ -0,0 +1,368 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_datasources_v1beta.types import fileuploads +from .base import FileUploadsServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import FileUploadsServiceGrpcTransport + +try: + from google.api_core import client_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.datasources.v1beta.FileUploadsService", + "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.datasources.v1beta.FileUploadsService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class FileUploadsServiceGrpcAsyncIOTransport(FileUploadsServiceTransport): + """gRPC AsyncIO backend transport for FileUploadsService. + + Service to manage data source file uploads. + + This 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_file_upload(self) -> Callable[ + [fileuploads.GetFileUploadRequest], + Awaitable[fileuploads.FileUpload]]: + r"""Return a callable for the get file upload method over gRPC. + + Gets the latest data source file upload. Only the ``latest`` + alias is accepted for a file upload. + + Returns: + Callable[[~.GetFileUploadRequest], + Awaitable[~.FileUpload]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_file_upload' not in self._stubs: + self._stubs['get_file_upload'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.datasources.v1beta.FileUploadsService/GetFileUpload', + request_serializer=fileuploads.GetFileUploadRequest.serialize, + response_deserializer=fileuploads.FileUpload.deserialize, + ) + return self._stubs['get_file_upload'] + + 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_file_upload: self._wrap_method( + self.get_file_upload, + 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__ = ( + 'FileUploadsServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/rest.py new file mode 100644 index 000000000000..88985daefcd9 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/rest.py @@ -0,0 +1,334 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +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_datasources_v1beta.types import fileuploads + + +from .rest_base import _BaseFileUploadsServiceRestTransport +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}", +) + + +class FileUploadsServiceRestInterceptor: + """Interceptor for FileUploadsService. + + 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 FileUploadsServiceRestTransport. + + .. code-block:: python + class MyCustomFileUploadsServiceInterceptor(FileUploadsServiceRestInterceptor): + def pre_get_file_upload(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_file_upload(self, response): + logging.log(f"Received response: {response}") + return response + + transport = FileUploadsServiceRestTransport(interceptor=MyCustomFileUploadsServiceInterceptor()) + client = FileUploadsServiceClient(transport=transport) + + + """ + def pre_get_file_upload(self, request: fileuploads.GetFileUploadRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[fileuploads.GetFileUploadRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_file_upload + + Override in a subclass to manipulate the request or metadata + before they are sent to the FileUploadsService server. + """ + return request, metadata + + def post_get_file_upload(self, response: fileuploads.FileUpload) -> fileuploads.FileUpload: + """Post-rpc interceptor for get_file_upload + + Override in a subclass to manipulate the response + after it is returned by the FileUploadsService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class FileUploadsServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: FileUploadsServiceRestInterceptor + + +class FileUploadsServiceRestTransport(_BaseFileUploadsServiceRestTransport): + """REST backend synchronous transport for FileUploadsService. + + Service to manage data source file uploads. + + This 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[FileUploadsServiceRestInterceptor] = 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 FileUploadsServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _GetFileUpload(_BaseFileUploadsServiceRestTransport._BaseGetFileUpload, FileUploadsServiceRestStub): + def __hash__(self): + return hash("FileUploadsServiceRestTransport.GetFileUpload") + + @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: fileuploads.GetFileUploadRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> fileuploads.FileUpload: + r"""Call the get file upload method over HTTP. + + Args: + request (~.fileuploads.GetFileUploadRequest): + The request object. Request message for the + GetFileUploadRequest method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.fileuploads.FileUpload: + The file upload of a specific data + source, that is, the result of the + retrieval of the data source at a + certain timestamp computed + asynchronously when the data source + processing is finished. Only applicable + to file data sources. + + """ + + http_options = _BaseFileUploadsServiceRestTransport._BaseGetFileUpload._get_http_options() + + request, metadata = self._interceptor.pre_get_file_upload(request, metadata) + transcoded_request = _BaseFileUploadsServiceRestTransport._BaseGetFileUpload._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseFileUploadsServiceRestTransport._BaseGetFileUpload._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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.datasources_v1beta.FileUploadsServiceClient.GetFileUpload", + extra = { + "serviceName": "google.shopping.merchant.datasources.v1beta.FileUploadsService", + "rpcName": "GetFileUpload", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = FileUploadsServiceRestTransport._GetFileUpload._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 = fileuploads.FileUpload() + pb_resp = fileuploads.FileUpload.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_file_upload(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = fileuploads.FileUpload.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.datasources_v1beta.FileUploadsServiceClient.get_file_upload", + extra = { + "serviceName": "google.shopping.merchant.datasources.v1beta.FileUploadsService", + "rpcName": "GetFileUpload", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def get_file_upload(self) -> Callable[ + [fileuploads.GetFileUploadRequest], + fileuploads.FileUpload]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetFileUpload(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'FileUploadsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/rest_base.py new file mode 100644 index 000000000000..65fd0e3b6d45 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/rest_base.py @@ -0,0 +1,128 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 FileUploadsServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.shopping.merchant_datasources_v1beta.types import fileuploads + + +class _BaseFileUploadsServiceRestTransport(FileUploadsServiceTransport): + """Base REST backend transport for FileUploadsService. + + 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 _BaseGetFileUpload: + 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': '/datasources/v1beta/{name=accounts/*/dataSources/*/fileUploads/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = fileuploads.GetFileUploadRequest.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(_BaseFileUploadsServiceRestTransport._BaseGetFileUpload._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseFileUploadsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/types/__init__.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/types/__init__.py new file mode 100644 index 000000000000..8579cd01b10c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/types/__init__.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .datasources import ( + CreateDataSourceRequest, + DataSource, + DeleteDataSourceRequest, + FetchDataSourceRequest, + GetDataSourceRequest, + ListDataSourcesRequest, + ListDataSourcesResponse, + UpdateDataSourceRequest, +) +from .datasourcetypes import ( + DataSourceReference, + LocalInventoryDataSource, + PrimaryProductDataSource, + PromotionDataSource, + RegionalInventoryDataSource, + SupplementalProductDataSource, +) +from .fileinputs import ( + FileInput, +) +from .fileuploads import ( + FileUpload, + GetFileUploadRequest, +) + +__all__ = ( + 'CreateDataSourceRequest', + 'DataSource', + 'DeleteDataSourceRequest', + 'FetchDataSourceRequest', + 'GetDataSourceRequest', + 'ListDataSourcesRequest', + 'ListDataSourcesResponse', + 'UpdateDataSourceRequest', + 'DataSourceReference', + 'LocalInventoryDataSource', + 'PrimaryProductDataSource', + 'PromotionDataSource', + 'RegionalInventoryDataSource', + 'SupplementalProductDataSource', + 'FileInput', + 'FileUpload', + 'GetFileUploadRequest', +) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/types/datasources.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/types/datasources.py new file mode 100644 index 000000000000..59d2cddd3464 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/types/datasources.py @@ -0,0 +1,351 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_datasources_v1beta.types import datasourcetypes +from google.shopping.merchant_datasources_v1beta.types import fileinputs + + +__protobuf__ = proto.module( + package='google.shopping.merchant.datasources.v1beta', + manifest={ + 'DataSource', + 'GetDataSourceRequest', + 'ListDataSourcesRequest', + 'ListDataSourcesResponse', + 'CreateDataSourceRequest', + 'UpdateDataSourceRequest', + 'FetchDataSourceRequest', + 'DeleteDataSourceRequest', + }, +) + + +class DataSource(proto.Message): + r"""The `data + source `__ for + the Merchant Center account. + + 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: + primary_product_data_source (google.shopping.merchant_datasources_v1beta.types.PrimaryProductDataSource): + Required. The `primary data + source `__ + for local and online products. + + This field is a member of `oneof`_ ``Type``. + supplemental_product_data_source (google.shopping.merchant_datasources_v1beta.types.SupplementalProductDataSource): + Required. The `supplemental data + source `__ + for local and online products. + + This field is a member of `oneof`_ ``Type``. + local_inventory_data_source (google.shopping.merchant_datasources_v1beta.types.LocalInventoryDataSource): + Required. The `local + inventory `__ + data source. + + This field is a member of `oneof`_ ``Type``. + regional_inventory_data_source (google.shopping.merchant_datasources_v1beta.types.RegionalInventoryDataSource): + Required. The `regional + inventory `__ + data source. + + This field is a member of `oneof`_ ``Type``. + promotion_data_source (google.shopping.merchant_datasources_v1beta.types.PromotionDataSource): + Required. The + `promotion `__ + data source. + + This field is a member of `oneof`_ ``Type``. + name (str): + Identifier. The name of the data source. Format: + ``{datasource.name=accounts/{account}/dataSources/{datasource}}`` + data_source_id (int): + Output only. The data source id. + display_name (str): + Required. The displayed data source name in + the Merchant Center UI. + input (google.shopping.merchant_datasources_v1beta.types.DataSource.Input): + Output only. Determines the type of input to + the data source. Based on the input some + settings might not work. Only generic data + sources can be created through the API. + file_input (google.shopping.merchant_datasources_v1beta.types.FileInput): + Optional. The field is used only when data is + managed through a file. + """ + class Input(proto.Enum): + r"""Determines the type of input to the data source. Based on the + input some settings might not be supported. + + Values: + INPUT_UNSPECIFIED (0): + Input unspecified. + API (1): + Represents data sources for which the data is + primarily provided through the API. + FILE (2): + Represents data sources for which the data is + primarily provided through file input. Data can + still be provided through the API. + UI (3): + The data source for products added directly + in Merchant Center. + This type of data source can not be created or + updated through this API, only by Merchant + Center UI. + + This type of data source is read only. + AUTOFEED (4): + This is also known as `Automated + feeds `__ + used to automatically build your product data. This type of + data source can be enabled or disabled through the Accounts + bundle. + """ + INPUT_UNSPECIFIED = 0 + API = 1 + FILE = 2 + UI = 3 + AUTOFEED = 4 + + primary_product_data_source: datasourcetypes.PrimaryProductDataSource = proto.Field( + proto.MESSAGE, + number=4, + oneof='Type', + message=datasourcetypes.PrimaryProductDataSource, + ) + supplemental_product_data_source: datasourcetypes.SupplementalProductDataSource = proto.Field( + proto.MESSAGE, + number=5, + oneof='Type', + message=datasourcetypes.SupplementalProductDataSource, + ) + local_inventory_data_source: datasourcetypes.LocalInventoryDataSource = proto.Field( + proto.MESSAGE, + number=6, + oneof='Type', + message=datasourcetypes.LocalInventoryDataSource, + ) + regional_inventory_data_source: datasourcetypes.RegionalInventoryDataSource = proto.Field( + proto.MESSAGE, + number=7, + oneof='Type', + message=datasourcetypes.RegionalInventoryDataSource, + ) + promotion_data_source: datasourcetypes.PromotionDataSource = proto.Field( + proto.MESSAGE, + number=8, + oneof='Type', + message=datasourcetypes.PromotionDataSource, + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + data_source_id: int = proto.Field( + proto.INT64, + number=2, + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + ) + input: Input = proto.Field( + proto.ENUM, + number=10, + enum=Input, + ) + file_input: fileinputs.FileInput = proto.Field( + proto.MESSAGE, + number=11, + message=fileinputs.FileInput, + ) + + +class GetDataSourceRequest(proto.Message): + r"""Request message for the GetDataSource method. + + Attributes: + name (str): + Required. The name of the data source to retrieve. Format: + ``accounts/{account}/dataSources/{datasource}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListDataSourcesRequest(proto.Message): + r"""Request message for the ListDataSources method. + + Attributes: + parent (str): + Required. The account to list data sources for. Format: + ``accounts/{account}`` + page_size (int): + Optional. The maximum number of data sources + to return. The service may return fewer than + this value. The maximum value is 1000; values + above 1000 will be coerced to 1000. If + unspecified, the maximum number of data sources + will be returned. + page_token (str): + Optional. A page token, received from a previous + ``ListDataSources`` call. Provide this to retrieve the + subsequent page. + + When paginating, all other parameters provided to + ``ListDataSources`` 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 ListDataSourcesResponse(proto.Message): + r"""Response message for the ListDataSources method. + + Attributes: + data_sources (MutableSequence[google.shopping.merchant_datasources_v1beta.types.DataSource]): + The data sources 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 + + data_sources: MutableSequence['DataSource'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='DataSource', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateDataSourceRequest(proto.Message): + r"""Request message for the CreateDataSource method. + + Attributes: + parent (str): + Required. The account where this data source will be + created. Format: ``accounts/{account}`` + data_source (google.shopping.merchant_datasources_v1beta.types.DataSource): + Required. The data source to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + data_source: 'DataSource' = proto.Field( + proto.MESSAGE, + number=2, + message='DataSource', + ) + + +class UpdateDataSourceRequest(proto.Message): + r"""Request message for the UpdateDataSource method. + + Attributes: + data_source (google.shopping.merchant_datasources_v1beta.types.DataSource): + Required. The data source resource to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of data source fields to be updated. + + Fields specified in the update mask without a value + specified in the body will be deleted from the data source. + + Providing special "*" value for full data source replacement + is not supported. + """ + + data_source: 'DataSource' = proto.Field( + proto.MESSAGE, + number=1, + message='DataSource', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class FetchDataSourceRequest(proto.Message): + r"""Request message for the FetchDataSource method. + + Attributes: + name (str): + Required. The name of the data source resource to fetch. + Format: ``accounts/{account}/dataSources/{datasource}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteDataSourceRequest(proto.Message): + r"""Request message for the DeleteDataSource method. + + Attributes: + name (str): + Required. The name of the data source to delete. Format: + ``accounts/{account}/dataSources/{datasource}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/types/datasourcetypes.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/types/datasourcetypes.py new file mode 100644 index 000000000000..eae022534c7b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/types/datasourcetypes.py @@ -0,0 +1,372 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.datasources.v1beta', + manifest={ + 'PrimaryProductDataSource', + 'SupplementalProductDataSource', + 'LocalInventoryDataSource', + 'RegionalInventoryDataSource', + 'PromotionDataSource', + 'DataSourceReference', + }, +) + + +class PrimaryProductDataSource(proto.Message): + r"""The primary data source for local and online products. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + channel (google.shopping.merchant_datasources_v1beta.types.PrimaryProductDataSource.Channel): + Required. Immutable. Specifies the type of + data source channel. + feed_label (str): + Optional. Immutable. The feed label that is specified on the + data source level. + + Must be less than or equal to 20 uppercase letters (A-Z), + numbers (0-9), and dashes (-). + + See also `migration to feed + labels `__. + + ``feedLabel`` and ``contentLanguage`` must be either both + set or unset for data sources with product content type. + They must be set for data sources with a file input. + + If set, the data source will only accept products matching + this combination. If unset, the data source will accept + products without that restriction. + + This field is a member of `oneof`_ ``_feed_label``. + content_language (str): + Optional. Immutable. The two-letter ISO 639-1 language of + the items in the data source. + + ``feedLabel`` and ``contentLanguage`` must be either both + set or unset. The fields can only be unset for data sources + without file input. + + If set, the data source will only accept products matching + this combination. If unset, the data source will accept + products without that restriction. + + This field is a member of `oneof`_ ``_content_language``. + countries (MutableSequence[str]): + Optional. The countries where the items may be displayed. + Represented as a `CLDR territory + code `__. + default_rule (google.shopping.merchant_datasources_v1beta.types.PrimaryProductDataSource.DefaultRule): + Optional. Default rule management of the data + source. If set, the linked data sources will be + replaced. + """ + class Channel(proto.Enum): + r"""Data Source Channel. + + Channel is used to distinguish between data sources for + different product verticals. + + Values: + CHANNEL_UNSPECIFIED (0): + Not specified. + ONLINE_PRODUCTS (1): + Online product. + LOCAL_PRODUCTS (2): + Local product. + PRODUCTS (3): + Unified data source for both local and online + products. Note: Products management through the + API is not possible for this channel. + """ + CHANNEL_UNSPECIFIED = 0 + ONLINE_PRODUCTS = 1 + LOCAL_PRODUCTS = 2 + PRODUCTS = 3 + + class DefaultRule(proto.Message): + r"""Default rule management of the data source. + + Attributes: + take_from_data_sources (MutableSequence[google.shopping.merchant_datasources_v1beta.types.DataSourceReference]): + Required. The list of data sources linked in the `default + rule `__. + This list is ordered by the default rule priority of joining + the data. It might include none or multiple references to + ``self`` and supplemental data sources. + + The list must not be empty. + + To link the data source to the default rule, you need to add + a new reference to this list (in sequential order). + + To unlink the data source from the default rule, you need to + remove the given reference from this list. To create + attribute rules that are different from the default rule, + see `Set up your attribute + rules `__. + + Changing the order of this list will result in changing the + priority of data sources in the default rule. + + For example, providing the following list: [``1001``, + ``self``] will take attribute values from supplemental data + source ``1001``, and fallback to ``self`` if the attribute + is not set in ``1001``. + """ + + take_from_data_sources: MutableSequence['DataSourceReference'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='DataSourceReference', + ) + + channel: Channel = proto.Field( + proto.ENUM, + number=3, + enum=Channel, + ) + feed_label: str = proto.Field( + proto.STRING, + number=4, + optional=True, + ) + content_language: str = proto.Field( + proto.STRING, + number=5, + optional=True, + ) + countries: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=6, + ) + default_rule: DefaultRule = proto.Field( + proto.MESSAGE, + number=7, + message=DefaultRule, + ) + + +class SupplementalProductDataSource(proto.Message): + r"""The supplemental data source for local and online products. + Supplemental API data sources must not have ``feedLabel`` and + ``contentLanguage`` fields set. You can only use supplemental data + sources to update existing products. For information about creating + a supplemental data source, see `Create a supplemental data source + and link it to the primary data + source `__. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + feed_label (str): + Optional. Immutable. The feed label that is specified on the + data source level. + + Must be less than or equal to 20 uppercase letters (A-Z), + numbers (0-9), and dashes (-). + + See also `migration to feed + labels `__. + + ``feedLabel`` and ``contentLanguage`` must be either both + set or unset for data sources with product content type. + They must be set for data sources with a file input. + + If set, the data source will only accept products matching + this combination. If unset, the data source will accept + produts without that restriction. + + This field is a member of `oneof`_ ``_feed_label``. + content_language (str): + Optional. Immutable. The two-letter ISO 639-1 language of + the items in the data source. + + ``feedLabel`` and ``contentLanguage`` must be either both + set or unset. The fields can only be unset for data sources + without file input. + + If set, the data source will only accept products matching + this combination. If unset, the data source will accept + produts without that restriction. + + This field is a member of `oneof`_ ``_content_language``. + referencing_primary_data_sources (MutableSequence[google.shopping.merchant_datasources_v1beta.types.DataSourceReference]): + Output only. The (unordered and deduplicated) + list of all primary data sources linked to this + data source in either default or custom rules. + Supplemental data source cannot be deleted + before all links are removed. + """ + + feed_label: str = proto.Field( + proto.STRING, + number=4, + optional=True, + ) + content_language: str = proto.Field( + proto.STRING, + number=5, + optional=True, + ) + referencing_primary_data_sources: MutableSequence['DataSourceReference'] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message='DataSourceReference', + ) + + +class LocalInventoryDataSource(proto.Message): + r"""The local inventory data source. + + Attributes: + feed_label (str): + Required. Immutable. The feed label of the offers to which + the local inventory is provided. + + Must be less than or equal to 20 uppercase letters (A-Z), + numbers (0-9), and dashes (-). + + See also `migration to feed + labels `__. + content_language (str): + Required. Immutable. The two-letter ISO 639-1 + language of the items to which the local + inventory is provided. + """ + + feed_label: str = proto.Field( + proto.STRING, + number=4, + ) + content_language: str = proto.Field( + proto.STRING, + number=5, + ) + + +class RegionalInventoryDataSource(proto.Message): + r"""The regional inventory data source. + + Attributes: + feed_label (str): + Required. Immutable. The feed label of the offers to which + the regional inventory is provided. + + Must be less than or equal to 20 uppercase letters (A-Z), + numbers (0-9), and dashes (-). + + See also `migration to feed + labels `__. + content_language (str): + Required. Immutable. The two-letter ISO 639-1 + language of the items to which the regional + inventory is provided. + """ + + feed_label: str = proto.Field( + proto.STRING, + number=4, + ) + content_language: str = proto.Field( + proto.STRING, + number=5, + ) + + +class PromotionDataSource(proto.Message): + r"""The promotion data source. + + Attributes: + target_country (str): + Required. Immutable. The target country used as part of the + unique identifier. Represented as a `CLDR territory + code `__. + + Promotions are only available in selected + `countries `__. + content_language (str): + Required. Immutable. The two-letter ISO 639-1 + language of the items in the data source. + """ + + target_country: str = proto.Field( + proto.STRING, + number=1, + ) + content_language: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DataSourceReference(proto.Message): + r"""Data source reference can be used to manage related data + sources within the data source service. + + 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: + self_ (bool): + Self should be used to reference the primary + data source itself. + + This field is a member of `oneof`_ ``data_source_id``. + primary_data_source_name (str): + Optional. The name of the primary data source. Format: + ``accounts/{account}/dataSources/{datasource}`` + + This field is a member of `oneof`_ ``data_source_id``. + supplemental_data_source_name (str): + Optional. The name of the supplemental data source. Format: + ``accounts/{account}/dataSources/{datasource}`` + + This field is a member of `oneof`_ ``data_source_id``. + """ + + self_: bool = proto.Field( + proto.BOOL, + number=1, + oneof='data_source_id', + ) + primary_data_source_name: str = proto.Field( + proto.STRING, + number=3, + oneof='data_source_id', + ) + supplemental_data_source_name: str = proto.Field( + proto.STRING, + number=2, + oneof='data_source_id', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/types/fileinputs.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/types/fileinputs.py new file mode 100644 index 000000000000..18869a01a769 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/types/fileinputs.py @@ -0,0 +1,201 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 dayofweek_pb2 # type: ignore +from google.type import timeofday_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.shopping.merchant.datasources.v1beta', + manifest={ + 'FileInput', + }, +) + + +class FileInput(proto.Message): + r"""The data specific for file data sources. This field is empty + for other data source inputs. + + Attributes: + fetch_settings (google.shopping.merchant_datasources_v1beta.types.FileInput.FetchSettings): + Optional. Fetch details to deliver the data source. It + contains settings for ``FETCH`` and ``GOOGLE_SHEETS`` file + input types. The required fields vary based on the frequency + of fetching. + file_name (str): + Optional. The file name of the data source. Required for + ``UPLOAD`` file input type. + file_input_type (google.shopping.merchant_datasources_v1beta.types.FileInput.FileInputType): + Output only. The type of file input. + """ + class FileInputType(proto.Enum): + r"""The method of file delivery. + + Values: + FILE_INPUT_TYPE_UNSPECIFIED (0): + File input type unspecified. + UPLOAD (1): + The file is uploaded through SFTP, Google + Cloud Storage or manually in the Merchant + Center. + FETCH (2): + The file is fetched from the configured + [fetch_uri][google.shopping.content.bundles.DataSources.FileInput.FetchSettings.fetch_uri]. + GOOGLE_SHEETS (3): + The file is fetched from Google Sheets specified in the + [fetch_uri][google.shopping.content.bundles.DataSources.FileInput.FetchSettings.fetch_uri]. + """ + FILE_INPUT_TYPE_UNSPECIFIED = 0 + UPLOAD = 1 + FETCH = 2 + GOOGLE_SHEETS = 3 + + class FetchSettings(proto.Message): + r"""Fetch details to deliver the data source. + + Attributes: + enabled (bool): + Optional. Enables or pauses the fetch + schedule. + day_of_month (int): + Optional. The day of the month when the data + source file should be fetched (1-31). This field + can only be set for monthly frequency. + time_of_day (google.type.timeofday_pb2.TimeOfDay): + Optional. The hour of the day when the data + source file should be fetched. Minutes and + seconds are not supported and will be ignored. + day_of_week (google.type.dayofweek_pb2.DayOfWeek): + Optional. The day of the week when the data + source file should be fetched. This field can + only be set for weekly frequency. + time_zone (str): + Optional. `Time zone `__ used for + schedule. UTC by default. For example, + "America/Los_Angeles". + frequency (google.shopping.merchant_datasources_v1beta.types.FileInput.FetchSettings.Frequency): + Required. The frequency describing fetch + schedule. + fetch_uri (str): + Optional. The URL where the data source file + can be fetched. Google Merchant Center supports + automatic scheduled uploads using the HTTP, + HTTPS or SFTP protocols, so the value will need + to be a valid link using one of those three + protocols. Immutable for Google Sheets files. + username (str): + Optional. An optional user name for [fetch + url][google.shopping.content.bundles.DataSources.FileInput.fetch_url]. + Used for `submitting data sources through + SFTP `__. + password (str): + Optional. An optional password for [fetch + url][google.shopping.content.bundles.DataSources.FileInput.fetch_url]. + Used for `submitting data sources through + SFTP `__. + """ + class Frequency(proto.Enum): + r"""The required fields vary based on the frequency of fetching. For a + monthly fetch schedule, [day of + month][google.shopping.content.bundles.DataSources.FileInput.FetchSchedule.day_of_month] + and [hour of + day][google.shopping.content.bundles.DataSources.FileInput.FetchSchedule.time_of_day] + are required. For a weekly fetch schedule, [day of + week][google.shopping.content.bundles.DataSources.FileInput.FetchSchedule.day_of_week] + and [hour of + day][google.shopping.content.bundles.DataSources.FileInput.FetchSchedule.time_of_day] + are required. For a daily fetch schedule, only an [hour of + day][google.shopping.content.bundles.DataSources.FileInput.FetchSchedule.time_of_day] + is required. + + Values: + FREQUENCY_UNSPECIFIED (0): + Frequency unspecified. + FREQUENCY_DAILY (1): + The fetch happens every day. + FREQUENCY_WEEKLY (2): + The fetch happens every week. + FREQUENCY_MONTHLY (3): + The fetch happens every month. + """ + FREQUENCY_UNSPECIFIED = 0 + FREQUENCY_DAILY = 1 + FREQUENCY_WEEKLY = 2 + FREQUENCY_MONTHLY = 3 + + enabled: bool = proto.Field( + proto.BOOL, + number=1, + ) + day_of_month: int = proto.Field( + proto.INT32, + number=2, + ) + time_of_day: timeofday_pb2.TimeOfDay = proto.Field( + proto.MESSAGE, + number=3, + message=timeofday_pb2.TimeOfDay, + ) + day_of_week: dayofweek_pb2.DayOfWeek = proto.Field( + proto.ENUM, + number=4, + enum=dayofweek_pb2.DayOfWeek, + ) + time_zone: str = proto.Field( + proto.STRING, + number=5, + ) + frequency: 'FileInput.FetchSettings.Frequency' = proto.Field( + proto.ENUM, + number=6, + enum='FileInput.FetchSettings.Frequency', + ) + fetch_uri: str = proto.Field( + proto.STRING, + number=7, + ) + username: str = proto.Field( + proto.STRING, + number=8, + ) + password: str = proto.Field( + proto.STRING, + number=9, + ) + + fetch_settings: FetchSettings = proto.Field( + proto.MESSAGE, + number=1, + message=FetchSettings, + ) + file_name: str = proto.Field( + proto.STRING, + number=2, + ) + file_input_type: FileInputType = proto.Field( + proto.ENUM, + number=3, + enum=FileInputType, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/types/fileuploads.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/types/fileuploads.py new file mode 100644 index 000000000000..6488a963fc40 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/types/fileuploads.py @@ -0,0 +1,205 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.shopping.merchant.datasources.v1beta', + manifest={ + 'FileUpload', + 'GetFileUploadRequest', + }, +) + + +class FileUpload(proto.Message): + r"""The file upload of a specific data source, that is, the + result of the retrieval of the data source at a certain + timestamp computed asynchronously when the data source + processing is finished. Only applicable to file data sources. + + Attributes: + name (str): + Identifier. The name of the data source file upload. Format: + ``{datasource.name=accounts/{account}/dataSources/{datasource}/fileUploads/{fileupload}}`` + data_source_id (int): + Output only. The data source id. + processing_state (google.shopping.merchant_datasources_v1beta.types.FileUpload.ProcessingState): + Output only. The processing state of the data + source. + issues (MutableSequence[google.shopping.merchant_datasources_v1beta.types.FileUpload.Issue]): + Output only. The list of issues occurring in + the data source. + items_total (int): + Output only. The number of items in the data + source that were processed. + items_created (int): + Output only. The number of items in the data + source that were created. + items_updated (int): + Output only. The number of items in the data + source that were updated. + upload_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The date at which the file of + the data source was uploaded. + """ + class ProcessingState(proto.Enum): + r"""The processing state of the data source. + + Values: + PROCESSING_STATE_UNSPECIFIED (0): + Processing state unspecified. + FAILED (1): + The data source could not be processed or all + the items had errors. + IN_PROGRESS (2): + The data source is being processed. + SUCCEEDED (3): + The data source was processed successfully, + though some items might have had errors. + """ + PROCESSING_STATE_UNSPECIFIED = 0 + FAILED = 1 + IN_PROGRESS = 2 + SUCCEEDED = 3 + + class Issue(proto.Message): + r"""An error occurring in the data source, like "invalid price". + + Attributes: + title (str): + Output only. The title of the issue, for + example, "Item too big". + description (str): + Output only. The error description, for + example, "Your data source contains items which + have too many attributes, or are too big. These + items will be dropped". + code (str): + Output only. The code of the error, for example, + "validation/invalid_value". Returns "?" if the code is + unknown. + count (int): + Output only. The number of occurrences of the + error in the file upload. + severity (google.shopping.merchant_datasources_v1beta.types.FileUpload.Issue.Severity): + Output only. The severity of the issue. + documentation_uri (str): + Output only. Link to the documentation + explaining the issue in more details, if + available. + """ + class Severity(proto.Enum): + r"""The severity of the issue. + + Values: + SEVERITY_UNSPECIFIED (0): + Severity unspecified. + WARNING (1): + The issue is the warning. + ERROR (2): + The issue is an error. + """ + SEVERITY_UNSPECIFIED = 0 + WARNING = 1 + ERROR = 2 + + title: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + code: str = proto.Field( + proto.STRING, + number=3, + ) + count: int = proto.Field( + proto.INT64, + number=4, + ) + severity: 'FileUpload.Issue.Severity' = proto.Field( + proto.ENUM, + number=5, + enum='FileUpload.Issue.Severity', + ) + documentation_uri: str = proto.Field( + proto.STRING, + number=6, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + data_source_id: int = proto.Field( + proto.INT64, + number=2, + ) + processing_state: ProcessingState = proto.Field( + proto.ENUM, + number=3, + enum=ProcessingState, + ) + issues: MutableSequence[Issue] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=Issue, + ) + items_total: int = proto.Field( + proto.INT64, + number=5, + ) + items_created: int = proto.Field( + proto.INT64, + number=6, + ) + items_updated: int = proto.Field( + proto.INT64, + number=7, + ) + upload_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + + +class GetFileUploadRequest(proto.Message): + r"""Request message for the GetFileUploadRequest method. + + Attributes: + name (str): + Required. The name of the data source file upload to + retrieve. Format: + ``accounts/{account}/dataSources/{datasource}/fileUploads/latest`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/mypy.ini b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/noxfile.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/noxfile.py new file mode 100644 index 000000000000..cdbea940f142 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/noxfile.py @@ -0,0 +1,280 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = 'google-shopping-merchant-datasources' + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.13" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "prerelease_deps", +] + +@nox.session(python=ALL_PYTHON) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def unit(session, protobuf_implementation): + """Run the unit test suite.""" + + 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+") + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") + + # 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") + + session.run( + 'py.test', + '--quiet', + '--cov=google/shopping/merchant_datasources_v1beta/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)), + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + +@nox.session(python=ALL_PYTHON[-1]) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def prerelease_deps(session, protobuf_implementation): + """Run the unit test suite against pre-release versions of dependencies.""" + + 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 test environment dependencies + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + + # Install the package without dependencies + session.install('-e', '.', '--no-deps') + + # We test the minimum dependency versions using the minimum Python + # version so the lowest python runtime that we test has a corresponding constraints + # file, located at `testing/constraints--.txt`, which contains all of the + # 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 + ) + ] + + session.install(*constraints_deps) + + prerel_deps = [ + "googleapis-common-protos", + "google-api-core", + "google-auth", + # Exclude grpcio!=1.67.0rc1 which does not support python 3.13 + "grpcio!=1.67.0rc1", + "grpcio-status", + "protobuf", + "proto-plus", + ] + + for dep in prerel_deps: + session.install("--pre", "--no-deps", "--upgrade", dep) + + # Remaining dependencies + other_deps = [ + "requests", + ] + session.install(*other_deps) + + # Print out prerelease package versions + + session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") + session.run("python", "-c", "import google.auth; print(google.auth.__version__)") + session.run("python", "-c", "import grpc; print(grpc.__version__)") + session.run( + "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" + ) + session.run( + "python", "-c", "import proto; print(proto.__version__)" + ) + + session.run( + 'py.test', + '--quiet', + '--cov=google/shopping/merchant_datasources_v1beta/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)), + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + + +@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=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 docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==7.0.1", "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=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", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_create_data_source_async.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_create_data_source_async.py new file mode 100644 index 000000000000..3a58c16a898f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_create_data_source_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateDataSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-datasources + + +# [START merchantapi_v1beta_generated_DataSourcesService_CreateDataSource_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_datasources_v1beta + + +async def sample_create_data_source(): + # Create a client + client = merchant_datasources_v1beta.DataSourcesServiceAsyncClient() + + # Initialize request argument(s) + data_source = merchant_datasources_v1beta.DataSource() + data_source.primary_product_data_source.channel = "PRODUCTS" + data_source.display_name = "display_name_value" + + request = merchant_datasources_v1beta.CreateDataSourceRequest( + parent="parent_value", + data_source=data_source, + ) + + # Make the request + response = await client.create_data_source(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_DataSourcesService_CreateDataSource_async] diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_create_data_source_sync.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_create_data_source_sync.py new file mode 100644 index 000000000000..e83b38fa6921 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_create_data_source_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateDataSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-datasources + + +# [START merchantapi_v1beta_generated_DataSourcesService_CreateDataSource_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_datasources_v1beta + + +def sample_create_data_source(): + # Create a client + client = merchant_datasources_v1beta.DataSourcesServiceClient() + + # Initialize request argument(s) + data_source = merchant_datasources_v1beta.DataSource() + data_source.primary_product_data_source.channel = "PRODUCTS" + data_source.display_name = "display_name_value" + + request = merchant_datasources_v1beta.CreateDataSourceRequest( + parent="parent_value", + data_source=data_source, + ) + + # Make the request + response = client.create_data_source(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_DataSourcesService_CreateDataSource_sync] diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_delete_data_source_async.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_delete_data_source_async.py new file mode 100644 index 000000000000..3acdea1ade71 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_delete_data_source_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteDataSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-datasources + + +# [START merchantapi_v1beta_generated_DataSourcesService_DeleteDataSource_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_datasources_v1beta + + +async def sample_delete_data_source(): + # Create a client + client = merchant_datasources_v1beta.DataSourcesServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_datasources_v1beta.DeleteDataSourceRequest( + name="name_value", + ) + + # Make the request + await client.delete_data_source(request=request) + + +# [END merchantapi_v1beta_generated_DataSourcesService_DeleteDataSource_async] diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_delete_data_source_sync.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_delete_data_source_sync.py new file mode 100644 index 000000000000..443f82260fcd --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_delete_data_source_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteDataSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-datasources + + +# [START merchantapi_v1beta_generated_DataSourcesService_DeleteDataSource_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_datasources_v1beta + + +def sample_delete_data_source(): + # Create a client + client = merchant_datasources_v1beta.DataSourcesServiceClient() + + # Initialize request argument(s) + request = merchant_datasources_v1beta.DeleteDataSourceRequest( + name="name_value", + ) + + # Make the request + client.delete_data_source(request=request) + + +# [END merchantapi_v1beta_generated_DataSourcesService_DeleteDataSource_sync] diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_fetch_data_source_async.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_fetch_data_source_async.py new file mode 100644 index 000000000000..14df43d8bd47 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_fetch_data_source_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for FetchDataSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-datasources + + +# [START merchantapi_v1beta_generated_DataSourcesService_FetchDataSource_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_datasources_v1beta + + +async def sample_fetch_data_source(): + # Create a client + client = merchant_datasources_v1beta.DataSourcesServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_datasources_v1beta.FetchDataSourceRequest( + name="name_value", + ) + + # Make the request + await client.fetch_data_source(request=request) + + +# [END merchantapi_v1beta_generated_DataSourcesService_FetchDataSource_async] diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_fetch_data_source_sync.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_fetch_data_source_sync.py new file mode 100644 index 000000000000..644b35470074 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_fetch_data_source_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for FetchDataSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-datasources + + +# [START merchantapi_v1beta_generated_DataSourcesService_FetchDataSource_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_datasources_v1beta + + +def sample_fetch_data_source(): + # Create a client + client = merchant_datasources_v1beta.DataSourcesServiceClient() + + # Initialize request argument(s) + request = merchant_datasources_v1beta.FetchDataSourceRequest( + name="name_value", + ) + + # Make the request + client.fetch_data_source(request=request) + + +# [END merchantapi_v1beta_generated_DataSourcesService_FetchDataSource_sync] diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_get_data_source_async.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_get_data_source_async.py new file mode 100644 index 000000000000..091d08e5fbd5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_get_data_source_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDataSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-datasources + + +# [START merchantapi_v1beta_generated_DataSourcesService_GetDataSource_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_datasources_v1beta + + +async def sample_get_data_source(): + # Create a client + client = merchant_datasources_v1beta.DataSourcesServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_datasources_v1beta.GetDataSourceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_data_source(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_DataSourcesService_GetDataSource_async] diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_get_data_source_sync.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_get_data_source_sync.py new file mode 100644 index 000000000000..fa9c6c87bc15 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_get_data_source_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDataSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-datasources + + +# [START merchantapi_v1beta_generated_DataSourcesService_GetDataSource_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_datasources_v1beta + + +def sample_get_data_source(): + # Create a client + client = merchant_datasources_v1beta.DataSourcesServiceClient() + + # Initialize request argument(s) + request = merchant_datasources_v1beta.GetDataSourceRequest( + name="name_value", + ) + + # Make the request + response = client.get_data_source(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_DataSourcesService_GetDataSource_sync] diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_list_data_sources_async.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_list_data_sources_async.py new file mode 100644 index 000000000000..78339cc39b35 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_list_data_sources_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListDataSources +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-datasources + + +# [START merchantapi_v1beta_generated_DataSourcesService_ListDataSources_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_datasources_v1beta + + +async def sample_list_data_sources(): + # Create a client + client = merchant_datasources_v1beta.DataSourcesServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_datasources_v1beta.ListDataSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_data_sources(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_DataSourcesService_ListDataSources_async] diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_list_data_sources_sync.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_list_data_sources_sync.py new file mode 100644 index 000000000000..46febb24d2d8 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_list_data_sources_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListDataSources +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-datasources + + +# [START merchantapi_v1beta_generated_DataSourcesService_ListDataSources_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_datasources_v1beta + + +def sample_list_data_sources(): + # Create a client + client = merchant_datasources_v1beta.DataSourcesServiceClient() + + # Initialize request argument(s) + request = merchant_datasources_v1beta.ListDataSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_data_sources(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_DataSourcesService_ListDataSources_sync] diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_update_data_source_async.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_update_data_source_async.py new file mode 100644 index 000000000000..a727ef72c51e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_update_data_source_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateDataSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-datasources + + +# [START merchantapi_v1beta_generated_DataSourcesService_UpdateDataSource_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_datasources_v1beta + + +async def sample_update_data_source(): + # Create a client + client = merchant_datasources_v1beta.DataSourcesServiceAsyncClient() + + # Initialize request argument(s) + data_source = merchant_datasources_v1beta.DataSource() + data_source.primary_product_data_source.channel = "PRODUCTS" + data_source.display_name = "display_name_value" + + request = merchant_datasources_v1beta.UpdateDataSourceRequest( + data_source=data_source, + ) + + # Make the request + response = await client.update_data_source(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_DataSourcesService_UpdateDataSource_async] diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_update_data_source_sync.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_update_data_source_sync.py new file mode 100644 index 000000000000..72d7760192c6 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_update_data_source_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateDataSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-datasources + + +# [START merchantapi_v1beta_generated_DataSourcesService_UpdateDataSource_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_datasources_v1beta + + +def sample_update_data_source(): + # Create a client + client = merchant_datasources_v1beta.DataSourcesServiceClient() + + # Initialize request argument(s) + data_source = merchant_datasources_v1beta.DataSource() + data_source.primary_product_data_source.channel = "PRODUCTS" + data_source.display_name = "display_name_value" + + request = merchant_datasources_v1beta.UpdateDataSourceRequest( + data_source=data_source, + ) + + # Make the request + response = client.update_data_source(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_DataSourcesService_UpdateDataSource_sync] diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_file_uploads_service_get_file_upload_async.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_file_uploads_service_get_file_upload_async.py new file mode 100644 index 000000000000..69eed065c6f5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_file_uploads_service_get_file_upload_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetFileUpload +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-datasources + + +# [START merchantapi_v1beta_generated_FileUploadsService_GetFileUpload_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_datasources_v1beta + + +async def sample_get_file_upload(): + # Create a client + client = merchant_datasources_v1beta.FileUploadsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_datasources_v1beta.GetFileUploadRequest( + name="name_value", + ) + + # Make the request + response = await client.get_file_upload(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_FileUploadsService_GetFileUpload_async] diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_file_uploads_service_get_file_upload_sync.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_file_uploads_service_get_file_upload_sync.py new file mode 100644 index 000000000000..8ca612c4e3bd --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_file_uploads_service_get_file_upload_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetFileUpload +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-datasources + + +# [START merchantapi_v1beta_generated_FileUploadsService_GetFileUpload_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_datasources_v1beta + + +def sample_get_file_upload(): + # Create a client + client = merchant_datasources_v1beta.FileUploadsServiceClient() + + # Initialize request argument(s) + request = merchant_datasources_v1beta.GetFileUploadRequest( + name="name_value", + ) + + # Make the request + response = client.get_file_upload(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_FileUploadsService_GetFileUpload_sync] diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.datasources.v1beta.json b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.datasources.v1beta.json new file mode 100644 index 000000000000..992de0dc6fb0 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.datasources.v1beta.json @@ -0,0 +1,1138 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.shopping.merchant.datasources.v1beta", + "version": "v1beta" + } + ], + "language": "PYTHON", + "name": "google-shopping-merchant-datasources", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceAsyncClient", + "shortName": "DataSourcesServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceAsyncClient.create_data_source", + "method": { + "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService.CreateDataSource", + "service": { + "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", + "shortName": "DataSourcesService" + }, + "shortName": "CreateDataSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_datasources_v1beta.types.CreateDataSourceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "data_source", + "type": "google.shopping.merchant_datasources_v1beta.types.DataSource" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.shopping.merchant_datasources_v1beta.types.DataSource", + "shortName": "create_data_source" + }, + "description": "Sample for CreateDataSource", + "file": "merchantapi_v1beta_generated_data_sources_service_create_data_source_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_DataSourcesService_CreateDataSource_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_data_sources_service_create_data_source_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceClient", + "shortName": "DataSourcesServiceClient" + }, + "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceClient.create_data_source", + "method": { + "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService.CreateDataSource", + "service": { + "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", + "shortName": "DataSourcesService" + }, + "shortName": "CreateDataSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_datasources_v1beta.types.CreateDataSourceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "data_source", + "type": "google.shopping.merchant_datasources_v1beta.types.DataSource" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.shopping.merchant_datasources_v1beta.types.DataSource", + "shortName": "create_data_source" + }, + "description": "Sample for CreateDataSource", + "file": "merchantapi_v1beta_generated_data_sources_service_create_data_source_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_DataSourcesService_CreateDataSource_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_data_sources_service_create_data_source_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceAsyncClient", + "shortName": "DataSourcesServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceAsyncClient.delete_data_source", + "method": { + "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService.DeleteDataSource", + "service": { + "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", + "shortName": "DataSourcesService" + }, + "shortName": "DeleteDataSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_datasources_v1beta.types.DeleteDataSourceRequest" + }, + { + "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_data_source" + }, + "description": "Sample for DeleteDataSource", + "file": "merchantapi_v1beta_generated_data_sources_service_delete_data_source_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_DataSourcesService_DeleteDataSource_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_data_sources_service_delete_data_source_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceClient", + "shortName": "DataSourcesServiceClient" + }, + "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceClient.delete_data_source", + "method": { + "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService.DeleteDataSource", + "service": { + "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", + "shortName": "DataSourcesService" + }, + "shortName": "DeleteDataSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_datasources_v1beta.types.DeleteDataSourceRequest" + }, + { + "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_data_source" + }, + "description": "Sample for DeleteDataSource", + "file": "merchantapi_v1beta_generated_data_sources_service_delete_data_source_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_DataSourcesService_DeleteDataSource_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_data_sources_service_delete_data_source_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceAsyncClient", + "shortName": "DataSourcesServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceAsyncClient.fetch_data_source", + "method": { + "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService.FetchDataSource", + "service": { + "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", + "shortName": "DataSourcesService" + }, + "shortName": "FetchDataSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_datasources_v1beta.types.FetchDataSourceRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "fetch_data_source" + }, + "description": "Sample for FetchDataSource", + "file": "merchantapi_v1beta_generated_data_sources_service_fetch_data_source_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_DataSourcesService_FetchDataSource_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_data_sources_service_fetch_data_source_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceClient", + "shortName": "DataSourcesServiceClient" + }, + "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceClient.fetch_data_source", + "method": { + "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService.FetchDataSource", + "service": { + "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", + "shortName": "DataSourcesService" + }, + "shortName": "FetchDataSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_datasources_v1beta.types.FetchDataSourceRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "fetch_data_source" + }, + "description": "Sample for FetchDataSource", + "file": "merchantapi_v1beta_generated_data_sources_service_fetch_data_source_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_DataSourcesService_FetchDataSource_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_data_sources_service_fetch_data_source_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceAsyncClient", + "shortName": "DataSourcesServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceAsyncClient.get_data_source", + "method": { + "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService.GetDataSource", + "service": { + "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", + "shortName": "DataSourcesService" + }, + "shortName": "GetDataSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_datasources_v1beta.types.GetDataSourceRequest" + }, + { + "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_datasources_v1beta.types.DataSource", + "shortName": "get_data_source" + }, + "description": "Sample for GetDataSource", + "file": "merchantapi_v1beta_generated_data_sources_service_get_data_source_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_DataSourcesService_GetDataSource_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_data_sources_service_get_data_source_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceClient", + "shortName": "DataSourcesServiceClient" + }, + "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceClient.get_data_source", + "method": { + "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService.GetDataSource", + "service": { + "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", + "shortName": "DataSourcesService" + }, + "shortName": "GetDataSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_datasources_v1beta.types.GetDataSourceRequest" + }, + { + "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_datasources_v1beta.types.DataSource", + "shortName": "get_data_source" + }, + "description": "Sample for GetDataSource", + "file": "merchantapi_v1beta_generated_data_sources_service_get_data_source_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_DataSourcesService_GetDataSource_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_data_sources_service_get_data_source_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceAsyncClient", + "shortName": "DataSourcesServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceAsyncClient.list_data_sources", + "method": { + "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService.ListDataSources", + "service": { + "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", + "shortName": "DataSourcesService" + }, + "shortName": "ListDataSources" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_datasources_v1beta.types.ListDataSourcesRequest" + }, + { + "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_datasources_v1beta.services.data_sources_service.pagers.ListDataSourcesAsyncPager", + "shortName": "list_data_sources" + }, + "description": "Sample for ListDataSources", + "file": "merchantapi_v1beta_generated_data_sources_service_list_data_sources_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_DataSourcesService_ListDataSources_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_data_sources_service_list_data_sources_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceClient", + "shortName": "DataSourcesServiceClient" + }, + "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceClient.list_data_sources", + "method": { + "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService.ListDataSources", + "service": { + "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", + "shortName": "DataSourcesService" + }, + "shortName": "ListDataSources" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_datasources_v1beta.types.ListDataSourcesRequest" + }, + { + "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_datasources_v1beta.services.data_sources_service.pagers.ListDataSourcesPager", + "shortName": "list_data_sources" + }, + "description": "Sample for ListDataSources", + "file": "merchantapi_v1beta_generated_data_sources_service_list_data_sources_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_DataSourcesService_ListDataSources_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_data_sources_service_list_data_sources_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceAsyncClient", + "shortName": "DataSourcesServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceAsyncClient.update_data_source", + "method": { + "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService.UpdateDataSource", + "service": { + "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", + "shortName": "DataSourcesService" + }, + "shortName": "UpdateDataSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_datasources_v1beta.types.UpdateDataSourceRequest" + }, + { + "name": "data_source", + "type": "google.shopping.merchant_datasources_v1beta.types.DataSource" + }, + { + "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_datasources_v1beta.types.DataSource", + "shortName": "update_data_source" + }, + "description": "Sample for UpdateDataSource", + "file": "merchantapi_v1beta_generated_data_sources_service_update_data_source_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_DataSourcesService_UpdateDataSource_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_data_sources_service_update_data_source_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceClient", + "shortName": "DataSourcesServiceClient" + }, + "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceClient.update_data_source", + "method": { + "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService.UpdateDataSource", + "service": { + "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", + "shortName": "DataSourcesService" + }, + "shortName": "UpdateDataSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_datasources_v1beta.types.UpdateDataSourceRequest" + }, + { + "name": "data_source", + "type": "google.shopping.merchant_datasources_v1beta.types.DataSource" + }, + { + "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_datasources_v1beta.types.DataSource", + "shortName": "update_data_source" + }, + "description": "Sample for UpdateDataSource", + "file": "merchantapi_v1beta_generated_data_sources_service_update_data_source_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_DataSourcesService_UpdateDataSource_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_data_sources_service_update_data_source_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_datasources_v1beta.FileUploadsServiceAsyncClient", + "shortName": "FileUploadsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_datasources_v1beta.FileUploadsServiceAsyncClient.get_file_upload", + "method": { + "fullName": "google.shopping.merchant.datasources.v1beta.FileUploadsService.GetFileUpload", + "service": { + "fullName": "google.shopping.merchant.datasources.v1beta.FileUploadsService", + "shortName": "FileUploadsService" + }, + "shortName": "GetFileUpload" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_datasources_v1beta.types.GetFileUploadRequest" + }, + { + "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_datasources_v1beta.types.FileUpload", + "shortName": "get_file_upload" + }, + "description": "Sample for GetFileUpload", + "file": "merchantapi_v1beta_generated_file_uploads_service_get_file_upload_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_FileUploadsService_GetFileUpload_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_file_uploads_service_get_file_upload_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_datasources_v1beta.FileUploadsServiceClient", + "shortName": "FileUploadsServiceClient" + }, + "fullName": "google.shopping.merchant_datasources_v1beta.FileUploadsServiceClient.get_file_upload", + "method": { + "fullName": "google.shopping.merchant.datasources.v1beta.FileUploadsService.GetFileUpload", + "service": { + "fullName": "google.shopping.merchant.datasources.v1beta.FileUploadsService", + "shortName": "FileUploadsService" + }, + "shortName": "GetFileUpload" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_datasources_v1beta.types.GetFileUploadRequest" + }, + { + "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_datasources_v1beta.types.FileUpload", + "shortName": "get_file_upload" + }, + "description": "Sample for GetFileUpload", + "file": "merchantapi_v1beta_generated_file_uploads_service_get_file_upload_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_FileUploadsService_GetFileUpload_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_file_uploads_service_get_file_upload_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/scripts/fixup_merchant_datasources_v1beta_keywords.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/scripts/fixup_merchant_datasources_v1beta_keywords.py new file mode 100644 index 000000000000..74286e5cd17b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/scripts/fixup_merchant_datasources_v1beta_keywords.py @@ -0,0 +1,182 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_datasourcesCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_data_source': ('parent', 'data_source', ), + 'delete_data_source': ('name', ), + 'fetch_data_source': ('name', ), + 'get_data_source': ('name', ), + 'get_file_upload': ('name', ), + 'list_data_sources': ('parent', 'page_size', 'page_token', ), + 'update_data_source': ('data_source', '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_datasourcesCallTransformer(), +): + """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_datasources 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-datasources/v1beta/setup.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/setup.py new file mode 100644 index 000000000000..c13b7221f606 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/setup.py @@ -0,0 +1,98 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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-datasources' + + +description = "Google Shopping Merchant Datasources API client library" + +version = None + +with open(os.path.join(package_root, 'google/shopping/merchant_datasources/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.0dev,!=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.0dev,!=2.24.0,!=2.25.0", + "proto-plus >= 1.22.3, <2.0.0dev", + "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'", + "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", +] +extras = { +} +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-datasources" + +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-datasources/v1beta/testing/constraints-3.10.txt b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.10.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.11.txt b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.11.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.12.txt b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.12.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.13.txt b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.13.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.13.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.7.txt b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.7.txt new file mode 100644 index 000000000000..fc812592b0ee --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.7.txt @@ -0,0 +1,10 @@ +# 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.0dev", +# 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 diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.8.txt b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.8.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.9.txt b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.9.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/tests/__init__.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-datasources/v1beta/tests/unit/__init__.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-datasources/v1beta/tests/unit/gapic/__init__.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-datasources/v1beta/tests/unit/gapic/merchant_datasources_v1beta/__init__.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/tests/unit/gapic/merchant_datasources_v1beta/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/tests/unit/gapic/merchant_datasources_v1beta/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-datasources/v1beta/tests/unit/gapic/merchant_datasources_v1beta/test_data_sources_service.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/tests/unit/gapic/merchant_datasources_v1beta/test_data_sources_service.py new file mode 100644 index 000000000000..a7e154e0e990 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/tests/unit/gapic/merchant_datasources_v1beta/test_data_sources_service.py @@ -0,0 +1,5650 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_datasources_v1beta.services.data_sources_service import DataSourcesServiceAsyncClient +from google.shopping.merchant_datasources_v1beta.services.data_sources_service import DataSourcesServiceClient +from google.shopping.merchant_datasources_v1beta.services.data_sources_service import pagers +from google.shopping.merchant_datasources_v1beta.services.data_sources_service import transports +from google.shopping.merchant_datasources_v1beta.types import datasources +from google.shopping.merchant_datasources_v1beta.types import datasourcetypes +from google.shopping.merchant_datasources_v1beta.types import fileinputs +from google.type import dayofweek_pb2 # type: ignore +from google.type import timeofday_pb2 # type: ignore +import google.auth + + +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 DataSourcesServiceClient._get_default_mtls_endpoint(None) is None + assert DataSourcesServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert DataSourcesServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert DataSourcesServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert DataSourcesServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert DataSourcesServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert DataSourcesServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert DataSourcesServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert DataSourcesServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + DataSourcesServiceClient._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 DataSourcesServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert DataSourcesServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert DataSourcesServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + DataSourcesServiceClient._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 DataSourcesServiceClient._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 DataSourcesServiceClient._get_client_cert_source(None, False) is None + assert DataSourcesServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert DataSourcesServiceClient._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 DataSourcesServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert DataSourcesServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(DataSourcesServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DataSourcesServiceClient)) +@mock.patch.object(DataSourcesServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DataSourcesServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = DataSourcesServiceClient._DEFAULT_UNIVERSE + default_endpoint = DataSourcesServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = DataSourcesServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert DataSourcesServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert DataSourcesServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == DataSourcesServiceClient.DEFAULT_MTLS_ENDPOINT + assert DataSourcesServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert DataSourcesServiceClient._get_api_endpoint(None, None, default_universe, "always") == DataSourcesServiceClient.DEFAULT_MTLS_ENDPOINT + assert DataSourcesServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == DataSourcesServiceClient.DEFAULT_MTLS_ENDPOINT + assert DataSourcesServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert DataSourcesServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + DataSourcesServiceClient._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 DataSourcesServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert DataSourcesServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert DataSourcesServiceClient._get_universe_domain(None, None) == DataSourcesServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + DataSourcesServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize("client_class,transport_name", [ + (DataSourcesServiceClient, "grpc"), + (DataSourcesServiceAsyncClient, "grpc_asyncio"), + (DataSourcesServiceClient, "rest"), +]) +def test_data_sources_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.DataSourcesServiceGrpcTransport, "grpc"), + (transports.DataSourcesServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.DataSourcesServiceRestTransport, "rest"), +]) +def test_data_sources_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", [ + (DataSourcesServiceClient, "grpc"), + (DataSourcesServiceAsyncClient, "grpc_asyncio"), + (DataSourcesServiceClient, "rest"), +]) +def test_data_sources_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_data_sources_service_client_get_transport_class(): + transport = DataSourcesServiceClient.get_transport_class() + available_transports = [ + transports.DataSourcesServiceGrpcTransport, + transports.DataSourcesServiceRestTransport, + ] + assert transport in available_transports + + transport = DataSourcesServiceClient.get_transport_class("grpc") + assert transport == transports.DataSourcesServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DataSourcesServiceClient, transports.DataSourcesServiceGrpcTransport, "grpc"), + (DataSourcesServiceAsyncClient, transports.DataSourcesServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (DataSourcesServiceClient, transports.DataSourcesServiceRestTransport, "rest"), +]) +@mock.patch.object(DataSourcesServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DataSourcesServiceClient)) +@mock.patch.object(DataSourcesServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DataSourcesServiceAsyncClient)) +def test_data_sources_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(DataSourcesServiceClient, '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(DataSourcesServiceClient, '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", [ + (DataSourcesServiceClient, transports.DataSourcesServiceGrpcTransport, "grpc", "true"), + (DataSourcesServiceAsyncClient, transports.DataSourcesServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (DataSourcesServiceClient, transports.DataSourcesServiceGrpcTransport, "grpc", "false"), + (DataSourcesServiceAsyncClient, transports.DataSourcesServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (DataSourcesServiceClient, transports.DataSourcesServiceRestTransport, "rest", "true"), + (DataSourcesServiceClient, transports.DataSourcesServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(DataSourcesServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DataSourcesServiceClient)) +@mock.patch.object(DataSourcesServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DataSourcesServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_data_sources_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", [ + DataSourcesServiceClient, DataSourcesServiceAsyncClient +]) +@mock.patch.object(DataSourcesServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataSourcesServiceClient)) +@mock.patch.object(DataSourcesServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataSourcesServiceAsyncClient)) +def test_data_sources_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", [ + DataSourcesServiceClient, DataSourcesServiceAsyncClient +]) +@mock.patch.object(DataSourcesServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DataSourcesServiceClient)) +@mock.patch.object(DataSourcesServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DataSourcesServiceAsyncClient)) +def test_data_sources_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = DataSourcesServiceClient._DEFAULT_UNIVERSE + default_endpoint = DataSourcesServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = DataSourcesServiceClient._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", [ + (DataSourcesServiceClient, transports.DataSourcesServiceGrpcTransport, "grpc"), + (DataSourcesServiceAsyncClient, transports.DataSourcesServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (DataSourcesServiceClient, transports.DataSourcesServiceRestTransport, "rest"), +]) +def test_data_sources_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", [ + (DataSourcesServiceClient, transports.DataSourcesServiceGrpcTransport, "grpc", grpc_helpers), + (DataSourcesServiceAsyncClient, transports.DataSourcesServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (DataSourcesServiceClient, transports.DataSourcesServiceRestTransport, "rest", None), +]) +def test_data_sources_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_data_sources_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_datasources_v1beta.services.data_sources_service.transports.DataSourcesServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = DataSourcesServiceClient( + 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", [ + (DataSourcesServiceClient, transports.DataSourcesServiceGrpcTransport, "grpc", grpc_helpers), + (DataSourcesServiceAsyncClient, transports.DataSourcesServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_data_sources_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", [ + datasources.GetDataSourceRequest, + dict, +]) +def test_get_data_source(request_type, transport: str = 'grpc'): + client = DataSourcesServiceClient( + 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_data_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datasources.DataSource( + name='name_value', + data_source_id=1462, + display_name='display_name_value', + input=datasources.DataSource.Input.API, + ) + response = client.get_data_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = datasources.GetDataSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, datasources.DataSource) + assert response.name == 'name_value' + assert response.data_source_id == 1462 + assert response.display_name == 'display_name_value' + assert response.input == datasources.DataSource.Input.API + + +def test_get_data_source_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 = DataSourcesServiceClient( + 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 = datasources.GetDataSourceRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_data_source(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datasources.GetDataSourceRequest( + name='name_value', + ) + +def test_get_data_source_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DataSourcesServiceClient( + 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_data_source in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_data_source] = mock_rpc + request = {} + client.get_data_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_data_source(request) + + # Establish that a new wrapper 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_data_source_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = DataSourcesServiceAsyncClient( + 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_data_source in client._client._transport._wrapped_methods + + # 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_data_source] = mock_rpc + + request = {} + await client.get_data_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_data_source(request) + + # Establish that a new wrapper 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_data_source_async(transport: str = 'grpc_asyncio', request_type=datasources.GetDataSourceRequest): + client = DataSourcesServiceAsyncClient( + 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_data_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datasources.DataSource( + name='name_value', + data_source_id=1462, + display_name='display_name_value', + input=datasources.DataSource.Input.API, + )) + response = await client.get_data_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = datasources.GetDataSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, datasources.DataSource) + assert response.name == 'name_value' + assert response.data_source_id == 1462 + assert response.display_name == 'display_name_value' + assert response.input == datasources.DataSource.Input.API + + +@pytest.mark.asyncio +async def test_get_data_source_async_from_dict(): + await test_get_data_source_async(request_type=dict) + +def test_get_data_source_field_headers(): + client = DataSourcesServiceClient( + 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 = datasources.GetDataSourceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_source), + '__call__') as call: + call.return_value = datasources.DataSource() + client.get_data_source(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_data_source_field_headers_async(): + client = DataSourcesServiceAsyncClient( + 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 = datasources.GetDataSourceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datasources.DataSource()) + await client.get_data_source(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_data_source_flattened(): + client = DataSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datasources.DataSource() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_data_source( + 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_data_source_flattened_error(): + client = DataSourcesServiceClient( + 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_data_source( + datasources.GetDataSourceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_data_source_flattened_async(): + client = DataSourcesServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datasources.DataSource() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datasources.DataSource()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_data_source( + 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_data_source_flattened_error_async(): + client = DataSourcesServiceAsyncClient( + 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_data_source( + datasources.GetDataSourceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + datasources.ListDataSourcesRequest, + dict, +]) +def test_list_data_sources(request_type, transport: str = 'grpc'): + client = DataSourcesServiceClient( + 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_data_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datasources.ListDataSourcesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_data_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = datasources.ListDataSourcesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDataSourcesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_data_sources_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 = DataSourcesServiceClient( + 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 = datasources.ListDataSourcesRequest( + 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_data_sources), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_data_sources(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datasources.ListDataSourcesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_data_sources_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DataSourcesServiceClient( + 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_data_sources in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_data_sources] = mock_rpc + request = {} + client.list_data_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_data_sources(request) + + # Establish that a new wrapper 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_data_sources_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = DataSourcesServiceAsyncClient( + 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_data_sources in client._client._transport._wrapped_methods + + # 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_data_sources] = mock_rpc + + request = {} + await client.list_data_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_data_sources(request) + + # Establish that a new wrapper 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_data_sources_async(transport: str = 'grpc_asyncio', request_type=datasources.ListDataSourcesRequest): + client = DataSourcesServiceAsyncClient( + 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_data_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datasources.ListDataSourcesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_data_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = datasources.ListDataSourcesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDataSourcesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_data_sources_async_from_dict(): + await test_list_data_sources_async(request_type=dict) + +def test_list_data_sources_field_headers(): + client = DataSourcesServiceClient( + 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 = datasources.ListDataSourcesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_sources), + '__call__') as call: + call.return_value = datasources.ListDataSourcesResponse() + client.list_data_sources(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_data_sources_field_headers_async(): + client = DataSourcesServiceAsyncClient( + 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 = datasources.ListDataSourcesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_sources), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datasources.ListDataSourcesResponse()) + await client.list_data_sources(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_data_sources_flattened(): + client = DataSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datasources.ListDataSourcesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_data_sources( + 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_data_sources_flattened_error(): + client = DataSourcesServiceClient( + 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_data_sources( + datasources.ListDataSourcesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_data_sources_flattened_async(): + client = DataSourcesServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datasources.ListDataSourcesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datasources.ListDataSourcesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_data_sources( + 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_data_sources_flattened_error_async(): + client = DataSourcesServiceAsyncClient( + 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_data_sources( + datasources.ListDataSourcesRequest(), + parent='parent_value', + ) + + +def test_list_data_sources_pager(transport_name: str = "grpc"): + client = DataSourcesServiceClient( + 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_data_sources), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + datasources.ListDataSourcesResponse( + data_sources=[ + datasources.DataSource(), + datasources.DataSource(), + datasources.DataSource(), + ], + next_page_token='abc', + ), + datasources.ListDataSourcesResponse( + data_sources=[], + next_page_token='def', + ), + datasources.ListDataSourcesResponse( + data_sources=[ + datasources.DataSource(), + ], + next_page_token='ghi', + ), + datasources.ListDataSourcesResponse( + data_sources=[ + datasources.DataSource(), + datasources.DataSource(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_data_sources(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, datasources.DataSource) + for i in results) +def test_list_data_sources_pages(transport_name: str = "grpc"): + client = DataSourcesServiceClient( + 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_data_sources), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + datasources.ListDataSourcesResponse( + data_sources=[ + datasources.DataSource(), + datasources.DataSource(), + datasources.DataSource(), + ], + next_page_token='abc', + ), + datasources.ListDataSourcesResponse( + data_sources=[], + next_page_token='def', + ), + datasources.ListDataSourcesResponse( + data_sources=[ + datasources.DataSource(), + ], + next_page_token='ghi', + ), + datasources.ListDataSourcesResponse( + data_sources=[ + datasources.DataSource(), + datasources.DataSource(), + ], + ), + RuntimeError, + ) + pages = list(client.list_data_sources(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_data_sources_async_pager(): + client = DataSourcesServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_sources), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + datasources.ListDataSourcesResponse( + data_sources=[ + datasources.DataSource(), + datasources.DataSource(), + datasources.DataSource(), + ], + next_page_token='abc', + ), + datasources.ListDataSourcesResponse( + data_sources=[], + next_page_token='def', + ), + datasources.ListDataSourcesResponse( + data_sources=[ + datasources.DataSource(), + ], + next_page_token='ghi', + ), + datasources.ListDataSourcesResponse( + data_sources=[ + datasources.DataSource(), + datasources.DataSource(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_data_sources(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, datasources.DataSource) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_data_sources_async_pages(): + client = DataSourcesServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_sources), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + datasources.ListDataSourcesResponse( + data_sources=[ + datasources.DataSource(), + datasources.DataSource(), + datasources.DataSource(), + ], + next_page_token='abc', + ), + datasources.ListDataSourcesResponse( + data_sources=[], + next_page_token='def', + ), + datasources.ListDataSourcesResponse( + data_sources=[ + datasources.DataSource(), + ], + next_page_token='ghi', + ), + datasources.ListDataSourcesResponse( + data_sources=[ + datasources.DataSource(), + datasources.DataSource(), + ], + ), + 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_data_sources(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", [ + datasources.CreateDataSourceRequest, + dict, +]) +def test_create_data_source(request_type, transport: str = 'grpc'): + client = DataSourcesServiceClient( + 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_data_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datasources.DataSource( + name='name_value', + data_source_id=1462, + display_name='display_name_value', + input=datasources.DataSource.Input.API, + ) + response = client.create_data_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = datasources.CreateDataSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, datasources.DataSource) + assert response.name == 'name_value' + assert response.data_source_id == 1462 + assert response.display_name == 'display_name_value' + assert response.input == datasources.DataSource.Input.API + + +def test_create_data_source_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 = DataSourcesServiceClient( + 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 = datasources.CreateDataSourceRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_data_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_data_source(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datasources.CreateDataSourceRequest( + parent='parent_value', + ) + +def test_create_data_source_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DataSourcesServiceClient( + 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_data_source in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_data_source] = mock_rpc + request = {} + client.create_data_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_data_source(request) + + # Establish that a new wrapper 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_data_source_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = DataSourcesServiceAsyncClient( + 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_data_source in client._client._transport._wrapped_methods + + # 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_data_source] = mock_rpc + + request = {} + await client.create_data_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_data_source(request) + + # Establish that a new wrapper 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_data_source_async(transport: str = 'grpc_asyncio', request_type=datasources.CreateDataSourceRequest): + client = DataSourcesServiceAsyncClient( + 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_data_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datasources.DataSource( + name='name_value', + data_source_id=1462, + display_name='display_name_value', + input=datasources.DataSource.Input.API, + )) + response = await client.create_data_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = datasources.CreateDataSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, datasources.DataSource) + assert response.name == 'name_value' + assert response.data_source_id == 1462 + assert response.display_name == 'display_name_value' + assert response.input == datasources.DataSource.Input.API + + +@pytest.mark.asyncio +async def test_create_data_source_async_from_dict(): + await test_create_data_source_async(request_type=dict) + +def test_create_data_source_field_headers(): + client = DataSourcesServiceClient( + 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 = datasources.CreateDataSourceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_data_source), + '__call__') as call: + call.return_value = datasources.DataSource() + client.create_data_source(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_data_source_field_headers_async(): + client = DataSourcesServiceAsyncClient( + 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 = datasources.CreateDataSourceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_data_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datasources.DataSource()) + await client.create_data_source(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_data_source_flattened(): + client = DataSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_data_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datasources.DataSource() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_data_source( + parent='parent_value', + data_source=datasources.DataSource(primary_product_data_source=datasourcetypes.PrimaryProductDataSource(channel=datasourcetypes.PrimaryProductDataSource.Channel.ONLINE_PRODUCTS)), + ) + + # 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].data_source + mock_val = datasources.DataSource(primary_product_data_source=datasourcetypes.PrimaryProductDataSource(channel=datasourcetypes.PrimaryProductDataSource.Channel.ONLINE_PRODUCTS)) + assert arg == mock_val + + +def test_create_data_source_flattened_error(): + client = DataSourcesServiceClient( + 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_data_source( + datasources.CreateDataSourceRequest(), + parent='parent_value', + data_source=datasources.DataSource(primary_product_data_source=datasourcetypes.PrimaryProductDataSource(channel=datasourcetypes.PrimaryProductDataSource.Channel.ONLINE_PRODUCTS)), + ) + +@pytest.mark.asyncio +async def test_create_data_source_flattened_async(): + client = DataSourcesServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_data_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datasources.DataSource() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datasources.DataSource()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_data_source( + parent='parent_value', + data_source=datasources.DataSource(primary_product_data_source=datasourcetypes.PrimaryProductDataSource(channel=datasourcetypes.PrimaryProductDataSource.Channel.ONLINE_PRODUCTS)), + ) + + # 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].data_source + mock_val = datasources.DataSource(primary_product_data_source=datasourcetypes.PrimaryProductDataSource(channel=datasourcetypes.PrimaryProductDataSource.Channel.ONLINE_PRODUCTS)) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_data_source_flattened_error_async(): + client = DataSourcesServiceAsyncClient( + 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_data_source( + datasources.CreateDataSourceRequest(), + parent='parent_value', + data_source=datasources.DataSource(primary_product_data_source=datasourcetypes.PrimaryProductDataSource(channel=datasourcetypes.PrimaryProductDataSource.Channel.ONLINE_PRODUCTS)), + ) + + +@pytest.mark.parametrize("request_type", [ + datasources.UpdateDataSourceRequest, + dict, +]) +def test_update_data_source(request_type, transport: str = 'grpc'): + client = DataSourcesServiceClient( + 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_data_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datasources.DataSource( + name='name_value', + data_source_id=1462, + display_name='display_name_value', + input=datasources.DataSource.Input.API, + ) + response = client.update_data_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = datasources.UpdateDataSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, datasources.DataSource) + assert response.name == 'name_value' + assert response.data_source_id == 1462 + assert response.display_name == 'display_name_value' + assert response.input == datasources.DataSource.Input.API + + +def test_update_data_source_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 = DataSourcesServiceClient( + 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 = datasources.UpdateDataSourceRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_data_source(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datasources.UpdateDataSourceRequest( + ) + +def test_update_data_source_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DataSourcesServiceClient( + 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_data_source in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_data_source] = mock_rpc + request = {} + client.update_data_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_data_source(request) + + # Establish that a new wrapper 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_data_source_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = DataSourcesServiceAsyncClient( + 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_data_source in client._client._transport._wrapped_methods + + # 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_data_source] = mock_rpc + + request = {} + await client.update_data_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_data_source(request) + + # Establish that a new wrapper 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_data_source_async(transport: str = 'grpc_asyncio', request_type=datasources.UpdateDataSourceRequest): + client = DataSourcesServiceAsyncClient( + 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_data_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datasources.DataSource( + name='name_value', + data_source_id=1462, + display_name='display_name_value', + input=datasources.DataSource.Input.API, + )) + response = await client.update_data_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = datasources.UpdateDataSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, datasources.DataSource) + assert response.name == 'name_value' + assert response.data_source_id == 1462 + assert response.display_name == 'display_name_value' + assert response.input == datasources.DataSource.Input.API + + +@pytest.mark.asyncio +async def test_update_data_source_async_from_dict(): + await test_update_data_source_async(request_type=dict) + +def test_update_data_source_field_headers(): + client = DataSourcesServiceClient( + 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 = datasources.UpdateDataSourceRequest() + + request.data_source.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_source), + '__call__') as call: + call.return_value = datasources.DataSource() + client.update_data_source(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', + 'data_source.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_data_source_field_headers_async(): + client = DataSourcesServiceAsyncClient( + 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 = datasources.UpdateDataSourceRequest() + + request.data_source.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datasources.DataSource()) + await client.update_data_source(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', + 'data_source.name=name_value', + ) in kw['metadata'] + + +def test_update_data_source_flattened(): + client = DataSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datasources.DataSource() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_data_source( + data_source=datasources.DataSource(primary_product_data_source=datasourcetypes.PrimaryProductDataSource(channel=datasourcetypes.PrimaryProductDataSource.Channel.ONLINE_PRODUCTS)), + 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].data_source + mock_val = datasources.DataSource(primary_product_data_source=datasourcetypes.PrimaryProductDataSource(channel=datasourcetypes.PrimaryProductDataSource.Channel.ONLINE_PRODUCTS)) + 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_data_source_flattened_error(): + client = DataSourcesServiceClient( + 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_data_source( + datasources.UpdateDataSourceRequest(), + data_source=datasources.DataSource(primary_product_data_source=datasourcetypes.PrimaryProductDataSource(channel=datasourcetypes.PrimaryProductDataSource.Channel.ONLINE_PRODUCTS)), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_data_source_flattened_async(): + client = DataSourcesServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datasources.DataSource() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datasources.DataSource()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_data_source( + data_source=datasources.DataSource(primary_product_data_source=datasourcetypes.PrimaryProductDataSource(channel=datasourcetypes.PrimaryProductDataSource.Channel.ONLINE_PRODUCTS)), + 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].data_source + mock_val = datasources.DataSource(primary_product_data_source=datasourcetypes.PrimaryProductDataSource(channel=datasourcetypes.PrimaryProductDataSource.Channel.ONLINE_PRODUCTS)) + 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_data_source_flattened_error_async(): + client = DataSourcesServiceAsyncClient( + 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_data_source( + datasources.UpdateDataSourceRequest(), + data_source=datasources.DataSource(primary_product_data_source=datasourcetypes.PrimaryProductDataSource(channel=datasourcetypes.PrimaryProductDataSource.Channel.ONLINE_PRODUCTS)), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + datasources.DeleteDataSourceRequest, + dict, +]) +def test_delete_data_source(request_type, transport: str = 'grpc'): + client = DataSourcesServiceClient( + 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_data_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_data_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = datasources.DeleteDataSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_data_source_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 = DataSourcesServiceClient( + 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 = datasources.DeleteDataSourceRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_data_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_data_source(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datasources.DeleteDataSourceRequest( + name='name_value', + ) + +def test_delete_data_source_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DataSourcesServiceClient( + 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_data_source in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_data_source] = mock_rpc + request = {} + client.delete_data_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_data_source(request) + + # Establish that a new wrapper 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_data_source_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = DataSourcesServiceAsyncClient( + 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_data_source in client._client._transport._wrapped_methods + + # 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_data_source] = mock_rpc + + request = {} + await client.delete_data_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_data_source(request) + + # Establish that a new wrapper 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_data_source_async(transport: str = 'grpc_asyncio', request_type=datasources.DeleteDataSourceRequest): + client = DataSourcesServiceAsyncClient( + 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_data_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_data_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = datasources.DeleteDataSourceRequest() + 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_data_source_async_from_dict(): + await test_delete_data_source_async(request_type=dict) + +def test_delete_data_source_field_headers(): + client = DataSourcesServiceClient( + 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 = datasources.DeleteDataSourceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_data_source), + '__call__') as call: + call.return_value = None + client.delete_data_source(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_data_source_field_headers_async(): + client = DataSourcesServiceAsyncClient( + 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 = datasources.DeleteDataSourceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_data_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_data_source(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_data_source_flattened(): + client = DataSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_data_source), + '__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_data_source( + 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_data_source_flattened_error(): + client = DataSourcesServiceClient( + 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_data_source( + datasources.DeleteDataSourceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_data_source_flattened_async(): + client = DataSourcesServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_data_source), + '__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_data_source( + 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_data_source_flattened_error_async(): + client = DataSourcesServiceAsyncClient( + 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_data_source( + datasources.DeleteDataSourceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + datasources.FetchDataSourceRequest, + dict, +]) +def test_fetch_data_source(request_type, transport: str = 'grpc'): + client = DataSourcesServiceClient( + 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.fetch_data_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.fetch_data_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = datasources.FetchDataSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_fetch_data_source_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 = DataSourcesServiceClient( + 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 = datasources.FetchDataSourceRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_data_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.fetch_data_source(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datasources.FetchDataSourceRequest( + name='name_value', + ) + +def test_fetch_data_source_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DataSourcesServiceClient( + 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.fetch_data_source in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.fetch_data_source] = mock_rpc + request = {} + client.fetch_data_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.fetch_data_source(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_fetch_data_source_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = DataSourcesServiceAsyncClient( + 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.fetch_data_source in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.fetch_data_source] = mock_rpc + + request = {} + await client.fetch_data_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.fetch_data_source(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_fetch_data_source_async(transport: str = 'grpc_asyncio', request_type=datasources.FetchDataSourceRequest): + client = DataSourcesServiceAsyncClient( + 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.fetch_data_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.fetch_data_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = datasources.FetchDataSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_fetch_data_source_async_from_dict(): + await test_fetch_data_source_async(request_type=dict) + +def test_fetch_data_source_field_headers(): + client = DataSourcesServiceClient( + 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 = datasources.FetchDataSourceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_data_source), + '__call__') as call: + call.return_value = None + client.fetch_data_source(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_fetch_data_source_field_headers_async(): + client = DataSourcesServiceAsyncClient( + 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 = datasources.FetchDataSourceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_data_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.fetch_data_source(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_data_source_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 = DataSourcesServiceClient( + 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_data_source in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_data_source] = mock_rpc + + request = {} + client.get_data_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_data_source(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_data_source_rest_required_fields(request_type=datasources.GetDataSourceRequest): + transport_class = transports.DataSourcesServiceRestTransport + + 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_data_source._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_data_source._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 = DataSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = datasources.DataSource() + # 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 = datasources.DataSource.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_data_source(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_data_source_rest_unset_required_fields(): + transport = transports.DataSourcesServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_data_source._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_data_source_rest_flattened(): + client = DataSourcesServiceClient( + 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 = datasources.DataSource() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/dataSources/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 = datasources.DataSource.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_data_source(**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/datasources/v1beta/{name=accounts/*/dataSources/*}" % client.transport._host, args[1]) + + +def test_get_data_source_rest_flattened_error(transport: str = 'rest'): + client = DataSourcesServiceClient( + 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_data_source( + datasources.GetDataSourceRequest(), + name='name_value', + ) + + +def test_list_data_sources_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 = DataSourcesServiceClient( + 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_data_sources in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_data_sources] = mock_rpc + + request = {} + client.list_data_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_data_sources(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_data_sources_rest_required_fields(request_type=datasources.ListDataSourcesRequest): + transport_class = transports.DataSourcesServiceRestTransport + + 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_data_sources._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_data_sources._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 = DataSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = datasources.ListDataSourcesResponse() + # 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 = datasources.ListDataSourcesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_data_sources(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_data_sources_rest_unset_required_fields(): + transport = transports.DataSourcesServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_data_sources._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_data_sources_rest_flattened(): + client = DataSourcesServiceClient( + 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 = datasources.ListDataSourcesResponse() + + # 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 = datasources.ListDataSourcesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_data_sources(**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/datasources/v1beta/{parent=accounts/*}/dataSources" % client.transport._host, args[1]) + + +def test_list_data_sources_rest_flattened_error(transport: str = 'rest'): + client = DataSourcesServiceClient( + 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_data_sources( + datasources.ListDataSourcesRequest(), + parent='parent_value', + ) + + +def test_list_data_sources_rest_pager(transport: str = 'rest'): + client = DataSourcesServiceClient( + 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 = ( + datasources.ListDataSourcesResponse( + data_sources=[ + datasources.DataSource(), + datasources.DataSource(), + datasources.DataSource(), + ], + next_page_token='abc', + ), + datasources.ListDataSourcesResponse( + data_sources=[], + next_page_token='def', + ), + datasources.ListDataSourcesResponse( + data_sources=[ + datasources.DataSource(), + ], + next_page_token='ghi', + ), + datasources.ListDataSourcesResponse( + data_sources=[ + datasources.DataSource(), + datasources.DataSource(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(datasources.ListDataSourcesResponse.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_data_sources(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, datasources.DataSource) + for i in results) + + pages = list(client.list_data_sources(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_create_data_source_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 = DataSourcesServiceClient( + 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_data_source in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_data_source] = mock_rpc + + request = {} + client.create_data_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_data_source(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_data_source_rest_required_fields(request_type=datasources.CreateDataSourceRequest): + transport_class = transports.DataSourcesServiceRestTransport + + 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_data_source._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_data_source._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 = DataSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = datasources.DataSource() + # 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 = datasources.DataSource.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_data_source(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_data_source_rest_unset_required_fields(): + transport = transports.DataSourcesServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_data_source._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "dataSource", ))) + + +def test_create_data_source_rest_flattened(): + client = DataSourcesServiceClient( + 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 = datasources.DataSource() + + # 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', + data_source=datasources.DataSource(primary_product_data_source=datasourcetypes.PrimaryProductDataSource(channel=datasourcetypes.PrimaryProductDataSource.Channel.ONLINE_PRODUCTS)), + ) + 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 = datasources.DataSource.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_data_source(**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/datasources/v1beta/{parent=accounts/*}/dataSources" % client.transport._host, args[1]) + + +def test_create_data_source_rest_flattened_error(transport: str = 'rest'): + client = DataSourcesServiceClient( + 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_data_source( + datasources.CreateDataSourceRequest(), + parent='parent_value', + data_source=datasources.DataSource(primary_product_data_source=datasourcetypes.PrimaryProductDataSource(channel=datasourcetypes.PrimaryProductDataSource.Channel.ONLINE_PRODUCTS)), + ) + + +def test_update_data_source_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 = DataSourcesServiceClient( + 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_data_source in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_data_source] = mock_rpc + + request = {} + client.update_data_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_data_source(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_data_source_rest_required_fields(request_type=datasources.UpdateDataSourceRequest): + transport_class = transports.DataSourcesServiceRestTransport + + 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_data_source._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_data_source._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 = DataSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = datasources.DataSource() + # 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 = datasources.DataSource.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_data_source(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_data_source_rest_unset_required_fields(): + transport = transports.DataSourcesServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_data_source._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("dataSource", "updateMask", ))) + + +def test_update_data_source_rest_flattened(): + client = DataSourcesServiceClient( + 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 = datasources.DataSource() + + # get arguments that satisfy an http rule for this method + sample_request = {'data_source': {'name': 'accounts/sample1/dataSources/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + data_source=datasources.DataSource(primary_product_data_source=datasourcetypes.PrimaryProductDataSource(channel=datasourcetypes.PrimaryProductDataSource.Channel.ONLINE_PRODUCTS)), + 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 = datasources.DataSource.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_data_source(**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/datasources/v1beta/{data_source.name=accounts/*/dataSources/*}" % client.transport._host, args[1]) + + +def test_update_data_source_rest_flattened_error(transport: str = 'rest'): + client = DataSourcesServiceClient( + 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_data_source( + datasources.UpdateDataSourceRequest(), + data_source=datasources.DataSource(primary_product_data_source=datasourcetypes.PrimaryProductDataSource(channel=datasourcetypes.PrimaryProductDataSource.Channel.ONLINE_PRODUCTS)), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_data_source_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 = DataSourcesServiceClient( + 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_data_source in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_data_source] = mock_rpc + + request = {} + client.delete_data_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_data_source(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_data_source_rest_required_fields(request_type=datasources.DeleteDataSourceRequest): + transport_class = transports.DataSourcesServiceRestTransport + + 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_data_source._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_data_source._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 = DataSourcesServiceClient( + 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_data_source(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_data_source_rest_unset_required_fields(): + transport = transports.DataSourcesServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_data_source._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_delete_data_source_rest_flattened(): + client = DataSourcesServiceClient( + 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/dataSources/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_data_source(**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/datasources/v1beta/{name=accounts/*/dataSources/*}" % client.transport._host, args[1]) + + +def test_delete_data_source_rest_flattened_error(transport: str = 'rest'): + client = DataSourcesServiceClient( + 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_data_source( + datasources.DeleteDataSourceRequest(), + name='name_value', + ) + + +def test_fetch_data_source_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 = DataSourcesServiceClient( + 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.fetch_data_source in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.fetch_data_source] = mock_rpc + + request = {} + client.fetch_data_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.fetch_data_source(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_fetch_data_source_rest_required_fields(request_type=datasources.FetchDataSourceRequest): + transport_class = transports.DataSourcesServiceRestTransport + + 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()).fetch_data_source._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()).fetch_data_source._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 = DataSourcesServiceClient( + 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.fetch_data_source(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_fetch_data_source_rest_unset_required_fields(): + transport = transports.DataSourcesServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.fetch_data_source._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.DataSourcesServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DataSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.DataSourcesServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DataSourcesServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.DataSourcesServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = DataSourcesServiceClient( + 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 = DataSourcesServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.DataSourcesServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DataSourcesServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.DataSourcesServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = DataSourcesServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.DataSourcesServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.DataSourcesServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.DataSourcesServiceGrpcTransport, + transports.DataSourcesServiceGrpcAsyncIOTransport, + transports.DataSourcesServiceRestTransport, +]) +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 = DataSourcesServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = DataSourcesServiceClient( + 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_data_source_empty_call_grpc(): + client = DataSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_data_source), + '__call__') as call: + call.return_value = datasources.DataSource() + client.get_data_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = datasources.GetDataSourceRequest() + + assert args[0] == request_msg + + +# This 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_data_sources_empty_call_grpc(): + client = DataSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_data_sources), + '__call__') as call: + call.return_value = datasources.ListDataSourcesResponse() + client.list_data_sources(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = datasources.ListDataSourcesRequest() + + assert args[0] == request_msg + + +# This 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_data_source_empty_call_grpc(): + client = DataSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_data_source), + '__call__') as call: + call.return_value = datasources.DataSource() + client.create_data_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = datasources.CreateDataSourceRequest() + + assert args[0] == request_msg + + +# This 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_data_source_empty_call_grpc(): + client = DataSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_data_source), + '__call__') as call: + call.return_value = datasources.DataSource() + client.update_data_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = datasources.UpdateDataSourceRequest() + + assert args[0] == request_msg + + +# This 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_data_source_empty_call_grpc(): + client = DataSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_data_source), + '__call__') as call: + call.return_value = None + client.delete_data_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = datasources.DeleteDataSourceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_fetch_data_source_empty_call_grpc(): + client = DataSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_data_source), + '__call__') as call: + call.return_value = None + client.fetch_data_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = datasources.FetchDataSourceRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = DataSourcesServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = DataSourcesServiceAsyncClient( + 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_data_source_empty_call_grpc_asyncio(): + client = DataSourcesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_data_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datasources.DataSource( + name='name_value', + data_source_id=1462, + display_name='display_name_value', + input=datasources.DataSource.Input.API, + )) + await client.get_data_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = datasources.GetDataSourceRequest() + + assert args[0] == request_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_data_sources_empty_call_grpc_asyncio(): + client = DataSourcesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_data_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datasources.ListDataSourcesResponse( + next_page_token='next_page_token_value', + )) + await client.list_data_sources(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = datasources.ListDataSourcesRequest() + + assert args[0] == request_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_data_source_empty_call_grpc_asyncio(): + client = DataSourcesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_data_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datasources.DataSource( + name='name_value', + data_source_id=1462, + display_name='display_name_value', + input=datasources.DataSource.Input.API, + )) + await client.create_data_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = datasources.CreateDataSourceRequest() + + assert args[0] == request_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_data_source_empty_call_grpc_asyncio(): + client = DataSourcesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_data_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datasources.DataSource( + name='name_value', + data_source_id=1462, + display_name='display_name_value', + input=datasources.DataSource.Input.API, + )) + await client.update_data_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = datasources.UpdateDataSourceRequest() + + assert args[0] == request_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_data_source_empty_call_grpc_asyncio(): + client = DataSourcesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_data_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_data_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = datasources.DeleteDataSourceRequest() + + assert args[0] == request_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_fetch_data_source_empty_call_grpc_asyncio(): + client = DataSourcesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_data_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.fetch_data_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = datasources.FetchDataSourceRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = DataSourcesServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_data_source_rest_bad_request(request_type=datasources.GetDataSourceRequest): + client = DataSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/dataSources/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_data_source(request) + + +@pytest.mark.parametrize("request_type", [ + datasources.GetDataSourceRequest, + dict, +]) +def test_get_data_source_rest_call_success(request_type): + client = DataSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/dataSources/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 = datasources.DataSource( + name='name_value', + data_source_id=1462, + display_name='display_name_value', + input=datasources.DataSource.Input.API, + ) + + # 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 = datasources.DataSource.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_data_source(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, datasources.DataSource) + assert response.name == 'name_value' + assert response.data_source_id == 1462 + assert response.display_name == 'display_name_value' + assert response.input == datasources.DataSource.Input.API + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_data_source_rest_interceptors(null_interceptor): + transport = transports.DataSourcesServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataSourcesServiceRestInterceptor(), + ) + client = DataSourcesServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DataSourcesServiceRestInterceptor, "post_get_data_source") as post, \ + mock.patch.object(transports.DataSourcesServiceRestInterceptor, "pre_get_data_source") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = datasources.GetDataSourceRequest.pb(datasources.GetDataSourceRequest()) + 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 = datasources.DataSource.to_json(datasources.DataSource()) + req.return_value.content = return_value + + request = datasources.GetDataSourceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = datasources.DataSource() + + client.get_data_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_data_sources_rest_bad_request(request_type=datasources.ListDataSourcesRequest): + client = DataSourcesServiceClient( + 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_data_sources(request) + + +@pytest.mark.parametrize("request_type", [ + datasources.ListDataSourcesRequest, + dict, +]) +def test_list_data_sources_rest_call_success(request_type): + client = DataSourcesServiceClient( + 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 = datasources.ListDataSourcesResponse( + 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 = datasources.ListDataSourcesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_data_sources(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDataSourcesPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_data_sources_rest_interceptors(null_interceptor): + transport = transports.DataSourcesServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataSourcesServiceRestInterceptor(), + ) + client = DataSourcesServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DataSourcesServiceRestInterceptor, "post_list_data_sources") as post, \ + mock.patch.object(transports.DataSourcesServiceRestInterceptor, "pre_list_data_sources") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = datasources.ListDataSourcesRequest.pb(datasources.ListDataSourcesRequest()) + 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 = datasources.ListDataSourcesResponse.to_json(datasources.ListDataSourcesResponse()) + req.return_value.content = return_value + + request = datasources.ListDataSourcesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = datasources.ListDataSourcesResponse() + + client.list_data_sources(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_data_source_rest_bad_request(request_type=datasources.CreateDataSourceRequest): + client = DataSourcesServiceClient( + 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_data_source(request) + + +@pytest.mark.parametrize("request_type", [ + datasources.CreateDataSourceRequest, + dict, +]) +def test_create_data_source_rest_call_success(request_type): + client = DataSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + request_init["data_source"] = {'primary_product_data_source': {'channel': 1, 'feed_label': 'feed_label_value', 'content_language': 'content_language_value', 'countries': ['countries_value1', 'countries_value2'], 'default_rule': {'take_from_data_sources': [{'self_': True, 'primary_data_source_name': 'primary_data_source_name_value', 'supplemental_data_source_name': 'supplemental_data_source_name_value'}]}}, 'supplemental_product_data_source': {'feed_label': 'feed_label_value', 'content_language': 'content_language_value', 'referencing_primary_data_sources': {}}, 'local_inventory_data_source': {'feed_label': 'feed_label_value', 'content_language': 'content_language_value'}, 'regional_inventory_data_source': {'feed_label': 'feed_label_value', 'content_language': 'content_language_value'}, 'promotion_data_source': {'target_country': 'target_country_value', 'content_language': 'content_language_value'}, 'name': 'name_value', 'data_source_id': 1462, 'display_name': 'display_name_value', 'input': 1, 'file_input': {'fetch_settings': {'enabled': True, 'day_of_month': 1271, 'time_of_day': {'hours': 561, 'minutes': 773, 'seconds': 751, 'nanos': 543}, 'day_of_week': 1, 'time_zone': 'time_zone_value', 'frequency': 1, 'fetch_uri': 'fetch_uri_value', 'username': 'username_value', 'password': 'password_value'}, 'file_name': 'file_name_value', 'file_input_type': 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 = datasources.CreateDataSourceRequest.meta.fields["data_source"] + + 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["data_source"].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["data_source"][field])): + del request_init["data_source"][field][i][subfield] + else: + del request_init["data_source"][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 = datasources.DataSource( + name='name_value', + data_source_id=1462, + display_name='display_name_value', + input=datasources.DataSource.Input.API, + ) + + # 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 = datasources.DataSource.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_data_source(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, datasources.DataSource) + assert response.name == 'name_value' + assert response.data_source_id == 1462 + assert response.display_name == 'display_name_value' + assert response.input == datasources.DataSource.Input.API + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_data_source_rest_interceptors(null_interceptor): + transport = transports.DataSourcesServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataSourcesServiceRestInterceptor(), + ) + client = DataSourcesServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DataSourcesServiceRestInterceptor, "post_create_data_source") as post, \ + mock.patch.object(transports.DataSourcesServiceRestInterceptor, "pre_create_data_source") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = datasources.CreateDataSourceRequest.pb(datasources.CreateDataSourceRequest()) + 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 = datasources.DataSource.to_json(datasources.DataSource()) + req.return_value.content = return_value + + request = datasources.CreateDataSourceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = datasources.DataSource() + + client.create_data_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_data_source_rest_bad_request(request_type=datasources.UpdateDataSourceRequest): + client = DataSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'data_source': {'name': 'accounts/sample1/dataSources/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_data_source(request) + + +@pytest.mark.parametrize("request_type", [ + datasources.UpdateDataSourceRequest, + dict, +]) +def test_update_data_source_rest_call_success(request_type): + client = DataSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'data_source': {'name': 'accounts/sample1/dataSources/sample2'}} + request_init["data_source"] = {'primary_product_data_source': {'channel': 1, 'feed_label': 'feed_label_value', 'content_language': 'content_language_value', 'countries': ['countries_value1', 'countries_value2'], 'default_rule': {'take_from_data_sources': [{'self_': True, 'primary_data_source_name': 'primary_data_source_name_value', 'supplemental_data_source_name': 'supplemental_data_source_name_value'}]}}, 'supplemental_product_data_source': {'feed_label': 'feed_label_value', 'content_language': 'content_language_value', 'referencing_primary_data_sources': {}}, 'local_inventory_data_source': {'feed_label': 'feed_label_value', 'content_language': 'content_language_value'}, 'regional_inventory_data_source': {'feed_label': 'feed_label_value', 'content_language': 'content_language_value'}, 'promotion_data_source': {'target_country': 'target_country_value', 'content_language': 'content_language_value'}, 'name': 'accounts/sample1/dataSources/sample2', 'data_source_id': 1462, 'display_name': 'display_name_value', 'input': 1, 'file_input': {'fetch_settings': {'enabled': True, 'day_of_month': 1271, 'time_of_day': {'hours': 561, 'minutes': 773, 'seconds': 751, 'nanos': 543}, 'day_of_week': 1, 'time_zone': 'time_zone_value', 'frequency': 1, 'fetch_uri': 'fetch_uri_value', 'username': 'username_value', 'password': 'password_value'}, 'file_name': 'file_name_value', 'file_input_type': 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 = datasources.UpdateDataSourceRequest.meta.fields["data_source"] + + 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["data_source"].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["data_source"][field])): + del request_init["data_source"][field][i][subfield] + else: + del request_init["data_source"][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 = datasources.DataSource( + name='name_value', + data_source_id=1462, + display_name='display_name_value', + input=datasources.DataSource.Input.API, + ) + + # 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 = datasources.DataSource.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_data_source(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, datasources.DataSource) + assert response.name == 'name_value' + assert response.data_source_id == 1462 + assert response.display_name == 'display_name_value' + assert response.input == datasources.DataSource.Input.API + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_data_source_rest_interceptors(null_interceptor): + transport = transports.DataSourcesServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataSourcesServiceRestInterceptor(), + ) + client = DataSourcesServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DataSourcesServiceRestInterceptor, "post_update_data_source") as post, \ + mock.patch.object(transports.DataSourcesServiceRestInterceptor, "pre_update_data_source") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = datasources.UpdateDataSourceRequest.pb(datasources.UpdateDataSourceRequest()) + 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 = datasources.DataSource.to_json(datasources.DataSource()) + req.return_value.content = return_value + + request = datasources.UpdateDataSourceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = datasources.DataSource() + + client.update_data_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_data_source_rest_bad_request(request_type=datasources.DeleteDataSourceRequest): + client = DataSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/dataSources/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_data_source(request) + + +@pytest.mark.parametrize("request_type", [ + datasources.DeleteDataSourceRequest, + dict, +]) +def test_delete_data_source_rest_call_success(request_type): + client = DataSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/dataSources/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_data_source(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_data_source_rest_interceptors(null_interceptor): + transport = transports.DataSourcesServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataSourcesServiceRestInterceptor(), + ) + client = DataSourcesServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DataSourcesServiceRestInterceptor, "pre_delete_data_source") as pre: + pre.assert_not_called() + pb_message = datasources.DeleteDataSourceRequest.pb(datasources.DeleteDataSourceRequest()) + 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 = datasources.DeleteDataSourceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_data_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_fetch_data_source_rest_bad_request(request_type=datasources.FetchDataSourceRequest): + client = DataSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/dataSources/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.fetch_data_source(request) + + +@pytest.mark.parametrize("request_type", [ + datasources.FetchDataSourceRequest, + dict, +]) +def test_fetch_data_source_rest_call_success(request_type): + client = DataSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/dataSources/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.fetch_data_source(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_fetch_data_source_rest_interceptors(null_interceptor): + transport = transports.DataSourcesServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataSourcesServiceRestInterceptor(), + ) + client = DataSourcesServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DataSourcesServiceRestInterceptor, "pre_fetch_data_source") as pre: + pre.assert_not_called() + pb_message = datasources.FetchDataSourceRequest.pb(datasources.FetchDataSourceRequest()) + 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 = datasources.FetchDataSourceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.fetch_data_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + +def test_initialize_client_w_rest(): + client = DataSourcesServiceClient( + 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_data_source_empty_call_rest(): + client = DataSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_data_source), + '__call__') as call: + client.get_data_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = datasources.GetDataSourceRequest() + + assert args[0] == request_msg + + +# This 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_data_sources_empty_call_rest(): + client = DataSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_data_sources), + '__call__') as call: + client.list_data_sources(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = datasources.ListDataSourcesRequest() + + assert args[0] == request_msg + + +# This 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_data_source_empty_call_rest(): + client = DataSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_data_source), + '__call__') as call: + client.create_data_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = datasources.CreateDataSourceRequest() + + assert args[0] == request_msg + + +# This 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_data_source_empty_call_rest(): + client = DataSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_data_source), + '__call__') as call: + client.update_data_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = datasources.UpdateDataSourceRequest() + + assert args[0] == request_msg + + +# This 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_data_source_empty_call_rest(): + client = DataSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_data_source), + '__call__') as call: + client.delete_data_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = datasources.DeleteDataSourceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_fetch_data_source_empty_call_rest(): + client = DataSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_data_source), + '__call__') as call: + client.fetch_data_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = datasources.FetchDataSourceRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = DataSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.DataSourcesServiceGrpcTransport, + ) + +def test_data_sources_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.DataSourcesServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_data_sources_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_datasources_v1beta.services.data_sources_service.transports.DataSourcesServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.DataSourcesServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_data_source', + 'list_data_sources', + 'create_data_source', + 'update_data_source', + 'delete_data_source', + 'fetch_data_source', + ) + 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_data_sources_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_datasources_v1beta.services.data_sources_service.transports.DataSourcesServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DataSourcesServiceTransport( + 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_data_sources_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_datasources_v1beta.services.data_sources_service.transports.DataSourcesServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DataSourcesServiceTransport() + adc.assert_called_once() + + +def test_data_sources_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) + DataSourcesServiceClient() + 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.DataSourcesServiceGrpcTransport, + transports.DataSourcesServiceGrpcAsyncIOTransport, + ], +) +def test_data_sources_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.DataSourcesServiceGrpcTransport, + transports.DataSourcesServiceGrpcAsyncIOTransport, + transports.DataSourcesServiceRestTransport, + ], +) +def test_data_sources_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.DataSourcesServiceGrpcTransport, grpc_helpers), + (transports.DataSourcesServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_data_sources_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.DataSourcesServiceGrpcTransport, transports.DataSourcesServiceGrpcAsyncIOTransport]) +def test_data_sources_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_data_sources_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.DataSourcesServiceRestTransport ( + 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_data_sources_service_host_no_port(transport_name): + client = DataSourcesServiceClient( + 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_data_sources_service_host_with_port(transport_name): + client = DataSourcesServiceClient( + 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_data_sources_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = DataSourcesServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = DataSourcesServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_data_source._session + session2 = client2.transport.get_data_source._session + assert session1 != session2 + session1 = client1.transport.list_data_sources._session + session2 = client2.transport.list_data_sources._session + assert session1 != session2 + session1 = client1.transport.create_data_source._session + session2 = client2.transport.create_data_source._session + assert session1 != session2 + session1 = client1.transport.update_data_source._session + session2 = client2.transport.update_data_source._session + assert session1 != session2 + session1 = client1.transport.delete_data_source._session + session2 = client2.transport.delete_data_source._session + assert session1 != session2 + session1 = client1.transport.fetch_data_source._session + session2 = client2.transport.fetch_data_source._session + assert session1 != session2 +def test_data_sources_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DataSourcesServiceGrpcTransport( + 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_data_sources_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DataSourcesServiceGrpcAsyncIOTransport( + 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.DataSourcesServiceGrpcTransport, transports.DataSourcesServiceGrpcAsyncIOTransport]) +def test_data_sources_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.DataSourcesServiceGrpcTransport, transports.DataSourcesServiceGrpcAsyncIOTransport]) +def test_data_sources_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_data_source_path(): + account = "squid" + datasource = "clam" + expected = "accounts/{account}/dataSources/{datasource}".format(account=account, datasource=datasource, ) + actual = DataSourcesServiceClient.data_source_path(account, datasource) + assert expected == actual + + +def test_parse_data_source_path(): + expected = { + "account": "whelk", + "datasource": "octopus", + } + path = DataSourcesServiceClient.data_source_path(**expected) + + # Check that the path construction is reversible. + actual = DataSourcesServiceClient.parse_data_source_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = DataSourcesServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = DataSourcesServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = DataSourcesServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = DataSourcesServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = DataSourcesServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = DataSourcesServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = DataSourcesServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = DataSourcesServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = DataSourcesServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = DataSourcesServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = DataSourcesServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = DataSourcesServiceClient.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 = DataSourcesServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = DataSourcesServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = DataSourcesServiceClient.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.DataSourcesServiceTransport, '_prep_wrapped_messages') as prep: + client = DataSourcesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.DataSourcesServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = DataSourcesServiceClient.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 = DataSourcesServiceClient( + 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 = DataSourcesServiceAsyncClient( + 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 = DataSourcesServiceClient( + 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 = DataSourcesServiceClient( + 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", [ + (DataSourcesServiceClient, transports.DataSourcesServiceGrpcTransport), + (DataSourcesServiceAsyncClient, transports.DataSourcesServiceGrpcAsyncIOTransport), +]) +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-datasources/v1beta/tests/unit/gapic/merchant_datasources_v1beta/test_file_uploads_service.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/tests/unit/gapic/merchant_datasources_v1beta/test_file_uploads_service.py new file mode 100644 index 000000000000..ecc075be50ee --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/tests/unit/gapic/merchant_datasources_v1beta/test_file_uploads_service.py @@ -0,0 +1,2121 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable, AsyncIterable +from google.protobuf import json_format +import json +import math +import pytest +from google.api_core import api_core_version +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +try: + from google.auth.aio import credentials as ga_credentials_async + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account +from google.protobuf import timestamp_pb2 # type: ignore +from google.shopping.merchant_datasources_v1beta.services.file_uploads_service import FileUploadsServiceAsyncClient +from google.shopping.merchant_datasources_v1beta.services.file_uploads_service import FileUploadsServiceClient +from google.shopping.merchant_datasources_v1beta.services.file_uploads_service import transports +from google.shopping.merchant_datasources_v1beta.types import fileuploads +import google.auth + + +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 FileUploadsServiceClient._get_default_mtls_endpoint(None) is None + assert FileUploadsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert FileUploadsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert FileUploadsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert FileUploadsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert FileUploadsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert FileUploadsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert FileUploadsServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert FileUploadsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + FileUploadsServiceClient._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 FileUploadsServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert FileUploadsServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert FileUploadsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + FileUploadsServiceClient._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 FileUploadsServiceClient._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 FileUploadsServiceClient._get_client_cert_source(None, False) is None + assert FileUploadsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert FileUploadsServiceClient._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 FileUploadsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert FileUploadsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(FileUploadsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(FileUploadsServiceClient)) +@mock.patch.object(FileUploadsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(FileUploadsServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = FileUploadsServiceClient._DEFAULT_UNIVERSE + default_endpoint = FileUploadsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = FileUploadsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert FileUploadsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert FileUploadsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == FileUploadsServiceClient.DEFAULT_MTLS_ENDPOINT + assert FileUploadsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert FileUploadsServiceClient._get_api_endpoint(None, None, default_universe, "always") == FileUploadsServiceClient.DEFAULT_MTLS_ENDPOINT + assert FileUploadsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == FileUploadsServiceClient.DEFAULT_MTLS_ENDPOINT + assert FileUploadsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert FileUploadsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + FileUploadsServiceClient._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 FileUploadsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert FileUploadsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert FileUploadsServiceClient._get_universe_domain(None, None) == FileUploadsServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + FileUploadsServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize("client_class,transport_name", [ + (FileUploadsServiceClient, "grpc"), + (FileUploadsServiceAsyncClient, "grpc_asyncio"), + (FileUploadsServiceClient, "rest"), +]) +def test_file_uploads_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.FileUploadsServiceGrpcTransport, "grpc"), + (transports.FileUploadsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.FileUploadsServiceRestTransport, "rest"), +]) +def test_file_uploads_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", [ + (FileUploadsServiceClient, "grpc"), + (FileUploadsServiceAsyncClient, "grpc_asyncio"), + (FileUploadsServiceClient, "rest"), +]) +def test_file_uploads_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_file_uploads_service_client_get_transport_class(): + transport = FileUploadsServiceClient.get_transport_class() + available_transports = [ + transports.FileUploadsServiceGrpcTransport, + transports.FileUploadsServiceRestTransport, + ] + assert transport in available_transports + + transport = FileUploadsServiceClient.get_transport_class("grpc") + assert transport == transports.FileUploadsServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (FileUploadsServiceClient, transports.FileUploadsServiceGrpcTransport, "grpc"), + (FileUploadsServiceAsyncClient, transports.FileUploadsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (FileUploadsServiceClient, transports.FileUploadsServiceRestTransport, "rest"), +]) +@mock.patch.object(FileUploadsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(FileUploadsServiceClient)) +@mock.patch.object(FileUploadsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(FileUploadsServiceAsyncClient)) +def test_file_uploads_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(FileUploadsServiceClient, '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(FileUploadsServiceClient, '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", [ + (FileUploadsServiceClient, transports.FileUploadsServiceGrpcTransport, "grpc", "true"), + (FileUploadsServiceAsyncClient, transports.FileUploadsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (FileUploadsServiceClient, transports.FileUploadsServiceGrpcTransport, "grpc", "false"), + (FileUploadsServiceAsyncClient, transports.FileUploadsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (FileUploadsServiceClient, transports.FileUploadsServiceRestTransport, "rest", "true"), + (FileUploadsServiceClient, transports.FileUploadsServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(FileUploadsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(FileUploadsServiceClient)) +@mock.patch.object(FileUploadsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(FileUploadsServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_file_uploads_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", [ + FileUploadsServiceClient, FileUploadsServiceAsyncClient +]) +@mock.patch.object(FileUploadsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FileUploadsServiceClient)) +@mock.patch.object(FileUploadsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FileUploadsServiceAsyncClient)) +def test_file_uploads_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", [ + FileUploadsServiceClient, FileUploadsServiceAsyncClient +]) +@mock.patch.object(FileUploadsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(FileUploadsServiceClient)) +@mock.patch.object(FileUploadsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(FileUploadsServiceAsyncClient)) +def test_file_uploads_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = FileUploadsServiceClient._DEFAULT_UNIVERSE + default_endpoint = FileUploadsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = FileUploadsServiceClient._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", [ + (FileUploadsServiceClient, transports.FileUploadsServiceGrpcTransport, "grpc"), + (FileUploadsServiceAsyncClient, transports.FileUploadsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (FileUploadsServiceClient, transports.FileUploadsServiceRestTransport, "rest"), +]) +def test_file_uploads_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", [ + (FileUploadsServiceClient, transports.FileUploadsServiceGrpcTransport, "grpc", grpc_helpers), + (FileUploadsServiceAsyncClient, transports.FileUploadsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (FileUploadsServiceClient, transports.FileUploadsServiceRestTransport, "rest", None), +]) +def test_file_uploads_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_file_uploads_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_datasources_v1beta.services.file_uploads_service.transports.FileUploadsServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = FileUploadsServiceClient( + 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", [ + (FileUploadsServiceClient, transports.FileUploadsServiceGrpcTransport, "grpc", grpc_helpers), + (FileUploadsServiceAsyncClient, transports.FileUploadsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_file_uploads_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", [ + fileuploads.GetFileUploadRequest, + dict, +]) +def test_get_file_upload(request_type, transport: str = 'grpc'): + client = FileUploadsServiceClient( + 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_file_upload), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = fileuploads.FileUpload( + name='name_value', + data_source_id=1462, + processing_state=fileuploads.FileUpload.ProcessingState.FAILED, + items_total=1189, + items_created=1369, + items_updated=1384, + ) + response = client.get_file_upload(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = fileuploads.GetFileUploadRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, fileuploads.FileUpload) + assert response.name == 'name_value' + assert response.data_source_id == 1462 + assert response.processing_state == fileuploads.FileUpload.ProcessingState.FAILED + assert response.items_total == 1189 + assert response.items_created == 1369 + assert response.items_updated == 1384 + + +def test_get_file_upload_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 = FileUploadsServiceClient( + 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 = fileuploads.GetFileUploadRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_file_upload), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_file_upload(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == fileuploads.GetFileUploadRequest( + name='name_value', + ) + +def test_get_file_upload_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = FileUploadsServiceClient( + 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_file_upload in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_file_upload] = mock_rpc + request = {} + client.get_file_upload(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_file_upload(request) + + # Establish that a new wrapper 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_file_upload_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = FileUploadsServiceAsyncClient( + 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_file_upload in client._client._transport._wrapped_methods + + # 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_file_upload] = mock_rpc + + request = {} + await client.get_file_upload(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_file_upload(request) + + # Establish that a new wrapper 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_file_upload_async(transport: str = 'grpc_asyncio', request_type=fileuploads.GetFileUploadRequest): + client = FileUploadsServiceAsyncClient( + 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_file_upload), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(fileuploads.FileUpload( + name='name_value', + data_source_id=1462, + processing_state=fileuploads.FileUpload.ProcessingState.FAILED, + items_total=1189, + items_created=1369, + items_updated=1384, + )) + response = await client.get_file_upload(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = fileuploads.GetFileUploadRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, fileuploads.FileUpload) + assert response.name == 'name_value' + assert response.data_source_id == 1462 + assert response.processing_state == fileuploads.FileUpload.ProcessingState.FAILED + assert response.items_total == 1189 + assert response.items_created == 1369 + assert response.items_updated == 1384 + + +@pytest.mark.asyncio +async def test_get_file_upload_async_from_dict(): + await test_get_file_upload_async(request_type=dict) + +def test_get_file_upload_field_headers(): + client = FileUploadsServiceClient( + 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 = fileuploads.GetFileUploadRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_file_upload), + '__call__') as call: + call.return_value = fileuploads.FileUpload() + client.get_file_upload(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_file_upload_field_headers_async(): + client = FileUploadsServiceAsyncClient( + 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 = fileuploads.GetFileUploadRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_file_upload), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(fileuploads.FileUpload()) + await client.get_file_upload(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_file_upload_flattened(): + client = FileUploadsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_file_upload), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = fileuploads.FileUpload() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_file_upload( + 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_file_upload_flattened_error(): + client = FileUploadsServiceClient( + 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_file_upload( + fileuploads.GetFileUploadRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_file_upload_flattened_async(): + client = FileUploadsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_file_upload), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = fileuploads.FileUpload() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(fileuploads.FileUpload()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_file_upload( + 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_file_upload_flattened_error_async(): + client = FileUploadsServiceAsyncClient( + 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_file_upload( + fileuploads.GetFileUploadRequest(), + name='name_value', + ) + + +def test_get_file_upload_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 = FileUploadsServiceClient( + 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_file_upload in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_file_upload] = mock_rpc + + request = {} + client.get_file_upload(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_file_upload(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_file_upload_rest_required_fields(request_type=fileuploads.GetFileUploadRequest): + transport_class = transports.FileUploadsServiceRestTransport + + 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_file_upload._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_file_upload._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 = FileUploadsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = fileuploads.FileUpload() + # 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 = fileuploads.FileUpload.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_file_upload(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_file_upload_rest_unset_required_fields(): + transport = transports.FileUploadsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_file_upload._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_file_upload_rest_flattened(): + client = FileUploadsServiceClient( + 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 = fileuploads.FileUpload() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/dataSources/sample2/fileUploads/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 = fileuploads.FileUpload.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_file_upload(**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/datasources/v1beta/{name=accounts/*/dataSources/*/fileUploads/*}" % client.transport._host, args[1]) + + +def test_get_file_upload_rest_flattened_error(transport: str = 'rest'): + client = FileUploadsServiceClient( + 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_file_upload( + fileuploads.GetFileUploadRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.FileUploadsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FileUploadsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.FileUploadsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FileUploadsServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.FileUploadsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = FileUploadsServiceClient( + 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 = FileUploadsServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.FileUploadsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FileUploadsServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.FileUploadsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = FileUploadsServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.FileUploadsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.FileUploadsServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.FileUploadsServiceGrpcTransport, + transports.FileUploadsServiceGrpcAsyncIOTransport, + transports.FileUploadsServiceRestTransport, +]) +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 = FileUploadsServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = FileUploadsServiceClient( + 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_file_upload_empty_call_grpc(): + client = FileUploadsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_file_upload), + '__call__') as call: + call.return_value = fileuploads.FileUpload() + client.get_file_upload(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = fileuploads.GetFileUploadRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = FileUploadsServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = FileUploadsServiceAsyncClient( + 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_file_upload_empty_call_grpc_asyncio(): + client = FileUploadsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_file_upload), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(fileuploads.FileUpload( + name='name_value', + data_source_id=1462, + processing_state=fileuploads.FileUpload.ProcessingState.FAILED, + items_total=1189, + items_created=1369, + items_updated=1384, + )) + await client.get_file_upload(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = fileuploads.GetFileUploadRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = FileUploadsServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_file_upload_rest_bad_request(request_type=fileuploads.GetFileUploadRequest): + client = FileUploadsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/dataSources/sample2/fileUploads/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.get_file_upload(request) + + +@pytest.mark.parametrize("request_type", [ + fileuploads.GetFileUploadRequest, + dict, +]) +def test_get_file_upload_rest_call_success(request_type): + client = FileUploadsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/dataSources/sample2/fileUploads/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 = fileuploads.FileUpload( + name='name_value', + data_source_id=1462, + processing_state=fileuploads.FileUpload.ProcessingState.FAILED, + items_total=1189, + items_created=1369, + items_updated=1384, + ) + + # 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 = fileuploads.FileUpload.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_file_upload(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, fileuploads.FileUpload) + assert response.name == 'name_value' + assert response.data_source_id == 1462 + assert response.processing_state == fileuploads.FileUpload.ProcessingState.FAILED + assert response.items_total == 1189 + assert response.items_created == 1369 + assert response.items_updated == 1384 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_file_upload_rest_interceptors(null_interceptor): + transport = transports.FileUploadsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.FileUploadsServiceRestInterceptor(), + ) + client = FileUploadsServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.FileUploadsServiceRestInterceptor, "post_get_file_upload") as post, \ + mock.patch.object(transports.FileUploadsServiceRestInterceptor, "pre_get_file_upload") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = fileuploads.GetFileUploadRequest.pb(fileuploads.GetFileUploadRequest()) + 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 = fileuploads.FileUpload.to_json(fileuploads.FileUpload()) + req.return_value.content = return_value + + request = fileuploads.GetFileUploadRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = fileuploads.FileUpload() + + client.get_file_upload(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + +def test_initialize_client_w_rest(): + client = FileUploadsServiceClient( + 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_file_upload_empty_call_rest(): + client = FileUploadsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_file_upload), + '__call__') as call: + client.get_file_upload(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = fileuploads.GetFileUploadRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = FileUploadsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.FileUploadsServiceGrpcTransport, + ) + +def test_file_uploads_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.FileUploadsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_file_uploads_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_datasources_v1beta.services.file_uploads_service.transports.FileUploadsServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.FileUploadsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_file_upload', + ) + 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_file_uploads_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_datasources_v1beta.services.file_uploads_service.transports.FileUploadsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.FileUploadsServiceTransport( + 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_file_uploads_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_datasources_v1beta.services.file_uploads_service.transports.FileUploadsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.FileUploadsServiceTransport() + adc.assert_called_once() + + +def test_file_uploads_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) + FileUploadsServiceClient() + 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.FileUploadsServiceGrpcTransport, + transports.FileUploadsServiceGrpcAsyncIOTransport, + ], +) +def test_file_uploads_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.FileUploadsServiceGrpcTransport, + transports.FileUploadsServiceGrpcAsyncIOTransport, + transports.FileUploadsServiceRestTransport, + ], +) +def test_file_uploads_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.FileUploadsServiceGrpcTransport, grpc_helpers), + (transports.FileUploadsServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_file_uploads_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.FileUploadsServiceGrpcTransport, transports.FileUploadsServiceGrpcAsyncIOTransport]) +def test_file_uploads_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_file_uploads_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.FileUploadsServiceRestTransport ( + 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_file_uploads_service_host_no_port(transport_name): + client = FileUploadsServiceClient( + 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_file_uploads_service_host_with_port(transport_name): + client = FileUploadsServiceClient( + 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_file_uploads_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = FileUploadsServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = FileUploadsServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_file_upload._session + session2 = client2.transport.get_file_upload._session + assert session1 != session2 +def test_file_uploads_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.FileUploadsServiceGrpcTransport( + 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_file_uploads_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.FileUploadsServiceGrpcAsyncIOTransport( + 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.FileUploadsServiceGrpcTransport, transports.FileUploadsServiceGrpcAsyncIOTransport]) +def test_file_uploads_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.FileUploadsServiceGrpcTransport, transports.FileUploadsServiceGrpcAsyncIOTransport]) +def test_file_uploads_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_file_upload_path(): + account = "squid" + datasource = "clam" + fileupload = "whelk" + expected = "accounts/{account}/dataSources/{datasource}/fileUploads/{fileupload}".format(account=account, datasource=datasource, fileupload=fileupload, ) + actual = FileUploadsServiceClient.file_upload_path(account, datasource, fileupload) + assert expected == actual + + +def test_parse_file_upload_path(): + expected = { + "account": "octopus", + "datasource": "oyster", + "fileupload": "nudibranch", + } + path = FileUploadsServiceClient.file_upload_path(**expected) + + # Check that the path construction is reversible. + actual = FileUploadsServiceClient.parse_file_upload_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = FileUploadsServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = FileUploadsServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = FileUploadsServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = FileUploadsServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = FileUploadsServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = FileUploadsServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = FileUploadsServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = FileUploadsServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = FileUploadsServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = FileUploadsServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = FileUploadsServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = FileUploadsServiceClient.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 = FileUploadsServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = FileUploadsServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = FileUploadsServiceClient.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.FileUploadsServiceTransport, '_prep_wrapped_messages') as prep: + client = FileUploadsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.FileUploadsServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = FileUploadsServiceClient.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 = FileUploadsServiceClient( + 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 = FileUploadsServiceAsyncClient( + 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 = FileUploadsServiceClient( + 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 = FileUploadsServiceClient( + 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", [ + (FileUploadsServiceClient, transports.FileUploadsServiceGrpcTransport), + (FileUploadsServiceAsyncClient, transports.FileUploadsServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/.coveragerc b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/.coveragerc new file mode 100644 index 000000000000..b3835b541d48 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/shopping/merchant_inventories/__init__.py + google/shopping/merchant_inventories/gapic_version.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/.flake8 b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/MANIFEST.in b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/MANIFEST.in new file mode 100644 index 000000000000..516108ef9a06 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/shopping/merchant_inventories *.py +recursive-include google/shopping/merchant_inventories_v1beta *.py diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/README.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/README.rst new file mode 100644 index 000000000000..0f012bb0c42e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Shopping Merchant Inventories API +================================================= + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. Enable the Google Shopping Merchant Inventories API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/_static/custom.css b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/conf.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/conf.py new file mode 100644 index 000000000000..f71381a47a11 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-shopping-merchant-inventories documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# 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.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The root toctree document. +root_doc = "index" + +# General information about the project. +project = u"google-shopping-merchant-inventories" +copyright = u"2023, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# 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 = 'en' + +# 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"] + +# 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 Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-shopping-merchant-inventories-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + root_doc, + "google-shopping-merchant-inventories.tex", + u"google-shopping-merchant-inventories Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + root_doc, + "google-shopping-merchant-inventories", + u"Google Shopping Merchant Inventories Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + root_doc, + "google-shopping-merchant-inventories", + u"google-shopping-merchant-inventories Documentation", + author, + "google-shopping-merchant-inventories", + "GAPIC library for Google Shopping Merchant Inventories API", + "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": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/index.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/index.rst new file mode 100644 index 000000000000..98ba4d129c6d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + merchant_inventories_v1beta/services_ + merchant_inventories_v1beta/types_ diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/local_inventory_service.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/local_inventory_service.rst new file mode 100644 index 000000000000..d8e5a2b05114 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/local_inventory_service.rst @@ -0,0 +1,10 @@ +LocalInventoryService +--------------------------------------- + +.. automodule:: google.shopping.merchant_inventories_v1beta.services.local_inventory_service + :members: + :inherited-members: + +.. automodule:: google.shopping.merchant_inventories_v1beta.services.local_inventory_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/regional_inventory_service.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/regional_inventory_service.rst new file mode 100644 index 000000000000..d23b466a2398 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/regional_inventory_service.rst @@ -0,0 +1,10 @@ +RegionalInventoryService +------------------------------------------ + +.. automodule:: google.shopping.merchant_inventories_v1beta.services.regional_inventory_service + :members: + :inherited-members: + +.. automodule:: google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/services_.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/services_.rst new file mode 100644 index 000000000000..7bdd71de9b95 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/services_.rst @@ -0,0 +1,7 @@ +Services for Google Shopping Merchant Inventories v1beta API +============================================================ +.. toctree:: + :maxdepth: 2 + + local_inventory_service + regional_inventory_service diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/types_.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/types_.rst new file mode 100644 index 000000000000..2bd5b6e3cb01 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/types_.rst @@ -0,0 +1,6 @@ +Types for Google Shopping Merchant Inventories v1beta API +========================================================= + +.. automodule:: google.shopping.merchant_inventories_v1beta.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/__init__.py new file mode 100644 index 000000000000..642093b6a92f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/__init__.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.shopping.merchant_inventories import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.shopping.merchant_inventories_v1beta.services.local_inventory_service.client import LocalInventoryServiceClient +from google.shopping.merchant_inventories_v1beta.services.local_inventory_service.async_client import LocalInventoryServiceAsyncClient +from google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.client import RegionalInventoryServiceClient +from google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.async_client import RegionalInventoryServiceAsyncClient + +from google.shopping.merchant_inventories_v1beta.types.localinventory import DeleteLocalInventoryRequest +from google.shopping.merchant_inventories_v1beta.types.localinventory import InsertLocalInventoryRequest +from google.shopping.merchant_inventories_v1beta.types.localinventory import ListLocalInventoriesRequest +from google.shopping.merchant_inventories_v1beta.types.localinventory import ListLocalInventoriesResponse +from google.shopping.merchant_inventories_v1beta.types.localinventory import LocalInventory +from google.shopping.merchant_inventories_v1beta.types.regionalinventory import DeleteRegionalInventoryRequest +from google.shopping.merchant_inventories_v1beta.types.regionalinventory import InsertRegionalInventoryRequest +from google.shopping.merchant_inventories_v1beta.types.regionalinventory import ListRegionalInventoriesRequest +from google.shopping.merchant_inventories_v1beta.types.regionalinventory import ListRegionalInventoriesResponse +from google.shopping.merchant_inventories_v1beta.types.regionalinventory import RegionalInventory + +__all__ = ('LocalInventoryServiceClient', + 'LocalInventoryServiceAsyncClient', + 'RegionalInventoryServiceClient', + 'RegionalInventoryServiceAsyncClient', + 'DeleteLocalInventoryRequest', + 'InsertLocalInventoryRequest', + 'ListLocalInventoriesRequest', + 'ListLocalInventoriesResponse', + 'LocalInventory', + 'DeleteRegionalInventoryRequest', + 'InsertRegionalInventoryRequest', + 'ListRegionalInventoriesRequest', + 'ListRegionalInventoriesResponse', + 'RegionalInventory', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/gapic_version.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/py.typed b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/py.typed new file mode 100644 index 000000000000..993f00a7e3c3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-shopping-merchant-inventories package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/__init__.py new file mode 100644 index 000000000000..3e759824ccdf --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/__init__.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.shopping.merchant_inventories_v1beta import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.local_inventory_service import LocalInventoryServiceClient +from .services.local_inventory_service import LocalInventoryServiceAsyncClient +from .services.regional_inventory_service import RegionalInventoryServiceClient +from .services.regional_inventory_service import RegionalInventoryServiceAsyncClient + +from .types.localinventory import DeleteLocalInventoryRequest +from .types.localinventory import InsertLocalInventoryRequest +from .types.localinventory import ListLocalInventoriesRequest +from .types.localinventory import ListLocalInventoriesResponse +from .types.localinventory import LocalInventory +from .types.regionalinventory import DeleteRegionalInventoryRequest +from .types.regionalinventory import InsertRegionalInventoryRequest +from .types.regionalinventory import ListRegionalInventoriesRequest +from .types.regionalinventory import ListRegionalInventoriesResponse +from .types.regionalinventory import RegionalInventory + +__all__ = ( + 'LocalInventoryServiceAsyncClient', + 'RegionalInventoryServiceAsyncClient', +'DeleteLocalInventoryRequest', +'DeleteRegionalInventoryRequest', +'InsertLocalInventoryRequest', +'InsertRegionalInventoryRequest', +'ListLocalInventoriesRequest', +'ListLocalInventoriesResponse', +'ListRegionalInventoriesRequest', +'ListRegionalInventoriesResponse', +'LocalInventory', +'LocalInventoryServiceClient', +'RegionalInventory', +'RegionalInventoryServiceClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/gapic_metadata.json b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/gapic_metadata.json new file mode 100644 index 000000000000..dca053900305 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/gapic_metadata.json @@ -0,0 +1,137 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.shopping.merchant_inventories_v1beta", + "protoPackage": "google.shopping.merchant.inventories.v1beta", + "schema": "1.0", + "services": { + "LocalInventoryService": { + "clients": { + "grpc": { + "libraryClient": "LocalInventoryServiceClient", + "rpcs": { + "DeleteLocalInventory": { + "methods": [ + "delete_local_inventory" + ] + }, + "InsertLocalInventory": { + "methods": [ + "insert_local_inventory" + ] + }, + "ListLocalInventories": { + "methods": [ + "list_local_inventories" + ] + } + } + }, + "grpc-async": { + "libraryClient": "LocalInventoryServiceAsyncClient", + "rpcs": { + "DeleteLocalInventory": { + "methods": [ + "delete_local_inventory" + ] + }, + "InsertLocalInventory": { + "methods": [ + "insert_local_inventory" + ] + }, + "ListLocalInventories": { + "methods": [ + "list_local_inventories" + ] + } + } + }, + "rest": { + "libraryClient": "LocalInventoryServiceClient", + "rpcs": { + "DeleteLocalInventory": { + "methods": [ + "delete_local_inventory" + ] + }, + "InsertLocalInventory": { + "methods": [ + "insert_local_inventory" + ] + }, + "ListLocalInventories": { + "methods": [ + "list_local_inventories" + ] + } + } + } + } + }, + "RegionalInventoryService": { + "clients": { + "grpc": { + "libraryClient": "RegionalInventoryServiceClient", + "rpcs": { + "DeleteRegionalInventory": { + "methods": [ + "delete_regional_inventory" + ] + }, + "InsertRegionalInventory": { + "methods": [ + "insert_regional_inventory" + ] + }, + "ListRegionalInventories": { + "methods": [ + "list_regional_inventories" + ] + } + } + }, + "grpc-async": { + "libraryClient": "RegionalInventoryServiceAsyncClient", + "rpcs": { + "DeleteRegionalInventory": { + "methods": [ + "delete_regional_inventory" + ] + }, + "InsertRegionalInventory": { + "methods": [ + "insert_regional_inventory" + ] + }, + "ListRegionalInventories": { + "methods": [ + "list_regional_inventories" + ] + } + } + }, + "rest": { + "libraryClient": "RegionalInventoryServiceClient", + "rpcs": { + "DeleteRegionalInventory": { + "methods": [ + "delete_regional_inventory" + ] + }, + "InsertRegionalInventory": { + "methods": [ + "insert_regional_inventory" + ] + }, + "ListRegionalInventories": { + "methods": [ + "list_regional_inventories" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/gapic_version.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/py.typed b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/py.typed new file mode 100644 index 000000000000..993f00a7e3c3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-shopping-merchant-inventories package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/__init__.py new file mode 100644 index 000000000000..fc4e82d6ff35 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import LocalInventoryServiceClient +from .async_client import LocalInventoryServiceAsyncClient + +__all__ = ( + 'LocalInventoryServiceClient', + 'LocalInventoryServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/async_client.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/async_client.py new file mode 100644 index 000000000000..ffcc5efbf5e0 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/async_client.py @@ -0,0 +1,585 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import logging as std_logging +from collections import OrderedDict +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.shopping.merchant_inventories_v1beta import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.shopping.merchant_inventories_v1beta.services.local_inventory_service import pagers +from google.shopping.merchant_inventories_v1beta.types import localinventory +from google.shopping.type.types import types +from google.type import interval_pb2 # type: ignore +from .transports.base import LocalInventoryServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import LocalInventoryServiceGrpcAsyncIOTransport +from .client import LocalInventoryServiceClient + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +class LocalInventoryServiceAsyncClient: + """Service to manage local inventory for products""" + + _client: LocalInventoryServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = LocalInventoryServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = LocalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = LocalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = LocalInventoryServiceClient._DEFAULT_UNIVERSE + + local_inventory_path = staticmethod(LocalInventoryServiceClient.local_inventory_path) + parse_local_inventory_path = staticmethod(LocalInventoryServiceClient.parse_local_inventory_path) + common_billing_account_path = staticmethod(LocalInventoryServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(LocalInventoryServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(LocalInventoryServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(LocalInventoryServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(LocalInventoryServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(LocalInventoryServiceClient.parse_common_organization_path) + common_project_path = staticmethod(LocalInventoryServiceClient.common_project_path) + parse_common_project_path = staticmethod(LocalInventoryServiceClient.parse_common_project_path) + common_location_path = staticmethod(LocalInventoryServiceClient.common_location_path) + parse_common_location_path = staticmethod(LocalInventoryServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + LocalInventoryServiceAsyncClient: The constructed client. + """ + return LocalInventoryServiceClient.from_service_account_info.__func__(LocalInventoryServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + LocalInventoryServiceAsyncClient: The constructed client. + """ + return LocalInventoryServiceClient.from_service_account_file.__func__(LocalInventoryServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return LocalInventoryServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> LocalInventoryServiceTransport: + """Returns the transport used by the client instance. + + Returns: + LocalInventoryServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = LocalInventoryServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, LocalInventoryServiceTransport, Callable[..., LocalInventoryServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the local inventory service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,LocalInventoryServiceTransport,Callable[..., LocalInventoryServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the LocalInventoryServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = LocalInventoryServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.shopping.merchant.inventories_v1beta.LocalInventoryServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._client._transport, "_credentials") else { + "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "credentialsType": None, + } + ) + + async def list_local_inventories(self, + request: Optional[Union[localinventory.ListLocalInventoriesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLocalInventoriesAsyncPager: + r"""Lists the ``LocalInventory`` resources for the given product in + your merchant account. The response might contain fewer items + than specified by ``pageSize``. If ``pageToken`` was returned in + previous request, it can be used to obtain additional results. + + ``LocalInventory`` resources are listed per product for a given + account. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_inventories_v1beta + + async def sample_list_local_inventories(): + # Create a client + client = merchant_inventories_v1beta.LocalInventoryServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_inventories_v1beta.ListLocalInventoriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_local_inventories(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesRequest, dict]]): + The request object. Request message for the ``ListLocalInventories`` method. + parent (:class:`str`): + Required. The ``name`` of the parent product to list + local inventories for. Format: + ``accounts/{account}/products/{product}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.shopping.merchant_inventories_v1beta.services.local_inventory_service.pagers.ListLocalInventoriesAsyncPager: + Response message for the ListLocalInventories method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, localinventory.ListLocalInventoriesRequest): + request = localinventory.ListLocalInventoriesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_local_inventories] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListLocalInventoriesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def insert_local_inventory(self, + request: Optional[Union[localinventory.InsertLocalInventoryRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> localinventory.LocalInventory: + r"""Inserts a ``LocalInventory`` resource to a product in your + merchant account. + + Replaces the full ``LocalInventory`` resource if an entry with + the same + [``storeCode``][google.shopping.merchant.inventories.v1beta.LocalInventory.store_code] + already exists for the product. + + It might take up to 30 minutes for the new or updated + ``LocalInventory`` resource to appear in products. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_inventories_v1beta + + async def sample_insert_local_inventory(): + # Create a client + client = merchant_inventories_v1beta.LocalInventoryServiceAsyncClient() + + # Initialize request argument(s) + local_inventory = merchant_inventories_v1beta.LocalInventory() + local_inventory.store_code = "store_code_value" + + request = merchant_inventories_v1beta.InsertLocalInventoryRequest( + parent="parent_value", + local_inventory=local_inventory, + ) + + # Make the request + response = await client.insert_local_inventory(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_inventories_v1beta.types.InsertLocalInventoryRequest, dict]]): + The request object. Request message for the ``InsertLocalInventory`` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.shopping.merchant_inventories_v1beta.types.LocalInventory: + Local inventory information for the product. Represents in-store information + for a specific product at the store specified by + [storeCode][google.shopping.merchant.inventories.v1beta.LocalInventory.store_code]. + For a list of all accepted attribute values, see the + [local product inventory data + specification](\ https://support.google.com/merchants/answer/3061342). + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, localinventory.InsertLocalInventoryRequest): + request = localinventory.InsertLocalInventoryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.insert_local_inventory] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_local_inventory(self, + request: Optional[Union[localinventory.DeleteLocalInventoryRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes the specified ``LocalInventory`` from the given product + in your merchant account. It might take a up to an hour for the + ``LocalInventory`` to be deleted from the specific product. Once + you have received a successful delete response, wait for that + period before attempting a delete again. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_inventories_v1beta + + async def sample_delete_local_inventory(): + # Create a client + client = merchant_inventories_v1beta.LocalInventoryServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_inventories_v1beta.DeleteLocalInventoryRequest( + name="name_value", + ) + + # Make the request + await client.delete_local_inventory(request=request) + + Args: + request (Optional[Union[google.shopping.merchant_inventories_v1beta.types.DeleteLocalInventoryRequest, dict]]): + The request object. Request message for the ``DeleteLocalInventory`` method. + name (:class:`str`): + Required. The name of the local inventory for the given + product to delete. Format: + ``accounts/{account}/products/{product}/localInventories/{store_code}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, localinventory.DeleteLocalInventoryRequest): + request = localinventory.DeleteLocalInventoryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_local_inventory] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def __aenter__(self) -> "LocalInventoryServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "LocalInventoryServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/client.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/client.py new file mode 100644 index 000000000000..4c93e36e7f8e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/client.py @@ -0,0 +1,919 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +import logging as std_logging +import os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.shopping.merchant_inventories_v1beta import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +from google.shopping.merchant_inventories_v1beta.services.local_inventory_service import pagers +from google.shopping.merchant_inventories_v1beta.types import localinventory +from google.shopping.type.types import types +from google.type import interval_pb2 # type: ignore +from .transports.base import LocalInventoryServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import LocalInventoryServiceGrpcTransport +from .transports.grpc_asyncio import LocalInventoryServiceGrpcAsyncIOTransport +from .transports.rest import LocalInventoryServiceRestTransport + + +class LocalInventoryServiceClientMeta(type): + """Metaclass for the LocalInventoryService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[LocalInventoryServiceTransport]] + _transport_registry["grpc"] = LocalInventoryServiceGrpcTransport + _transport_registry["grpc_asyncio"] = LocalInventoryServiceGrpcAsyncIOTransport + _transport_registry["rest"] = LocalInventoryServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[LocalInventoryServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class LocalInventoryServiceClient(metaclass=LocalInventoryServiceClientMeta): + """Service to manage local inventory for products""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "merchantapi.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "merchantapi.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + LocalInventoryServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + LocalInventoryServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> LocalInventoryServiceTransport: + """Returns the transport used by the client instance. + + Returns: + LocalInventoryServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def local_inventory_path(account: str,product: str,store_code: str,) -> str: + """Returns a fully-qualified local_inventory string.""" + return "accounts/{account}/products/{product}/localInventories/{store_code}".format(account=account, product=product, store_code=store_code, ) + + @staticmethod + def parse_local_inventory_path(path: str) -> Dict[str,str]: + """Parses a local_inventory path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/products/(?P.+?)/localInventories/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + _default_universe = LocalInventoryServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = LocalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = LocalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + return api_endpoint + + @staticmethod + def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = LocalInventoryServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, LocalInventoryServiceTransport, Callable[..., LocalInventoryServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the local inventory service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,LocalInventoryServiceTransport,Callable[..., LocalInventoryServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the LocalInventoryServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = LocalInventoryServiceClient._read_environment_variables() + self._client_cert_source = LocalInventoryServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = LocalInventoryServiceClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, LocalInventoryServiceTransport) + if transport_provided: + # transport is a LocalInventoryServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(LocalInventoryServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + LocalInventoryServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint)) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + transport_init: Union[Type[LocalInventoryServiceTransport], Callable[..., LocalInventoryServiceTransport]] = ( + LocalInventoryServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., LocalInventoryServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.shopping.merchant.inventories_v1beta.LocalInventoryServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._transport, "_credentials") else { + "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "credentialsType": None, + } + ) + + def list_local_inventories(self, + request: Optional[Union[localinventory.ListLocalInventoriesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLocalInventoriesPager: + r"""Lists the ``LocalInventory`` resources for the given product in + your merchant account. The response might contain fewer items + than specified by ``pageSize``. If ``pageToken`` was returned in + previous request, it can be used to obtain additional results. + + ``LocalInventory`` resources are listed per product for a given + account. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_inventories_v1beta + + def sample_list_local_inventories(): + # Create a client + client = merchant_inventories_v1beta.LocalInventoryServiceClient() + + # Initialize request argument(s) + request = merchant_inventories_v1beta.ListLocalInventoriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_local_inventories(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesRequest, dict]): + The request object. Request message for the ``ListLocalInventories`` method. + parent (str): + Required. The ``name`` of the parent product to list + local inventories for. Format: + ``accounts/{account}/products/{product}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.shopping.merchant_inventories_v1beta.services.local_inventory_service.pagers.ListLocalInventoriesPager: + Response message for the ListLocalInventories method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, localinventory.ListLocalInventoriesRequest): + request = localinventory.ListLocalInventoriesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_local_inventories] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListLocalInventoriesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def insert_local_inventory(self, + request: Optional[Union[localinventory.InsertLocalInventoryRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> localinventory.LocalInventory: + r"""Inserts a ``LocalInventory`` resource to a product in your + merchant account. + + Replaces the full ``LocalInventory`` resource if an entry with + the same + [``storeCode``][google.shopping.merchant.inventories.v1beta.LocalInventory.store_code] + already exists for the product. + + It might take up to 30 minutes for the new or updated + ``LocalInventory`` resource to appear in products. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_inventories_v1beta + + def sample_insert_local_inventory(): + # Create a client + client = merchant_inventories_v1beta.LocalInventoryServiceClient() + + # Initialize request argument(s) + local_inventory = merchant_inventories_v1beta.LocalInventory() + local_inventory.store_code = "store_code_value" + + request = merchant_inventories_v1beta.InsertLocalInventoryRequest( + parent="parent_value", + local_inventory=local_inventory, + ) + + # Make the request + response = client.insert_local_inventory(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_inventories_v1beta.types.InsertLocalInventoryRequest, dict]): + The request object. Request message for the ``InsertLocalInventory`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.shopping.merchant_inventories_v1beta.types.LocalInventory: + Local inventory information for the product. Represents in-store information + for a specific product at the store specified by + [storeCode][google.shopping.merchant.inventories.v1beta.LocalInventory.store_code]. + For a list of all accepted attribute values, see the + [local product inventory data + specification](\ https://support.google.com/merchants/answer/3061342). + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, localinventory.InsertLocalInventoryRequest): + request = localinventory.InsertLocalInventoryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.insert_local_inventory] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_local_inventory(self, + request: Optional[Union[localinventory.DeleteLocalInventoryRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes the specified ``LocalInventory`` from the given product + in your merchant account. It might take a up to an hour for the + ``LocalInventory`` to be deleted from the specific product. Once + you have received a successful delete response, wait for that + period before attempting a delete again. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_inventories_v1beta + + def sample_delete_local_inventory(): + # Create a client + client = merchant_inventories_v1beta.LocalInventoryServiceClient() + + # Initialize request argument(s) + request = merchant_inventories_v1beta.DeleteLocalInventoryRequest( + name="name_value", + ) + + # Make the request + client.delete_local_inventory(request=request) + + Args: + request (Union[google.shopping.merchant_inventories_v1beta.types.DeleteLocalInventoryRequest, dict]): + The request object. Request message for the ``DeleteLocalInventory`` method. + name (str): + Required. The name of the local inventory for the given + product to delete. Format: + ``accounts/{account}/products/{product}/localInventories/{store_code}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, localinventory.DeleteLocalInventoryRequest): + request = localinventory.DeleteLocalInventoryRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_local_inventory] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def __enter__(self) -> "LocalInventoryServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "LocalInventoryServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/pagers.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/pagers.py new file mode 100644 index 000000000000..185fea1c5d47 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/pagers.py @@ -0,0 +1,166 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.shopping.merchant_inventories_v1beta.types import localinventory + + +class ListLocalInventoriesPager: + """A pager for iterating through ``list_local_inventories`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``local_inventories`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListLocalInventories`` requests and continue to iterate + through the ``local_inventories`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., localinventory.ListLocalInventoriesResponse], + request: localinventory.ListLocalInventoriesRequest, + response: localinventory.ListLocalInventoriesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesRequest): + The initial request object. + response (google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = localinventory.ListLocalInventoriesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[localinventory.ListLocalInventoriesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[localinventory.LocalInventory]: + for page in self.pages: + yield from page.local_inventories + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListLocalInventoriesAsyncPager: + """A pager for iterating through ``list_local_inventories`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``local_inventories`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListLocalInventories`` requests and continue to iterate + through the ``local_inventories`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[localinventory.ListLocalInventoriesResponse]], + request: localinventory.ListLocalInventoriesRequest, + response: localinventory.ListLocalInventoriesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesRequest): + The initial request object. + response (google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = localinventory.ListLocalInventoriesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[localinventory.ListLocalInventoriesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[localinventory.LocalInventory]: + async def async_generator(): + async for page in self.pages: + for response in page.local_inventories: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/README.rst new file mode 100644 index 000000000000..816e98eb5847 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`LocalInventoryServiceTransport` is the ABC for all transports. +- public child `LocalInventoryServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `LocalInventoryServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseLocalInventoryServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `LocalInventoryServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/__init__.py new file mode 100644 index 000000000000..77e2551dd074 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import LocalInventoryServiceTransport +from .grpc import LocalInventoryServiceGrpcTransport +from .grpc_asyncio import LocalInventoryServiceGrpcAsyncIOTransport +from .rest import LocalInventoryServiceRestTransport +from .rest import LocalInventoryServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[LocalInventoryServiceTransport]] +_transport_registry['grpc'] = LocalInventoryServiceGrpcTransport +_transport_registry['grpc_asyncio'] = LocalInventoryServiceGrpcAsyncIOTransport +_transport_registry['rest'] = LocalInventoryServiceRestTransport + +__all__ = ( + 'LocalInventoryServiceTransport', + 'LocalInventoryServiceGrpcTransport', + 'LocalInventoryServiceGrpcAsyncIOTransport', + 'LocalInventoryServiceRestTransport', + 'LocalInventoryServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/base.py new file mode 100644 index 000000000000..1e299a9a0ba8 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/base.py @@ -0,0 +1,183 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.shopping.merchant_inventories_v1beta import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.protobuf import empty_pb2 # type: ignore +from google.shopping.merchant_inventories_v1beta.types import localinventory + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class LocalInventoryServiceTransport(abc.ABC): + """Abstract transport class for LocalInventoryService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/content', + ) + + DEFAULT_HOST: str = 'merchantapi.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'merchantapi.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_local_inventories: gapic_v1.method.wrap_method( + self.list_local_inventories, + default_timeout=None, + client_info=client_info, + ), + self.insert_local_inventory: gapic_v1.method.wrap_method( + self.insert_local_inventory, + default_timeout=None, + client_info=client_info, + ), + self.delete_local_inventory: gapic_v1.method.wrap_method( + self.delete_local_inventory, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def list_local_inventories(self) -> Callable[ + [localinventory.ListLocalInventoriesRequest], + Union[ + localinventory.ListLocalInventoriesResponse, + Awaitable[localinventory.ListLocalInventoriesResponse] + ]]: + raise NotImplementedError() + + @property + def insert_local_inventory(self) -> Callable[ + [localinventory.InsertLocalInventoryRequest], + Union[ + localinventory.LocalInventory, + Awaitable[localinventory.LocalInventory] + ]]: + raise NotImplementedError() + + @property + def delete_local_inventory(self) -> Callable[ + [localinventory.DeleteLocalInventoryRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'LocalInventoryServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/grpc.py new file mode 100644 index 000000000000..21eb1b3e88ba --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/grpc.py @@ -0,0 +1,419 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import pickle +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message + +import grpc # type: ignore +import proto # type: ignore + +from google.protobuf import empty_pb2 # type: ignore +from google.shopping.merchant_inventories_v1beta.types import localinventory +from .base import LocalInventoryServiceTransport, DEFAULT_CLIENT_INFO + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "rpcName": client_call_details.method, + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class LocalInventoryServiceGrpcTransport(LocalInventoryServiceTransport): + """gRPC backend transport for LocalInventoryService. + + Service to manage local inventory for products + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'merchantapi.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'merchantapi.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'merchantapi.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def list_local_inventories(self) -> Callable[ + [localinventory.ListLocalInventoriesRequest], + localinventory.ListLocalInventoriesResponse]: + r"""Return a callable for the list local inventories method over gRPC. + + Lists the ``LocalInventory`` resources for the given product in + your merchant account. The response might contain fewer items + than specified by ``pageSize``. If ``pageToken`` was returned in + previous request, it can be used to obtain additional results. + + ``LocalInventory`` resources are listed per product for a given + account. + + Returns: + Callable[[~.ListLocalInventoriesRequest], + ~.ListLocalInventoriesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_local_inventories' not in self._stubs: + self._stubs['list_local_inventories'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.inventories.v1beta.LocalInventoryService/ListLocalInventories', + request_serializer=localinventory.ListLocalInventoriesRequest.serialize, + response_deserializer=localinventory.ListLocalInventoriesResponse.deserialize, + ) + return self._stubs['list_local_inventories'] + + @property + def insert_local_inventory(self) -> Callable[ + [localinventory.InsertLocalInventoryRequest], + localinventory.LocalInventory]: + r"""Return a callable for the insert local inventory method over gRPC. + + Inserts a ``LocalInventory`` resource to a product in your + merchant account. + + Replaces the full ``LocalInventory`` resource if an entry with + the same + [``storeCode``][google.shopping.merchant.inventories.v1beta.LocalInventory.store_code] + already exists for the product. + + It might take up to 30 minutes for the new or updated + ``LocalInventory`` resource to appear in products. + + Returns: + Callable[[~.InsertLocalInventoryRequest], + ~.LocalInventory]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'insert_local_inventory' not in self._stubs: + self._stubs['insert_local_inventory'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.inventories.v1beta.LocalInventoryService/InsertLocalInventory', + request_serializer=localinventory.InsertLocalInventoryRequest.serialize, + response_deserializer=localinventory.LocalInventory.deserialize, + ) + return self._stubs['insert_local_inventory'] + + @property + def delete_local_inventory(self) -> Callable[ + [localinventory.DeleteLocalInventoryRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete local inventory method over gRPC. + + Deletes the specified ``LocalInventory`` from the given product + in your merchant account. It might take a up to an hour for the + ``LocalInventory`` to be deleted from the specific product. Once + you have received a successful delete response, wait for that + period before attempting a delete again. + + Returns: + Callable[[~.DeleteLocalInventoryRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_local_inventory' not in self._stubs: + self._stubs['delete_local_inventory'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.inventories.v1beta.LocalInventoryService/DeleteLocalInventory', + request_serializer=localinventory.DeleteLocalInventoryRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_local_inventory'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'LocalInventoryServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..a29b3d0a28e3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/grpc_asyncio.py @@ -0,0 +1,449 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import json +import pickle +import logging as std_logging +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import exceptions as core_exceptions +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message + +import grpc # type: ignore +import proto # type: ignore +from grpc.experimental import aio # type: ignore + +from google.protobuf import empty_pb2 # type: ignore +from google.shopping.merchant_inventories_v1beta.types import localinventory +from .base import LocalInventoryServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import LocalInventoryServiceGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class LocalInventoryServiceGrpcAsyncIOTransport(LocalInventoryServiceTransport): + """gRPC AsyncIO backend transport for LocalInventoryService. + + Service to manage local inventory for products + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'merchantapi.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'merchantapi.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'merchantapi.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_local_inventories(self) -> Callable[ + [localinventory.ListLocalInventoriesRequest], + Awaitable[localinventory.ListLocalInventoriesResponse]]: + r"""Return a callable for the list local inventories method over gRPC. + + Lists the ``LocalInventory`` resources for the given product in + your merchant account. The response might contain fewer items + than specified by ``pageSize``. If ``pageToken`` was returned in + previous request, it can be used to obtain additional results. + + ``LocalInventory`` resources are listed per product for a given + account. + + Returns: + Callable[[~.ListLocalInventoriesRequest], + Awaitable[~.ListLocalInventoriesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_local_inventories' not in self._stubs: + self._stubs['list_local_inventories'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.inventories.v1beta.LocalInventoryService/ListLocalInventories', + request_serializer=localinventory.ListLocalInventoriesRequest.serialize, + response_deserializer=localinventory.ListLocalInventoriesResponse.deserialize, + ) + return self._stubs['list_local_inventories'] + + @property + def insert_local_inventory(self) -> Callable[ + [localinventory.InsertLocalInventoryRequest], + Awaitable[localinventory.LocalInventory]]: + r"""Return a callable for the insert local inventory method over gRPC. + + Inserts a ``LocalInventory`` resource to a product in your + merchant account. + + Replaces the full ``LocalInventory`` resource if an entry with + the same + [``storeCode``][google.shopping.merchant.inventories.v1beta.LocalInventory.store_code] + already exists for the product. + + It might take up to 30 minutes for the new or updated + ``LocalInventory`` resource to appear in products. + + Returns: + Callable[[~.InsertLocalInventoryRequest], + Awaitable[~.LocalInventory]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'insert_local_inventory' not in self._stubs: + self._stubs['insert_local_inventory'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.inventories.v1beta.LocalInventoryService/InsertLocalInventory', + request_serializer=localinventory.InsertLocalInventoryRequest.serialize, + response_deserializer=localinventory.LocalInventory.deserialize, + ) + return self._stubs['insert_local_inventory'] + + @property + def delete_local_inventory(self) -> Callable[ + [localinventory.DeleteLocalInventoryRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete local inventory method over gRPC. + + Deletes the specified ``LocalInventory`` from the given product + in your merchant account. It might take a up to an hour for the + ``LocalInventory`` to be deleted from the specific product. Once + you have received a successful delete response, wait for that + period before attempting a delete again. + + Returns: + Callable[[~.DeleteLocalInventoryRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_local_inventory' not in self._stubs: + self._stubs['delete_local_inventory'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.inventories.v1beta.LocalInventoryService/DeleteLocalInventory', + request_serializer=localinventory.DeleteLocalInventoryRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_local_inventory'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.list_local_inventories: self._wrap_method( + self.list_local_inventories, + default_timeout=None, + client_info=client_info, + ), + self.insert_local_inventory: self._wrap_method( + self.insert_local_inventory, + default_timeout=None, + client_info=client_info, + ), + self.delete_local_inventory: self._wrap_method( + self.delete_local_inventory, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + +__all__ = ( + 'LocalInventoryServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/rest.py new file mode 100644 index 000000000000..2a7b87a761c7 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/rest.py @@ -0,0 +1,594 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +from google.protobuf import json_format + +from requests import __version__ as requests_version +import dataclasses +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + + +from google.protobuf import empty_pb2 # type: ignore +from google.shopping.merchant_inventories_v1beta.types import localinventory + + +from .rest_base import _BaseLocalInventoryServiceRestTransport +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + + +class LocalInventoryServiceRestInterceptor: + """Interceptor for LocalInventoryService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the LocalInventoryServiceRestTransport. + + .. code-block:: python + class MyCustomLocalInventoryServiceInterceptor(LocalInventoryServiceRestInterceptor): + def pre_delete_local_inventory(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_insert_local_inventory(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_insert_local_inventory(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_local_inventories(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_local_inventories(self, response): + logging.log(f"Received response: {response}") + return response + + transport = LocalInventoryServiceRestTransport(interceptor=MyCustomLocalInventoryServiceInterceptor()) + client = LocalInventoryServiceClient(transport=transport) + + + """ + def pre_delete_local_inventory(self, request: localinventory.DeleteLocalInventoryRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[localinventory.DeleteLocalInventoryRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_local_inventory + + Override in a subclass to manipulate the request or metadata + before they are sent to the LocalInventoryService server. + """ + return request, metadata + + def pre_insert_local_inventory(self, request: localinventory.InsertLocalInventoryRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[localinventory.InsertLocalInventoryRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for insert_local_inventory + + Override in a subclass to manipulate the request or metadata + before they are sent to the LocalInventoryService server. + """ + return request, metadata + + def post_insert_local_inventory(self, response: localinventory.LocalInventory) -> localinventory.LocalInventory: + """Post-rpc interceptor for insert_local_inventory + + Override in a subclass to manipulate the response + after it is returned by the LocalInventoryService server but before + it is returned to user code. + """ + return response + + def pre_list_local_inventories(self, request: localinventory.ListLocalInventoriesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[localinventory.ListLocalInventoriesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_local_inventories + + Override in a subclass to manipulate the request or metadata + before they are sent to the LocalInventoryService server. + """ + return request, metadata + + def post_list_local_inventories(self, response: localinventory.ListLocalInventoriesResponse) -> localinventory.ListLocalInventoriesResponse: + """Post-rpc interceptor for list_local_inventories + + Override in a subclass to manipulate the response + after it is returned by the LocalInventoryService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class LocalInventoryServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: LocalInventoryServiceRestInterceptor + + +class LocalInventoryServiceRestTransport(_BaseLocalInventoryServiceRestTransport): + """REST backend synchronous transport for LocalInventoryService. + + Service to manage local inventory for products + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__(self, *, + host: str = 'merchantapi.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[ + ], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + interceptor: Optional[LocalInventoryServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'merchantapi.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or LocalInventoryServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _DeleteLocalInventory(_BaseLocalInventoryServiceRestTransport._BaseDeleteLocalInventory, LocalInventoryServiceRestStub): + def __hash__(self): + return hash("LocalInventoryServiceRestTransport.DeleteLocalInventory") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: localinventory.DeleteLocalInventoryRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): + r"""Call the delete local inventory method over HTTP. + + Args: + request (~.localinventory.DeleteLocalInventoryRequest): + The request object. Request message for the ``DeleteLocalInventory`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseLocalInventoryServiceRestTransport._BaseDeleteLocalInventory._get_http_options() + + request, metadata = self._interceptor.pre_delete_local_inventory(request, metadata) + transcoded_request = _BaseLocalInventoryServiceRestTransport._BaseDeleteLocalInventory._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseLocalInventoryServiceRestTransport._BaseDeleteLocalInventory._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.shopping.merchant.inventories_v1beta.LocalInventoryServiceClient.DeleteLocalInventory", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "rpcName": "DeleteLocalInventory", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = LocalInventoryServiceRestTransport._DeleteLocalInventory._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _InsertLocalInventory(_BaseLocalInventoryServiceRestTransport._BaseInsertLocalInventory, LocalInventoryServiceRestStub): + def __hash__(self): + return hash("LocalInventoryServiceRestTransport.InsertLocalInventory") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: localinventory.InsertLocalInventoryRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> localinventory.LocalInventory: + r"""Call the insert local inventory method over HTTP. + + Args: + request (~.localinventory.InsertLocalInventoryRequest): + The request object. Request message for the ``InsertLocalInventory`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.localinventory.LocalInventory: + Local inventory information for the product. Represents + in-store information for a specific product at the store + specified by + [``storeCode``][google.shopping.merchant.inventories.v1beta.LocalInventory.store_code]. + For a list of all accepted attribute values, see the + `local product inventory data + specification `__. + + """ + + http_options = _BaseLocalInventoryServiceRestTransport._BaseInsertLocalInventory._get_http_options() + + request, metadata = self._interceptor.pre_insert_local_inventory(request, metadata) + transcoded_request = _BaseLocalInventoryServiceRestTransport._BaseInsertLocalInventory._get_transcoded_request(http_options, request) + + body = _BaseLocalInventoryServiceRestTransport._BaseInsertLocalInventory._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseLocalInventoryServiceRestTransport._BaseInsertLocalInventory._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.shopping.merchant.inventories_v1beta.LocalInventoryServiceClient.InsertLocalInventory", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "rpcName": "InsertLocalInventory", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = LocalInventoryServiceRestTransport._InsertLocalInventory._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = localinventory.LocalInventory() + pb_resp = localinventory.LocalInventory.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_insert_local_inventory(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = localinventory.LocalInventory.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.shopping.merchant.inventories_v1beta.LocalInventoryServiceClient.insert_local_inventory", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "rpcName": "InsertLocalInventory", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListLocalInventories(_BaseLocalInventoryServiceRestTransport._BaseListLocalInventories, LocalInventoryServiceRestStub): + def __hash__(self): + return hash("LocalInventoryServiceRestTransport.ListLocalInventories") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: localinventory.ListLocalInventoriesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> localinventory.ListLocalInventoriesResponse: + r"""Call the list local inventories method over HTTP. + + Args: + request (~.localinventory.ListLocalInventoriesRequest): + The request object. Request message for the ``ListLocalInventories`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.localinventory.ListLocalInventoriesResponse: + Response message for the ``ListLocalInventories`` + method. + + """ + + http_options = _BaseLocalInventoryServiceRestTransport._BaseListLocalInventories._get_http_options() + + request, metadata = self._interceptor.pre_list_local_inventories(request, metadata) + transcoded_request = _BaseLocalInventoryServiceRestTransport._BaseListLocalInventories._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseLocalInventoryServiceRestTransport._BaseListLocalInventories._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.shopping.merchant.inventories_v1beta.LocalInventoryServiceClient.ListLocalInventories", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "rpcName": "ListLocalInventories", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = LocalInventoryServiceRestTransport._ListLocalInventories._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = localinventory.ListLocalInventoriesResponse() + pb_resp = localinventory.ListLocalInventoriesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_local_inventories(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = localinventory.ListLocalInventoriesResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.shopping.merchant.inventories_v1beta.LocalInventoryServiceClient.list_local_inventories", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "rpcName": "ListLocalInventories", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def delete_local_inventory(self) -> Callable[ + [localinventory.DeleteLocalInventoryRequest], + empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteLocalInventory(self._session, self._host, self._interceptor) # type: ignore + + @property + def insert_local_inventory(self) -> Callable[ + [localinventory.InsertLocalInventoryRequest], + localinventory.LocalInventory]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._InsertLocalInventory(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_local_inventories(self) -> Callable[ + [localinventory.ListLocalInventoriesRequest], + localinventory.ListLocalInventoriesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListLocalInventories(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'LocalInventoryServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/rest_base.py new file mode 100644 index 000000000000..b032ed33070d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/rest_base.py @@ -0,0 +1,213 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json # type: ignore +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from .base import LocalInventoryServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.protobuf import empty_pb2 # type: ignore +from google.shopping.merchant_inventories_v1beta.types import localinventory + + +class _BaseLocalInventoryServiceRestTransport(LocalInventoryServiceTransport): + """Base REST backend transport for LocalInventoryService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__(self, *, + host: str = 'merchantapi.googleapis.com', + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'merchantapi.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + + class _BaseDeleteLocalInventory: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/inventories/v1beta/{name=accounts/*/products/*/localInventories/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = localinventory.DeleteLocalInventoryRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseLocalInventoryServiceRestTransport._BaseDeleteLocalInventory._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseInsertLocalInventory: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/inventories/v1beta/{parent=accounts/*/products/*}/localInventories:insert', + 'body': 'local_inventory', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = localinventory.InsertLocalInventoryRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseLocalInventoryServiceRestTransport._BaseInsertLocalInventory._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListLocalInventories: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/inventories/v1beta/{parent=accounts/*/products/*}/localInventories', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = localinventory.ListLocalInventoriesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseLocalInventoryServiceRestTransport._BaseListLocalInventories._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseLocalInventoryServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/__init__.py new file mode 100644 index 000000000000..1858a9e76b49 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import RegionalInventoryServiceClient +from .async_client import RegionalInventoryServiceAsyncClient + +__all__ = ( + 'RegionalInventoryServiceClient', + 'RegionalInventoryServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/async_client.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/async_client.py new file mode 100644 index 000000000000..cccbc1bdb3bc --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/async_client.py @@ -0,0 +1,591 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import logging as std_logging +from collections import OrderedDict +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.shopping.merchant_inventories_v1beta import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.shopping.merchant_inventories_v1beta.services.regional_inventory_service import pagers +from google.shopping.merchant_inventories_v1beta.types import regionalinventory +from google.shopping.type.types import types +from google.type import interval_pb2 # type: ignore +from .transports.base import RegionalInventoryServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import RegionalInventoryServiceGrpcAsyncIOTransport +from .client import RegionalInventoryServiceClient + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +class RegionalInventoryServiceAsyncClient: + """Service to manage regional inventory for products. There is also + separate ``regions`` resource and API to manage regions definitions. + """ + + _client: RegionalInventoryServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = RegionalInventoryServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = RegionalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = RegionalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = RegionalInventoryServiceClient._DEFAULT_UNIVERSE + + regional_inventory_path = staticmethod(RegionalInventoryServiceClient.regional_inventory_path) + parse_regional_inventory_path = staticmethod(RegionalInventoryServiceClient.parse_regional_inventory_path) + common_billing_account_path = staticmethod(RegionalInventoryServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(RegionalInventoryServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(RegionalInventoryServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(RegionalInventoryServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(RegionalInventoryServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(RegionalInventoryServiceClient.parse_common_organization_path) + common_project_path = staticmethod(RegionalInventoryServiceClient.common_project_path) + parse_common_project_path = staticmethod(RegionalInventoryServiceClient.parse_common_project_path) + common_location_path = staticmethod(RegionalInventoryServiceClient.common_location_path) + parse_common_location_path = staticmethod(RegionalInventoryServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RegionalInventoryServiceAsyncClient: The constructed client. + """ + return RegionalInventoryServiceClient.from_service_account_info.__func__(RegionalInventoryServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RegionalInventoryServiceAsyncClient: The constructed client. + """ + return RegionalInventoryServiceClient.from_service_account_file.__func__(RegionalInventoryServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return RegionalInventoryServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> RegionalInventoryServiceTransport: + """Returns the transport used by the client instance. + + Returns: + RegionalInventoryServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = RegionalInventoryServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, RegionalInventoryServiceTransport, Callable[..., RegionalInventoryServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the regional inventory service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,RegionalInventoryServiceTransport,Callable[..., RegionalInventoryServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the RegionalInventoryServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = RegionalInventoryServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.shopping.merchant.inventories_v1beta.RegionalInventoryServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._client._transport, "_credentials") else { + "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "credentialsType": None, + } + ) + + async def list_regional_inventories(self, + request: Optional[Union[regionalinventory.ListRegionalInventoriesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListRegionalInventoriesAsyncPager: + r"""Lists the ``RegionalInventory`` resources for the given product + in your merchant account. The response might contain fewer items + than specified by ``pageSize``. If ``pageToken`` was returned in + previous request, it can be used to obtain additional results. + + ``RegionalInventory`` resources are listed per product for a + given account. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_inventories_v1beta + + async def sample_list_regional_inventories(): + # Create a client + client = merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_inventories_v1beta.ListRegionalInventoriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_regional_inventories(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesRequest, dict]]): + The request object. Request message for the ``ListRegionalInventories`` + method. + parent (:class:`str`): + Required. The ``name`` of the parent product to list + ``RegionalInventory`` resources for. Format: + ``accounts/{account}/products/{product}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.pagers.ListRegionalInventoriesAsyncPager: + Response message for the ListRegionalInventories method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, regionalinventory.ListRegionalInventoriesRequest): + request = regionalinventory.ListRegionalInventoriesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_regional_inventories] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListRegionalInventoriesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def insert_regional_inventory(self, + request: Optional[Union[regionalinventory.InsertRegionalInventoryRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> regionalinventory.RegionalInventory: + r"""Inserts a ``RegionalInventory`` to a given product in your + merchant account. + + Replaces the full ``RegionalInventory`` resource if an entry + with the same + [``region``][google.shopping.merchant.inventories.v1beta.RegionalInventory.region] + already exists for the product. + + It might take up to 30 minutes for the new or updated + ``RegionalInventory`` resource to appear in products. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_inventories_v1beta + + async def sample_insert_regional_inventory(): + # Create a client + client = merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient() + + # Initialize request argument(s) + regional_inventory = merchant_inventories_v1beta.RegionalInventory() + regional_inventory.region = "region_value" + + request = merchant_inventories_v1beta.InsertRegionalInventoryRequest( + parent="parent_value", + regional_inventory=regional_inventory, + ) + + # Make the request + response = await client.insert_regional_inventory(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_inventories_v1beta.types.InsertRegionalInventoryRequest, dict]]): + The request object. Request message for the ``InsertRegionalInventory`` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.shopping.merchant_inventories_v1beta.types.RegionalInventory: + Regional inventory information for the product. Represents specific + information like price and availability for a given + product in a specific + [region][google.shopping.merchant.inventories.v1beta.RegionalInventory.region]. + For a list of all accepted attribute values, see the + [regional product inventory data + specification](\ https://support.google.com/merchants/answer/9698880). + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, regionalinventory.InsertRegionalInventoryRequest): + request = regionalinventory.InsertRegionalInventoryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.insert_regional_inventory] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_regional_inventory(self, + request: Optional[Union[regionalinventory.DeleteRegionalInventoryRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes the specified ``RegionalInventory`` resource from the + given product in your merchant account. It might take up to an + hour for the ``RegionalInventory`` to be deleted from the + specific product. Once you have received a successful delete + response, wait for that period before attempting a delete again. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_inventories_v1beta + + async def sample_delete_regional_inventory(): + # Create a client + client = merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_inventories_v1beta.DeleteRegionalInventoryRequest( + name="name_value", + ) + + # Make the request + await client.delete_regional_inventory(request=request) + + Args: + request (Optional[Union[google.shopping.merchant_inventories_v1beta.types.DeleteRegionalInventoryRequest, dict]]): + The request object. Request message for the ``DeleteRegionalInventory`` + method. + name (:class:`str`): + Required. The name of the ``RegionalInventory`` resource + to delete. Format: + ``accounts/{account}/products/{product}/regionalInventories/{region}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, regionalinventory.DeleteRegionalInventoryRequest): + request = regionalinventory.DeleteRegionalInventoryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_regional_inventory] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def __aenter__(self) -> "RegionalInventoryServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "RegionalInventoryServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/client.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/client.py new file mode 100644 index 000000000000..68f368040075 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/client.py @@ -0,0 +1,925 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +import logging as std_logging +import os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.shopping.merchant_inventories_v1beta import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +from google.shopping.merchant_inventories_v1beta.services.regional_inventory_service import pagers +from google.shopping.merchant_inventories_v1beta.types import regionalinventory +from google.shopping.type.types import types +from google.type import interval_pb2 # type: ignore +from .transports.base import RegionalInventoryServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import RegionalInventoryServiceGrpcTransport +from .transports.grpc_asyncio import RegionalInventoryServiceGrpcAsyncIOTransport +from .transports.rest import RegionalInventoryServiceRestTransport + + +class RegionalInventoryServiceClientMeta(type): + """Metaclass for the RegionalInventoryService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[RegionalInventoryServiceTransport]] + _transport_registry["grpc"] = RegionalInventoryServiceGrpcTransport + _transport_registry["grpc_asyncio"] = RegionalInventoryServiceGrpcAsyncIOTransport + _transport_registry["rest"] = RegionalInventoryServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[RegionalInventoryServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class RegionalInventoryServiceClient(metaclass=RegionalInventoryServiceClientMeta): + """Service to manage regional inventory for products. There is also + separate ``regions`` resource and API to manage regions definitions. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "merchantapi.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "merchantapi.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RegionalInventoryServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RegionalInventoryServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> RegionalInventoryServiceTransport: + """Returns the transport used by the client instance. + + Returns: + RegionalInventoryServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def regional_inventory_path(account: str,product: str,region: str,) -> str: + """Returns a fully-qualified regional_inventory string.""" + return "accounts/{account}/products/{product}/regionalInventories/{region}".format(account=account, product=product, region=region, ) + + @staticmethod + def parse_regional_inventory_path(path: str) -> Dict[str,str]: + """Parses a regional_inventory path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/products/(?P.+?)/regionalInventories/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + _default_universe = RegionalInventoryServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = RegionalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = RegionalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + return api_endpoint + + @staticmethod + def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = RegionalInventoryServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, RegionalInventoryServiceTransport, Callable[..., RegionalInventoryServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the regional inventory service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,RegionalInventoryServiceTransport,Callable[..., RegionalInventoryServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the RegionalInventoryServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = RegionalInventoryServiceClient._read_environment_variables() + self._client_cert_source = RegionalInventoryServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = RegionalInventoryServiceClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, RegionalInventoryServiceTransport) + if transport_provided: + # transport is a RegionalInventoryServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(RegionalInventoryServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + RegionalInventoryServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint)) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + transport_init: Union[Type[RegionalInventoryServiceTransport], Callable[..., RegionalInventoryServiceTransport]] = ( + RegionalInventoryServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., RegionalInventoryServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.shopping.merchant.inventories_v1beta.RegionalInventoryServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._transport, "_credentials") else { + "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "credentialsType": None, + } + ) + + def list_regional_inventories(self, + request: Optional[Union[regionalinventory.ListRegionalInventoriesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListRegionalInventoriesPager: + r"""Lists the ``RegionalInventory`` resources for the given product + in your merchant account. The response might contain fewer items + than specified by ``pageSize``. If ``pageToken`` was returned in + previous request, it can be used to obtain additional results. + + ``RegionalInventory`` resources are listed per product for a + given account. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_inventories_v1beta + + def sample_list_regional_inventories(): + # Create a client + client = merchant_inventories_v1beta.RegionalInventoryServiceClient() + + # Initialize request argument(s) + request = merchant_inventories_v1beta.ListRegionalInventoriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_regional_inventories(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesRequest, dict]): + The request object. Request message for the ``ListRegionalInventories`` + method. + parent (str): + Required. The ``name`` of the parent product to list + ``RegionalInventory`` resources for. Format: + ``accounts/{account}/products/{product}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.pagers.ListRegionalInventoriesPager: + Response message for the ListRegionalInventories method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, regionalinventory.ListRegionalInventoriesRequest): + request = regionalinventory.ListRegionalInventoriesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_regional_inventories] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListRegionalInventoriesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def insert_regional_inventory(self, + request: Optional[Union[regionalinventory.InsertRegionalInventoryRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> regionalinventory.RegionalInventory: + r"""Inserts a ``RegionalInventory`` to a given product in your + merchant account. + + Replaces the full ``RegionalInventory`` resource if an entry + with the same + [``region``][google.shopping.merchant.inventories.v1beta.RegionalInventory.region] + already exists for the product. + + It might take up to 30 minutes for the new or updated + ``RegionalInventory`` resource to appear in products. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_inventories_v1beta + + def sample_insert_regional_inventory(): + # Create a client + client = merchant_inventories_v1beta.RegionalInventoryServiceClient() + + # Initialize request argument(s) + regional_inventory = merchant_inventories_v1beta.RegionalInventory() + regional_inventory.region = "region_value" + + request = merchant_inventories_v1beta.InsertRegionalInventoryRequest( + parent="parent_value", + regional_inventory=regional_inventory, + ) + + # Make the request + response = client.insert_regional_inventory(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_inventories_v1beta.types.InsertRegionalInventoryRequest, dict]): + The request object. Request message for the ``InsertRegionalInventory`` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.shopping.merchant_inventories_v1beta.types.RegionalInventory: + Regional inventory information for the product. Represents specific + information like price and availability for a given + product in a specific + [region][google.shopping.merchant.inventories.v1beta.RegionalInventory.region]. + For a list of all accepted attribute values, see the + [regional product inventory data + specification](\ https://support.google.com/merchants/answer/9698880). + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, regionalinventory.InsertRegionalInventoryRequest): + request = regionalinventory.InsertRegionalInventoryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.insert_regional_inventory] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_regional_inventory(self, + request: Optional[Union[regionalinventory.DeleteRegionalInventoryRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes the specified ``RegionalInventory`` resource from the + given product in your merchant account. It might take up to an + hour for the ``RegionalInventory`` to be deleted from the + specific product. Once you have received a successful delete + response, wait for that period before attempting a delete again. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_inventories_v1beta + + def sample_delete_regional_inventory(): + # Create a client + client = merchant_inventories_v1beta.RegionalInventoryServiceClient() + + # Initialize request argument(s) + request = merchant_inventories_v1beta.DeleteRegionalInventoryRequest( + name="name_value", + ) + + # Make the request + client.delete_regional_inventory(request=request) + + Args: + request (Union[google.shopping.merchant_inventories_v1beta.types.DeleteRegionalInventoryRequest, dict]): + The request object. Request message for the ``DeleteRegionalInventory`` + method. + name (str): + Required. The name of the ``RegionalInventory`` resource + to delete. Format: + ``accounts/{account}/products/{product}/regionalInventories/{region}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, regionalinventory.DeleteRegionalInventoryRequest): + request = regionalinventory.DeleteRegionalInventoryRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_regional_inventory] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def __enter__(self) -> "RegionalInventoryServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "RegionalInventoryServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/pagers.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/pagers.py new file mode 100644 index 000000000000..e993198f8953 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/pagers.py @@ -0,0 +1,166 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.shopping.merchant_inventories_v1beta.types import regionalinventory + + +class ListRegionalInventoriesPager: + """A pager for iterating through ``list_regional_inventories`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``regional_inventories`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListRegionalInventories`` requests and continue to iterate + through the ``regional_inventories`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., regionalinventory.ListRegionalInventoriesResponse], + request: regionalinventory.ListRegionalInventoriesRequest, + response: regionalinventory.ListRegionalInventoriesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesRequest): + The initial request object. + response (google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = regionalinventory.ListRegionalInventoriesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[regionalinventory.ListRegionalInventoriesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[regionalinventory.RegionalInventory]: + for page in self.pages: + yield from page.regional_inventories + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListRegionalInventoriesAsyncPager: + """A pager for iterating through ``list_regional_inventories`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``regional_inventories`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListRegionalInventories`` requests and continue to iterate + through the ``regional_inventories`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[regionalinventory.ListRegionalInventoriesResponse]], + request: regionalinventory.ListRegionalInventoriesRequest, + response: regionalinventory.ListRegionalInventoriesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesRequest): + The initial request object. + response (google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = regionalinventory.ListRegionalInventoriesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[regionalinventory.ListRegionalInventoriesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[regionalinventory.RegionalInventory]: + async def async_generator(): + async for page in self.pages: + for response in page.regional_inventories: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/README.rst new file mode 100644 index 000000000000..0b66f48dbd0c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`RegionalInventoryServiceTransport` is the ABC for all transports. +- public child `RegionalInventoryServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `RegionalInventoryServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseRegionalInventoryServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `RegionalInventoryServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/__init__.py new file mode 100644 index 000000000000..8e46523d873a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import RegionalInventoryServiceTransport +from .grpc import RegionalInventoryServiceGrpcTransport +from .grpc_asyncio import RegionalInventoryServiceGrpcAsyncIOTransport +from .rest import RegionalInventoryServiceRestTransport +from .rest import RegionalInventoryServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[RegionalInventoryServiceTransport]] +_transport_registry['grpc'] = RegionalInventoryServiceGrpcTransport +_transport_registry['grpc_asyncio'] = RegionalInventoryServiceGrpcAsyncIOTransport +_transport_registry['rest'] = RegionalInventoryServiceRestTransport + +__all__ = ( + 'RegionalInventoryServiceTransport', + 'RegionalInventoryServiceGrpcTransport', + 'RegionalInventoryServiceGrpcAsyncIOTransport', + 'RegionalInventoryServiceRestTransport', + 'RegionalInventoryServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/base.py new file mode 100644 index 000000000000..415c38742b8b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/base.py @@ -0,0 +1,183 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.shopping.merchant_inventories_v1beta import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.protobuf import empty_pb2 # type: ignore +from google.shopping.merchant_inventories_v1beta.types import regionalinventory + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class RegionalInventoryServiceTransport(abc.ABC): + """Abstract transport class for RegionalInventoryService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/content', + ) + + DEFAULT_HOST: str = 'merchantapi.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'merchantapi.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_regional_inventories: gapic_v1.method.wrap_method( + self.list_regional_inventories, + default_timeout=None, + client_info=client_info, + ), + self.insert_regional_inventory: gapic_v1.method.wrap_method( + self.insert_regional_inventory, + default_timeout=None, + client_info=client_info, + ), + self.delete_regional_inventory: gapic_v1.method.wrap_method( + self.delete_regional_inventory, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def list_regional_inventories(self) -> Callable[ + [regionalinventory.ListRegionalInventoriesRequest], + Union[ + regionalinventory.ListRegionalInventoriesResponse, + Awaitable[regionalinventory.ListRegionalInventoriesResponse] + ]]: + raise NotImplementedError() + + @property + def insert_regional_inventory(self) -> Callable[ + [regionalinventory.InsertRegionalInventoryRequest], + Union[ + regionalinventory.RegionalInventory, + Awaitable[regionalinventory.RegionalInventory] + ]]: + raise NotImplementedError() + + @property + def delete_regional_inventory(self) -> Callable[ + [regionalinventory.DeleteRegionalInventoryRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'RegionalInventoryServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/grpc.py new file mode 100644 index 000000000000..00d8041052a3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/grpc.py @@ -0,0 +1,420 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import pickle +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message + +import grpc # type: ignore +import proto # type: ignore + +from google.protobuf import empty_pb2 # type: ignore +from google.shopping.merchant_inventories_v1beta.types import regionalinventory +from .base import RegionalInventoryServiceTransport, DEFAULT_CLIENT_INFO + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "rpcName": client_call_details.method, + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class RegionalInventoryServiceGrpcTransport(RegionalInventoryServiceTransport): + """gRPC backend transport for RegionalInventoryService. + + Service to manage regional inventory for products. There is also + separate ``regions`` resource and API to manage regions definitions. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'merchantapi.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'merchantapi.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'merchantapi.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def list_regional_inventories(self) -> Callable[ + [regionalinventory.ListRegionalInventoriesRequest], + regionalinventory.ListRegionalInventoriesResponse]: + r"""Return a callable for the list regional inventories method over gRPC. + + Lists the ``RegionalInventory`` resources for the given product + in your merchant account. The response might contain fewer items + than specified by ``pageSize``. If ``pageToken`` was returned in + previous request, it can be used to obtain additional results. + + ``RegionalInventory`` resources are listed per product for a + given account. + + Returns: + Callable[[~.ListRegionalInventoriesRequest], + ~.ListRegionalInventoriesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_regional_inventories' not in self._stubs: + self._stubs['list_regional_inventories'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.inventories.v1beta.RegionalInventoryService/ListRegionalInventories', + request_serializer=regionalinventory.ListRegionalInventoriesRequest.serialize, + response_deserializer=regionalinventory.ListRegionalInventoriesResponse.deserialize, + ) + return self._stubs['list_regional_inventories'] + + @property + def insert_regional_inventory(self) -> Callable[ + [regionalinventory.InsertRegionalInventoryRequest], + regionalinventory.RegionalInventory]: + r"""Return a callable for the insert regional inventory method over gRPC. + + Inserts a ``RegionalInventory`` to a given product in your + merchant account. + + Replaces the full ``RegionalInventory`` resource if an entry + with the same + [``region``][google.shopping.merchant.inventories.v1beta.RegionalInventory.region] + already exists for the product. + + It might take up to 30 minutes for the new or updated + ``RegionalInventory`` resource to appear in products. + + Returns: + Callable[[~.InsertRegionalInventoryRequest], + ~.RegionalInventory]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'insert_regional_inventory' not in self._stubs: + self._stubs['insert_regional_inventory'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.inventories.v1beta.RegionalInventoryService/InsertRegionalInventory', + request_serializer=regionalinventory.InsertRegionalInventoryRequest.serialize, + response_deserializer=regionalinventory.RegionalInventory.deserialize, + ) + return self._stubs['insert_regional_inventory'] + + @property + def delete_regional_inventory(self) -> Callable[ + [regionalinventory.DeleteRegionalInventoryRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete regional inventory method over gRPC. + + Deletes the specified ``RegionalInventory`` resource from the + given product in your merchant account. It might take up to an + hour for the ``RegionalInventory`` to be deleted from the + specific product. Once you have received a successful delete + response, wait for that period before attempting a delete again. + + Returns: + Callable[[~.DeleteRegionalInventoryRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_regional_inventory' not in self._stubs: + self._stubs['delete_regional_inventory'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.inventories.v1beta.RegionalInventoryService/DeleteRegionalInventory', + request_serializer=regionalinventory.DeleteRegionalInventoryRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_regional_inventory'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'RegionalInventoryServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..22f4431d5d53 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/grpc_asyncio.py @@ -0,0 +1,450 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import json +import pickle +import logging as std_logging +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import exceptions as core_exceptions +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message + +import grpc # type: ignore +import proto # type: ignore +from grpc.experimental import aio # type: ignore + +from google.protobuf import empty_pb2 # type: ignore +from google.shopping.merchant_inventories_v1beta.types import regionalinventory +from .base import RegionalInventoryServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import RegionalInventoryServiceGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class RegionalInventoryServiceGrpcAsyncIOTransport(RegionalInventoryServiceTransport): + """gRPC AsyncIO backend transport for RegionalInventoryService. + + Service to manage regional inventory for products. There is also + separate ``regions`` resource and API to manage regions definitions. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'merchantapi.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'merchantapi.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'merchantapi.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_regional_inventories(self) -> Callable[ + [regionalinventory.ListRegionalInventoriesRequest], + Awaitable[regionalinventory.ListRegionalInventoriesResponse]]: + r"""Return a callable for the list regional inventories method over gRPC. + + Lists the ``RegionalInventory`` resources for the given product + in your merchant account. The response might contain fewer items + than specified by ``pageSize``. If ``pageToken`` was returned in + previous request, it can be used to obtain additional results. + + ``RegionalInventory`` resources are listed per product for a + given account. + + Returns: + Callable[[~.ListRegionalInventoriesRequest], + Awaitable[~.ListRegionalInventoriesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_regional_inventories' not in self._stubs: + self._stubs['list_regional_inventories'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.inventories.v1beta.RegionalInventoryService/ListRegionalInventories', + request_serializer=regionalinventory.ListRegionalInventoriesRequest.serialize, + response_deserializer=regionalinventory.ListRegionalInventoriesResponse.deserialize, + ) + return self._stubs['list_regional_inventories'] + + @property + def insert_regional_inventory(self) -> Callable[ + [regionalinventory.InsertRegionalInventoryRequest], + Awaitable[regionalinventory.RegionalInventory]]: + r"""Return a callable for the insert regional inventory method over gRPC. + + Inserts a ``RegionalInventory`` to a given product in your + merchant account. + + Replaces the full ``RegionalInventory`` resource if an entry + with the same + [``region``][google.shopping.merchant.inventories.v1beta.RegionalInventory.region] + already exists for the product. + + It might take up to 30 minutes for the new or updated + ``RegionalInventory`` resource to appear in products. + + Returns: + Callable[[~.InsertRegionalInventoryRequest], + Awaitable[~.RegionalInventory]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'insert_regional_inventory' not in self._stubs: + self._stubs['insert_regional_inventory'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.inventories.v1beta.RegionalInventoryService/InsertRegionalInventory', + request_serializer=regionalinventory.InsertRegionalInventoryRequest.serialize, + response_deserializer=regionalinventory.RegionalInventory.deserialize, + ) + return self._stubs['insert_regional_inventory'] + + @property + def delete_regional_inventory(self) -> Callable[ + [regionalinventory.DeleteRegionalInventoryRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete regional inventory method over gRPC. + + Deletes the specified ``RegionalInventory`` resource from the + given product in your merchant account. It might take up to an + hour for the ``RegionalInventory`` to be deleted from the + specific product. Once you have received a successful delete + response, wait for that period before attempting a delete again. + + Returns: + Callable[[~.DeleteRegionalInventoryRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_regional_inventory' not in self._stubs: + self._stubs['delete_regional_inventory'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.inventories.v1beta.RegionalInventoryService/DeleteRegionalInventory', + request_serializer=regionalinventory.DeleteRegionalInventoryRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_regional_inventory'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.list_regional_inventories: self._wrap_method( + self.list_regional_inventories, + default_timeout=None, + client_info=client_info, + ), + self.insert_regional_inventory: self._wrap_method( + self.insert_regional_inventory, + default_timeout=None, + client_info=client_info, + ), + self.delete_regional_inventory: self._wrap_method( + self.delete_regional_inventory, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + +__all__ = ( + 'RegionalInventoryServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/rest.py new file mode 100644 index 000000000000..cb2352f27d10 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/rest.py @@ -0,0 +1,598 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +from google.protobuf import json_format + +from requests import __version__ as requests_version +import dataclasses +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + + +from google.protobuf import empty_pb2 # type: ignore +from google.shopping.merchant_inventories_v1beta.types import regionalinventory + + +from .rest_base import _BaseRegionalInventoryServiceRestTransport +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + + +class RegionalInventoryServiceRestInterceptor: + """Interceptor for RegionalInventoryService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the RegionalInventoryServiceRestTransport. + + .. code-block:: python + class MyCustomRegionalInventoryServiceInterceptor(RegionalInventoryServiceRestInterceptor): + def pre_delete_regional_inventory(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_insert_regional_inventory(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_insert_regional_inventory(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_regional_inventories(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_regional_inventories(self, response): + logging.log(f"Received response: {response}") + return response + + transport = RegionalInventoryServiceRestTransport(interceptor=MyCustomRegionalInventoryServiceInterceptor()) + client = RegionalInventoryServiceClient(transport=transport) + + + """ + def pre_delete_regional_inventory(self, request: regionalinventory.DeleteRegionalInventoryRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regionalinventory.DeleteRegionalInventoryRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_regional_inventory + + Override in a subclass to manipulate the request or metadata + before they are sent to the RegionalInventoryService server. + """ + return request, metadata + + def pre_insert_regional_inventory(self, request: regionalinventory.InsertRegionalInventoryRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regionalinventory.InsertRegionalInventoryRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for insert_regional_inventory + + Override in a subclass to manipulate the request or metadata + before they are sent to the RegionalInventoryService server. + """ + return request, metadata + + def post_insert_regional_inventory(self, response: regionalinventory.RegionalInventory) -> regionalinventory.RegionalInventory: + """Post-rpc interceptor for insert_regional_inventory + + Override in a subclass to manipulate the response + after it is returned by the RegionalInventoryService server but before + it is returned to user code. + """ + return response + + def pre_list_regional_inventories(self, request: regionalinventory.ListRegionalInventoriesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regionalinventory.ListRegionalInventoriesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_regional_inventories + + Override in a subclass to manipulate the request or metadata + before they are sent to the RegionalInventoryService server. + """ + return request, metadata + + def post_list_regional_inventories(self, response: regionalinventory.ListRegionalInventoriesResponse) -> regionalinventory.ListRegionalInventoriesResponse: + """Post-rpc interceptor for list_regional_inventories + + Override in a subclass to manipulate the response + after it is returned by the RegionalInventoryService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class RegionalInventoryServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: RegionalInventoryServiceRestInterceptor + + +class RegionalInventoryServiceRestTransport(_BaseRegionalInventoryServiceRestTransport): + """REST backend synchronous transport for RegionalInventoryService. + + Service to manage regional inventory for products. There is also + separate ``regions`` resource and API to manage regions definitions. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__(self, *, + host: str = 'merchantapi.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[ + ], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + interceptor: Optional[RegionalInventoryServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'merchantapi.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or RegionalInventoryServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _DeleteRegionalInventory(_BaseRegionalInventoryServiceRestTransport._BaseDeleteRegionalInventory, RegionalInventoryServiceRestStub): + def __hash__(self): + return hash("RegionalInventoryServiceRestTransport.DeleteRegionalInventory") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: regionalinventory.DeleteRegionalInventoryRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): + r"""Call the delete regional inventory method over HTTP. + + Args: + request (~.regionalinventory.DeleteRegionalInventoryRequest): + The request object. Request message for the ``DeleteRegionalInventory`` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseRegionalInventoryServiceRestTransport._BaseDeleteRegionalInventory._get_http_options() + + request, metadata = self._interceptor.pre_delete_regional_inventory(request, metadata) + transcoded_request = _BaseRegionalInventoryServiceRestTransport._BaseDeleteRegionalInventory._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseRegionalInventoryServiceRestTransport._BaseDeleteRegionalInventory._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.shopping.merchant.inventories_v1beta.RegionalInventoryServiceClient.DeleteRegionalInventory", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "rpcName": "DeleteRegionalInventory", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RegionalInventoryServiceRestTransport._DeleteRegionalInventory._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _InsertRegionalInventory(_BaseRegionalInventoryServiceRestTransport._BaseInsertRegionalInventory, RegionalInventoryServiceRestStub): + def __hash__(self): + return hash("RegionalInventoryServiceRestTransport.InsertRegionalInventory") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: regionalinventory.InsertRegionalInventoryRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> regionalinventory.RegionalInventory: + r"""Call the insert regional inventory method over HTTP. + + Args: + request (~.regionalinventory.InsertRegionalInventoryRequest): + The request object. Request message for the ``InsertRegionalInventory`` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.regionalinventory.RegionalInventory: + Regional inventory information for the product. + Represents specific information like price and + availability for a given product in a specific + [``region``][google.shopping.merchant.inventories.v1beta.RegionalInventory.region]. + For a list of all accepted attribute values, see the + `regional product inventory data + specification `__. + + """ + + http_options = _BaseRegionalInventoryServiceRestTransport._BaseInsertRegionalInventory._get_http_options() + + request, metadata = self._interceptor.pre_insert_regional_inventory(request, metadata) + transcoded_request = _BaseRegionalInventoryServiceRestTransport._BaseInsertRegionalInventory._get_transcoded_request(http_options, request) + + body = _BaseRegionalInventoryServiceRestTransport._BaseInsertRegionalInventory._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseRegionalInventoryServiceRestTransport._BaseInsertRegionalInventory._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.shopping.merchant.inventories_v1beta.RegionalInventoryServiceClient.InsertRegionalInventory", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "rpcName": "InsertRegionalInventory", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RegionalInventoryServiceRestTransport._InsertRegionalInventory._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = regionalinventory.RegionalInventory() + pb_resp = regionalinventory.RegionalInventory.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_insert_regional_inventory(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = regionalinventory.RegionalInventory.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.shopping.merchant.inventories_v1beta.RegionalInventoryServiceClient.insert_regional_inventory", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "rpcName": "InsertRegionalInventory", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListRegionalInventories(_BaseRegionalInventoryServiceRestTransport._BaseListRegionalInventories, RegionalInventoryServiceRestStub): + def __hash__(self): + return hash("RegionalInventoryServiceRestTransport.ListRegionalInventories") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: regionalinventory.ListRegionalInventoriesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> regionalinventory.ListRegionalInventoriesResponse: + r"""Call the list regional inventories method over HTTP. + + Args: + request (~.regionalinventory.ListRegionalInventoriesRequest): + The request object. Request message for the ``ListRegionalInventories`` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.regionalinventory.ListRegionalInventoriesResponse: + Response message for the ``ListRegionalInventories`` + method. + + """ + + http_options = _BaseRegionalInventoryServiceRestTransport._BaseListRegionalInventories._get_http_options() + + request, metadata = self._interceptor.pre_list_regional_inventories(request, metadata) + transcoded_request = _BaseRegionalInventoryServiceRestTransport._BaseListRegionalInventories._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseRegionalInventoryServiceRestTransport._BaseListRegionalInventories._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.shopping.merchant.inventories_v1beta.RegionalInventoryServiceClient.ListRegionalInventories", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "rpcName": "ListRegionalInventories", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RegionalInventoryServiceRestTransport._ListRegionalInventories._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = regionalinventory.ListRegionalInventoriesResponse() + pb_resp = regionalinventory.ListRegionalInventoriesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_regional_inventories(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = regionalinventory.ListRegionalInventoriesResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.shopping.merchant.inventories_v1beta.RegionalInventoryServiceClient.list_regional_inventories", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "rpcName": "ListRegionalInventories", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def delete_regional_inventory(self) -> Callable[ + [regionalinventory.DeleteRegionalInventoryRequest], + empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteRegionalInventory(self._session, self._host, self._interceptor) # type: ignore + + @property + def insert_regional_inventory(self) -> Callable[ + [regionalinventory.InsertRegionalInventoryRequest], + regionalinventory.RegionalInventory]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._InsertRegionalInventory(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_regional_inventories(self) -> Callable[ + [regionalinventory.ListRegionalInventoriesRequest], + regionalinventory.ListRegionalInventoriesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListRegionalInventories(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'RegionalInventoryServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/rest_base.py new file mode 100644 index 000000000000..c2a7417ff9c0 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/rest_base.py @@ -0,0 +1,213 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json # type: ignore +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from .base import RegionalInventoryServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.protobuf import empty_pb2 # type: ignore +from google.shopping.merchant_inventories_v1beta.types import regionalinventory + + +class _BaseRegionalInventoryServiceRestTransport(RegionalInventoryServiceTransport): + """Base REST backend transport for RegionalInventoryService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__(self, *, + host: str = 'merchantapi.googleapis.com', + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'merchantapi.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + + class _BaseDeleteRegionalInventory: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/inventories/v1beta/{name=accounts/*/products/*/regionalInventories/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = regionalinventory.DeleteRegionalInventoryRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseRegionalInventoryServiceRestTransport._BaseDeleteRegionalInventory._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseInsertRegionalInventory: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/inventories/v1beta/{parent=accounts/*/products/*}/regionalInventories:insert', + 'body': 'regional_inventory', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = regionalinventory.InsertRegionalInventoryRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseRegionalInventoryServiceRestTransport._BaseInsertRegionalInventory._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListRegionalInventories: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/inventories/v1beta/{parent=accounts/*/products/*}/regionalInventories', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = regionalinventory.ListRegionalInventoriesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseRegionalInventoryServiceRestTransport._BaseListRegionalInventories._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseRegionalInventoryServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/__init__.py new file mode 100644 index 000000000000..e9443375bc16 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/__init__.py @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .localinventory import ( + DeleteLocalInventoryRequest, + InsertLocalInventoryRequest, + ListLocalInventoriesRequest, + ListLocalInventoriesResponse, + LocalInventory, +) +from .regionalinventory import ( + DeleteRegionalInventoryRequest, + InsertRegionalInventoryRequest, + ListRegionalInventoriesRequest, + ListRegionalInventoriesResponse, + RegionalInventory, +) + +__all__ = ( + 'DeleteLocalInventoryRequest', + 'InsertLocalInventoryRequest', + 'ListLocalInventoriesRequest', + 'ListLocalInventoriesResponse', + 'LocalInventory', + 'DeleteRegionalInventoryRequest', + 'InsertRegionalInventoryRequest', + 'ListRegionalInventoriesRequest', + 'ListRegionalInventoriesResponse', + 'RegionalInventory', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/localinventory.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/localinventory.py new file mode 100644 index 000000000000..ce4ed8566637 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/localinventory.py @@ -0,0 +1,281 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.shopping.type.types import types +from google.type import interval_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.shopping.merchant.inventories.v1beta', + manifest={ + 'LocalInventory', + 'ListLocalInventoriesRequest', + 'ListLocalInventoriesResponse', + 'InsertLocalInventoryRequest', + 'DeleteLocalInventoryRequest', + }, +) + + +class LocalInventory(proto.Message): + r"""Local inventory information for the product. Represents in-store + information for a specific product at the store specified by + [``storeCode``][google.shopping.merchant.inventories.v1beta.LocalInventory.store_code]. + For a list of all accepted attribute values, see the `local product + inventory data + specification `__. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Output only. The name of the ``LocalInventory`` resource. + Format: + ``accounts/{account}/products/{product}/localInventories/{store_code}`` + account (int): + Output only. The account that owns the + product. This field will be ignored if set by + the client. + store_code (str): + Required. Immutable. Store code (the store ID from your + Business Profile) of the physical store the product is sold + in. See the `Local product inventory data + specification `__ + for more information. + price (google.shopping.type.types.Price): + Price of the product at this store. + sale_price (google.shopping.type.types.Price): + Sale price of the product at this store. Mandatory if + [``salePriceEffectiveDate``][google.shopping.merchant.inventories.v1beta.LocalInventory.sale_price_effective_date] + is defined. + sale_price_effective_date (google.type.interval_pb2.Interval): + The ``TimePeriod`` of the sale at this store. + availability (str): + Availability of the product at this store. For accepted + attribute values, see the `local product inventory data + specification `__ + + This field is a member of `oneof`_ ``_availability``. + quantity (int): + Quantity of the product available at this + store. Must be greater than or equal to zero. + + This field is a member of `oneof`_ ``_quantity``. + pickup_method (str): + Supported pickup method for this product. Unless the value + is ``"not supported"``, this field must be submitted + together with ``pickupSla``. For accepted attribute values, + see the `local product inventory data + specification `__ + + This field is a member of `oneof`_ ``_pickup_method``. + pickup_sla (str): + Relative time period from the order date for an order for + this product, from this store, to be ready for pickup. Must + be submitted with ``pickupMethod``. For accepted attribute + values, see the `local product inventory data + specification `__ + + This field is a member of `oneof`_ ``_pickup_sla``. + instore_product_location (str): + Location of the product inside the store. + Maximum length is 20 bytes. + + This field is a member of `oneof`_ ``_instore_product_location``. + custom_attributes (MutableSequence[google.shopping.type.types.CustomAttribute]): + A list of custom (merchant-provided) attributes. You can + also use ``CustomAttribute`` to submit any attribute of the + data specification in its generic form. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + account: int = proto.Field( + proto.INT64, + number=2, + ) + store_code: str = proto.Field( + proto.STRING, + number=3, + ) + price: types.Price = proto.Field( + proto.MESSAGE, + number=4, + message=types.Price, + ) + sale_price: types.Price = proto.Field( + proto.MESSAGE, + number=5, + message=types.Price, + ) + sale_price_effective_date: interval_pb2.Interval = proto.Field( + proto.MESSAGE, + number=6, + message=interval_pb2.Interval, + ) + availability: str = proto.Field( + proto.STRING, + number=7, + optional=True, + ) + quantity: int = proto.Field( + proto.INT64, + number=8, + optional=True, + ) + pickup_method: str = proto.Field( + proto.STRING, + number=9, + optional=True, + ) + pickup_sla: str = proto.Field( + proto.STRING, + number=10, + optional=True, + ) + instore_product_location: str = proto.Field( + proto.STRING, + number=11, + optional=True, + ) + custom_attributes: MutableSequence[types.CustomAttribute] = proto.RepeatedField( + proto.MESSAGE, + number=12, + message=types.CustomAttribute, + ) + + +class ListLocalInventoriesRequest(proto.Message): + r"""Request message for the ``ListLocalInventories`` method. + + Attributes: + parent (str): + Required. The ``name`` of the parent product to list local + inventories for. Format: + ``accounts/{account}/products/{product}`` + page_size (int): + The maximum number of ``LocalInventory`` resources for the + given product to return. The service returns fewer than this + value if the number of inventories for the given product is + less that than the ``pageSize``. The default value is 25000. + The maximum value is 25000; If a value higher than the + maximum is specified, then the ``pageSize`` will default to + the maximum + page_token (str): + A page token, received from a previous + ``ListLocalInventories`` call. Provide the page token to + retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListLocalInventories`` must match the call that provided + the page token. The token returned as + [nextPageToken][google.shopping.merchant.inventories.v1beta.ListLocalInventoriesResponse.next_page_token] + in the response to the previous request. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListLocalInventoriesResponse(proto.Message): + r"""Response message for the ``ListLocalInventories`` method. + + Attributes: + local_inventories (MutableSequence[google.shopping.merchant_inventories_v1beta.types.LocalInventory]): + The ``LocalInventory`` resources for the given product from + the specified account. + next_page_token (str): + A token, which can be sent as ``pageToken`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + local_inventories: MutableSequence['LocalInventory'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='LocalInventory', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class InsertLocalInventoryRequest(proto.Message): + r"""Request message for the ``InsertLocalInventory`` method. + + Attributes: + parent (str): + Required. The account and product where this inventory will + be inserted. Format: + ``accounts/{account}/products/{product}`` + local_inventory (google.shopping.merchant_inventories_v1beta.types.LocalInventory): + Required. Local inventory information of the product. If the + product already has a ``LocalInventory`` resource for the + same ``storeCode``, full replacement of the + ``LocalInventory`` resource is performed. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + local_inventory: 'LocalInventory' = proto.Field( + proto.MESSAGE, + number=2, + message='LocalInventory', + ) + + +class DeleteLocalInventoryRequest(proto.Message): + r"""Request message for the ``DeleteLocalInventory`` method. + + Attributes: + name (str): + Required. The name of the local inventory for the given + product to delete. Format: + ``accounts/{account}/products/{product}/localInventories/{store_code}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/regionalinventory.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/regionalinventory.py new file mode 100644 index 000000000000..d5a18381605f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/regionalinventory.py @@ -0,0 +1,236 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.shopping.type.types import types +from google.type import interval_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.shopping.merchant.inventories.v1beta', + manifest={ + 'RegionalInventory', + 'ListRegionalInventoriesRequest', + 'ListRegionalInventoriesResponse', + 'InsertRegionalInventoryRequest', + 'DeleteRegionalInventoryRequest', + }, +) + + +class RegionalInventory(proto.Message): + r"""Regional inventory information for the product. Represents specific + information like price and availability for a given product in a + specific + [``region``][google.shopping.merchant.inventories.v1beta.RegionalInventory.region]. + For a list of all accepted attribute values, see the `regional + product inventory data + specification `__. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Output only. The name of the ``RegionalInventory`` resource. + Format: + ``{regional_inventory.name=accounts/{account}/products/{product}/regionalInventories/{region}`` + account (int): + Output only. The account that owns the + product. This field will be ignored if set by + the client. + region (str): + Required. Immutable. ID of the region for this + ``RegionalInventory`` resource. See the `Regional + availability and + pricing `__ + for more details. + price (google.shopping.type.types.Price): + Price of the product in this region. + sale_price (google.shopping.type.types.Price): + Sale price of the product in this region. Mandatory if + [``salePriceEffectiveDate``][google.shopping.merchant.inventories.v1beta.RegionalInventory.sale_price_effective_date] + is defined. + sale_price_effective_date (google.type.interval_pb2.Interval): + The ``TimePeriod`` of the sale price in this region. + availability (str): + Availability of the product in this region. For accepted + attribute values, see the `regional product inventory data + specification `__ + + This field is a member of `oneof`_ ``_availability``. + custom_attributes (MutableSequence[google.shopping.type.types.CustomAttribute]): + A list of custom (merchant-provided) attributes. You can + also use ``CustomAttribute`` to submit any attribute of the + data specification in its generic form. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + account: int = proto.Field( + proto.INT64, + number=2, + ) + region: str = proto.Field( + proto.STRING, + number=3, + ) + price: types.Price = proto.Field( + proto.MESSAGE, + number=4, + message=types.Price, + ) + sale_price: types.Price = proto.Field( + proto.MESSAGE, + number=5, + message=types.Price, + ) + sale_price_effective_date: interval_pb2.Interval = proto.Field( + proto.MESSAGE, + number=6, + message=interval_pb2.Interval, + ) + availability: str = proto.Field( + proto.STRING, + number=7, + optional=True, + ) + custom_attributes: MutableSequence[types.CustomAttribute] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message=types.CustomAttribute, + ) + + +class ListRegionalInventoriesRequest(proto.Message): + r"""Request message for the ``ListRegionalInventories`` method. + + Attributes: + parent (str): + Required. The ``name`` of the parent product to list + ``RegionalInventory`` resources for. Format: + ``accounts/{account}/products/{product}`` + page_size (int): + The maximum number of ``RegionalInventory`` resources for + the given product to return. The service returns fewer than + this value if the number of inventories for the given + product is less that than the ``pageSize``. The default + value is 25000. The maximum value is 100000; If a value + higher than the maximum is specified, then the ``pageSize`` + will default to the maximum. + page_token (str): + A page token, received from a previous + ``ListRegionalInventories`` call. Provide the page token to + retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListRegionalInventories`` must match the call that + provided the page token. The token returned as + [nextPageToken][google.shopping.merchant.inventories.v1beta.ListRegionalInventoriesResponse.next_page_token] + in the response to the previous request. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListRegionalInventoriesResponse(proto.Message): + r"""Response message for the ``ListRegionalInventories`` method. + + Attributes: + regional_inventories (MutableSequence[google.shopping.merchant_inventories_v1beta.types.RegionalInventory]): + The ``RegionalInventory`` resources for the given product + from the specified account. + next_page_token (str): + A token, which can be sent as ``pageToken`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + regional_inventories: MutableSequence['RegionalInventory'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='RegionalInventory', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class InsertRegionalInventoryRequest(proto.Message): + r"""Request message for the ``InsertRegionalInventory`` method. + + Attributes: + parent (str): + Required. The account and product where this inventory will + be inserted. Format: + ``accounts/{account}/products/{product}`` + regional_inventory (google.shopping.merchant_inventories_v1beta.types.RegionalInventory): + Required. Regional inventory information to add to the + product. If the product already has a ``RegionalInventory`` + resource for the same ``region``, full replacement of the + ``RegionalInventory`` resource is performed. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + regional_inventory: 'RegionalInventory' = proto.Field( + proto.MESSAGE, + number=2, + message='RegionalInventory', + ) + + +class DeleteRegionalInventoryRequest(proto.Message): + r"""Request message for the ``DeleteRegionalInventory`` method. + + Attributes: + name (str): + Required. The name of the ``RegionalInventory`` resource to + delete. Format: + ``accounts/{account}/products/{product}/regionalInventories/{region}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/mypy.ini b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/noxfile.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/noxfile.py new file mode 100644 index 000000000000..103e86007356 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/noxfile.py @@ -0,0 +1,280 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = 'google-shopping-merchant-inventories' + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.13" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "prerelease_deps", +] + +@nox.session(python=ALL_PYTHON) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def unit(session, protobuf_implementation): + """Run the unit test suite.""" + + 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+") + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") + + # 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") + + session.run( + 'py.test', + '--quiet', + '--cov=google/shopping/merchant_inventories_v1beta/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)), + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + +@nox.session(python=ALL_PYTHON[-1]) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def prerelease_deps(session, protobuf_implementation): + """Run the unit test suite against pre-release versions of dependencies.""" + + 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 test environment dependencies + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + + # Install the package without dependencies + session.install('-e', '.', '--no-deps') + + # We test the minimum dependency versions using the minimum Python + # version so the lowest python runtime that we test has a corresponding constraints + # file, located at `testing/constraints--.txt`, which contains all of the + # 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 + ) + ] + + session.install(*constraints_deps) + + prerel_deps = [ + "googleapis-common-protos", + "google-api-core", + "google-auth", + # Exclude grpcio!=1.67.0rc1 which does not support python 3.13 + "grpcio!=1.67.0rc1", + "grpcio-status", + "protobuf", + "proto-plus", + ] + + for dep in prerel_deps: + session.install("--pre", "--no-deps", "--upgrade", dep) + + # Remaining dependencies + other_deps = [ + "requests", + ] + session.install(*other_deps) + + # Print out prerelease package versions + + session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") + session.run("python", "-c", "import google.auth; print(google.auth.__version__)") + session.run("python", "-c", "import grpc; print(grpc.__version__)") + session.run( + "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" + ) + session.run( + "python", "-c", "import proto; print(proto.__version__)" + ) + + session.run( + 'py.test', + '--quiet', + '--cov=google/shopping/merchant_inventories_v1beta/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)), + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + + +@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=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 docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==7.0.1", "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=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", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_async.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_async.py new file mode 100644 index 000000000000..c2b887fa74b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteLocalInventory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-inventories + + +# [START merchantapi_v1beta_generated_LocalInventoryService_DeleteLocalInventory_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.shopping import merchant_inventories_v1beta + + +async def sample_delete_local_inventory(): + # Create a client + client = merchant_inventories_v1beta.LocalInventoryServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_inventories_v1beta.DeleteLocalInventoryRequest( + name="name_value", + ) + + # Make the request + await client.delete_local_inventory(request=request) + + +# [END merchantapi_v1beta_generated_LocalInventoryService_DeleteLocalInventory_async] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_sync.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_sync.py new file mode 100644 index 000000000000..f7987bde6168 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteLocalInventory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-inventories + + +# [START merchantapi_v1beta_generated_LocalInventoryService_DeleteLocalInventory_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.shopping import merchant_inventories_v1beta + + +def sample_delete_local_inventory(): + # Create a client + client = merchant_inventories_v1beta.LocalInventoryServiceClient() + + # Initialize request argument(s) + request = merchant_inventories_v1beta.DeleteLocalInventoryRequest( + name="name_value", + ) + + # Make the request + client.delete_local_inventory(request=request) + + +# [END merchantapi_v1beta_generated_LocalInventoryService_DeleteLocalInventory_sync] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_async.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_async.py new file mode 100644 index 000000000000..8fd3fb0cd942 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for InsertLocalInventory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-inventories + + +# [START merchantapi_v1beta_generated_LocalInventoryService_InsertLocalInventory_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.shopping import merchant_inventories_v1beta + + +async def sample_insert_local_inventory(): + # Create a client + client = merchant_inventories_v1beta.LocalInventoryServiceAsyncClient() + + # Initialize request argument(s) + local_inventory = merchant_inventories_v1beta.LocalInventory() + local_inventory.store_code = "store_code_value" + + request = merchant_inventories_v1beta.InsertLocalInventoryRequest( + parent="parent_value", + local_inventory=local_inventory, + ) + + # Make the request + response = await client.insert_local_inventory(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_LocalInventoryService_InsertLocalInventory_async] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_sync.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_sync.py new file mode 100644 index 000000000000..27ff97c03bb3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for InsertLocalInventory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-inventories + + +# [START merchantapi_v1beta_generated_LocalInventoryService_InsertLocalInventory_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.shopping import merchant_inventories_v1beta + + +def sample_insert_local_inventory(): + # Create a client + client = merchant_inventories_v1beta.LocalInventoryServiceClient() + + # Initialize request argument(s) + local_inventory = merchant_inventories_v1beta.LocalInventory() + local_inventory.store_code = "store_code_value" + + request = merchant_inventories_v1beta.InsertLocalInventoryRequest( + parent="parent_value", + local_inventory=local_inventory, + ) + + # Make the request + response = client.insert_local_inventory(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_LocalInventoryService_InsertLocalInventory_sync] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_async.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_async.py new file mode 100644 index 000000000000..0401ce499705 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListLocalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-inventories + + +# [START merchantapi_v1beta_generated_LocalInventoryService_ListLocalInventories_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.shopping import merchant_inventories_v1beta + + +async def sample_list_local_inventories(): + # Create a client + client = merchant_inventories_v1beta.LocalInventoryServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_inventories_v1beta.ListLocalInventoriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_local_inventories(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_LocalInventoryService_ListLocalInventories_async] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_sync.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_sync.py new file mode 100644 index 000000000000..f6a35200c618 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListLocalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-inventories + + +# [START merchantapi_v1beta_generated_LocalInventoryService_ListLocalInventories_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.shopping import merchant_inventories_v1beta + + +def sample_list_local_inventories(): + # Create a client + client = merchant_inventories_v1beta.LocalInventoryServiceClient() + + # Initialize request argument(s) + request = merchant_inventories_v1beta.ListLocalInventoriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_local_inventories(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_LocalInventoryService_ListLocalInventories_sync] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_async.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_async.py new file mode 100644 index 000000000000..baecc3b1f705 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteRegionalInventory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-inventories + + +# [START merchantapi_v1beta_generated_RegionalInventoryService_DeleteRegionalInventory_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.shopping import merchant_inventories_v1beta + + +async def sample_delete_regional_inventory(): + # Create a client + client = merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_inventories_v1beta.DeleteRegionalInventoryRequest( + name="name_value", + ) + + # Make the request + await client.delete_regional_inventory(request=request) + + +# [END merchantapi_v1beta_generated_RegionalInventoryService_DeleteRegionalInventory_async] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_sync.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_sync.py new file mode 100644 index 000000000000..785fea0a8519 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteRegionalInventory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-inventories + + +# [START merchantapi_v1beta_generated_RegionalInventoryService_DeleteRegionalInventory_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.shopping import merchant_inventories_v1beta + + +def sample_delete_regional_inventory(): + # Create a client + client = merchant_inventories_v1beta.RegionalInventoryServiceClient() + + # Initialize request argument(s) + request = merchant_inventories_v1beta.DeleteRegionalInventoryRequest( + name="name_value", + ) + + # Make the request + client.delete_regional_inventory(request=request) + + +# [END merchantapi_v1beta_generated_RegionalInventoryService_DeleteRegionalInventory_sync] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_async.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_async.py new file mode 100644 index 000000000000..0cfcfe596291 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for InsertRegionalInventory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-inventories + + +# [START merchantapi_v1beta_generated_RegionalInventoryService_InsertRegionalInventory_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.shopping import merchant_inventories_v1beta + + +async def sample_insert_regional_inventory(): + # Create a client + client = merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient() + + # Initialize request argument(s) + regional_inventory = merchant_inventories_v1beta.RegionalInventory() + regional_inventory.region = "region_value" + + request = merchant_inventories_v1beta.InsertRegionalInventoryRequest( + parent="parent_value", + regional_inventory=regional_inventory, + ) + + # Make the request + response = await client.insert_regional_inventory(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_RegionalInventoryService_InsertRegionalInventory_async] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_sync.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_sync.py new file mode 100644 index 000000000000..04912cc719d2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for InsertRegionalInventory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-inventories + + +# [START merchantapi_v1beta_generated_RegionalInventoryService_InsertRegionalInventory_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.shopping import merchant_inventories_v1beta + + +def sample_insert_regional_inventory(): + # Create a client + client = merchant_inventories_v1beta.RegionalInventoryServiceClient() + + # Initialize request argument(s) + regional_inventory = merchant_inventories_v1beta.RegionalInventory() + regional_inventory.region = "region_value" + + request = merchant_inventories_v1beta.InsertRegionalInventoryRequest( + parent="parent_value", + regional_inventory=regional_inventory, + ) + + # Make the request + response = client.insert_regional_inventory(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_RegionalInventoryService_InsertRegionalInventory_sync] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_async.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_async.py new file mode 100644 index 000000000000..ea04c9082f2a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListRegionalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-inventories + + +# [START merchantapi_v1beta_generated_RegionalInventoryService_ListRegionalInventories_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.shopping import merchant_inventories_v1beta + + +async def sample_list_regional_inventories(): + # Create a client + client = merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_inventories_v1beta.ListRegionalInventoriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_regional_inventories(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_RegionalInventoryService_ListRegionalInventories_async] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_sync.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_sync.py new file mode 100644 index 000000000000..6136c4ff08ba --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListRegionalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-inventories + + +# [START merchantapi_v1beta_generated_RegionalInventoryService_ListRegionalInventories_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.shopping import merchant_inventories_v1beta + + +def sample_list_regional_inventories(): + # Create a client + client = merchant_inventories_v1beta.RegionalInventoryServiceClient() + + # Initialize request argument(s) + request = merchant_inventories_v1beta.ListRegionalInventoriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_regional_inventories(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_RegionalInventoryService_ListRegionalInventories_sync] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.inventories.v1beta.json b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.inventories.v1beta.json new file mode 100644 index 000000000000..73ddfcf94070 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.inventories.v1beta.json @@ -0,0 +1,953 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.shopping.merchant.inventories.v1beta", + "version": "v1beta" + } + ], + "language": "PYTHON", + "name": "google-shopping-merchant-inventories", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceAsyncClient", + "shortName": "LocalInventoryServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceAsyncClient.delete_local_inventory", + "method": { + "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService.DeleteLocalInventory", + "service": { + "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "shortName": "LocalInventoryService" + }, + "shortName": "DeleteLocalInventory" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_inventories_v1beta.types.DeleteLocalInventoryRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_local_inventory" + }, + "description": "Sample for DeleteLocalInventory", + "file": "merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_LocalInventoryService_DeleteLocalInventory_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceClient", + "shortName": "LocalInventoryServiceClient" + }, + "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceClient.delete_local_inventory", + "method": { + "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService.DeleteLocalInventory", + "service": { + "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "shortName": "LocalInventoryService" + }, + "shortName": "DeleteLocalInventory" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_inventories_v1beta.types.DeleteLocalInventoryRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_local_inventory" + }, + "description": "Sample for DeleteLocalInventory", + "file": "merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_LocalInventoryService_DeleteLocalInventory_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceAsyncClient", + "shortName": "LocalInventoryServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceAsyncClient.insert_local_inventory", + "method": { + "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService.InsertLocalInventory", + "service": { + "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "shortName": "LocalInventoryService" + }, + "shortName": "InsertLocalInventory" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_inventories_v1beta.types.InsertLocalInventoryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.shopping.merchant_inventories_v1beta.types.LocalInventory", + "shortName": "insert_local_inventory" + }, + "description": "Sample for InsertLocalInventory", + "file": "merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_LocalInventoryService_InsertLocalInventory_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceClient", + "shortName": "LocalInventoryServiceClient" + }, + "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceClient.insert_local_inventory", + "method": { + "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService.InsertLocalInventory", + "service": { + "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "shortName": "LocalInventoryService" + }, + "shortName": "InsertLocalInventory" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_inventories_v1beta.types.InsertLocalInventoryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.shopping.merchant_inventories_v1beta.types.LocalInventory", + "shortName": "insert_local_inventory" + }, + "description": "Sample for InsertLocalInventory", + "file": "merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_LocalInventoryService_InsertLocalInventory_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceAsyncClient", + "shortName": "LocalInventoryServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceAsyncClient.list_local_inventories", + "method": { + "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService.ListLocalInventories", + "service": { + "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "shortName": "LocalInventoryService" + }, + "shortName": "ListLocalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.shopping.merchant_inventories_v1beta.services.local_inventory_service.pagers.ListLocalInventoriesAsyncPager", + "shortName": "list_local_inventories" + }, + "description": "Sample for ListLocalInventories", + "file": "merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_LocalInventoryService_ListLocalInventories_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceClient", + "shortName": "LocalInventoryServiceClient" + }, + "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceClient.list_local_inventories", + "method": { + "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService.ListLocalInventories", + "service": { + "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "shortName": "LocalInventoryService" + }, + "shortName": "ListLocalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.shopping.merchant_inventories_v1beta.services.local_inventory_service.pagers.ListLocalInventoriesPager", + "shortName": "list_local_inventories" + }, + "description": "Sample for ListLocalInventories", + "file": "merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_LocalInventoryService_ListLocalInventories_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient", + "shortName": "RegionalInventoryServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient.delete_regional_inventory", + "method": { + "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService.DeleteRegionalInventory", + "service": { + "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "shortName": "RegionalInventoryService" + }, + "shortName": "DeleteRegionalInventory" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_inventories_v1beta.types.DeleteRegionalInventoryRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_regional_inventory" + }, + "description": "Sample for DeleteRegionalInventory", + "file": "merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_RegionalInventoryService_DeleteRegionalInventory_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceClient", + "shortName": "RegionalInventoryServiceClient" + }, + "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceClient.delete_regional_inventory", + "method": { + "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService.DeleteRegionalInventory", + "service": { + "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "shortName": "RegionalInventoryService" + }, + "shortName": "DeleteRegionalInventory" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_inventories_v1beta.types.DeleteRegionalInventoryRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_regional_inventory" + }, + "description": "Sample for DeleteRegionalInventory", + "file": "merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_RegionalInventoryService_DeleteRegionalInventory_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient", + "shortName": "RegionalInventoryServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient.insert_regional_inventory", + "method": { + "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService.InsertRegionalInventory", + "service": { + "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "shortName": "RegionalInventoryService" + }, + "shortName": "InsertRegionalInventory" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_inventories_v1beta.types.InsertRegionalInventoryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.shopping.merchant_inventories_v1beta.types.RegionalInventory", + "shortName": "insert_regional_inventory" + }, + "description": "Sample for InsertRegionalInventory", + "file": "merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_RegionalInventoryService_InsertRegionalInventory_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceClient", + "shortName": "RegionalInventoryServiceClient" + }, + "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceClient.insert_regional_inventory", + "method": { + "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService.InsertRegionalInventory", + "service": { + "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "shortName": "RegionalInventoryService" + }, + "shortName": "InsertRegionalInventory" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_inventories_v1beta.types.InsertRegionalInventoryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.shopping.merchant_inventories_v1beta.types.RegionalInventory", + "shortName": "insert_regional_inventory" + }, + "description": "Sample for InsertRegionalInventory", + "file": "merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_RegionalInventoryService_InsertRegionalInventory_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient", + "shortName": "RegionalInventoryServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient.list_regional_inventories", + "method": { + "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService.ListRegionalInventories", + "service": { + "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "shortName": "RegionalInventoryService" + }, + "shortName": "ListRegionalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.pagers.ListRegionalInventoriesAsyncPager", + "shortName": "list_regional_inventories" + }, + "description": "Sample for ListRegionalInventories", + "file": "merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_RegionalInventoryService_ListRegionalInventories_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceClient", + "shortName": "RegionalInventoryServiceClient" + }, + "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceClient.list_regional_inventories", + "method": { + "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService.ListRegionalInventories", + "service": { + "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "shortName": "RegionalInventoryService" + }, + "shortName": "ListRegionalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.pagers.ListRegionalInventoriesPager", + "shortName": "list_regional_inventories" + }, + "description": "Sample for ListRegionalInventories", + "file": "merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_RegionalInventoryService_ListRegionalInventories_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/scripts/fixup_merchant_inventories_v1beta_keywords.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/scripts/fixup_merchant_inventories_v1beta_keywords.py new file mode 100644 index 000000000000..f3a43869aa74 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/scripts/fixup_merchant_inventories_v1beta_keywords.py @@ -0,0 +1,181 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class merchant_inventoriesCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'delete_local_inventory': ('name', ), + 'delete_regional_inventory': ('name', ), + 'insert_local_inventory': ('parent', 'local_inventory', ), + 'insert_regional_inventory': ('parent', 'regional_inventory', ), + 'list_local_inventories': ('parent', 'page_size', 'page_token', ), + 'list_regional_inventories': ('parent', 'page_size', 'page_token', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=merchant_inventoriesCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the merchant_inventories client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/setup.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/setup.py new file mode 100644 index 000000000000..70bf2bb6e0f2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/setup.py @@ -0,0 +1,99 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os +import re + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-shopping-merchant-inventories' + + +description = "Google Shopping Merchant Inventories API client library" + +version = None + +with open(os.path.join(package_root, 'google/shopping/merchant_inventories/gapic_version.py')) as fp: + version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) + assert (len(version_candidates) == 1) + version = version_candidates[0] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + +dependencies = [ + "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=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.0dev,!=2.24.0,!=2.25.0", + "proto-plus >= 1.22.3, <2.0.0dev", + "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'", + "protobuf>=3.20.2,<6.0.0dev,!=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.0dev", +] +extras = { +} +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-inventories" + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, "README.rst") +with io.open(readme_filename, encoding="utf-8") as readme_file: + readme = readme_file.read() + +packages = [ + package + for package in setuptools.find_namespace_packages() + if package.startswith("google") +] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + install_requires=dependencies, + extras_require=extras, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.10.txt b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.10.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.10.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +google-shopping-type diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.11.txt b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.11.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.11.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +google-shopping-type diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.12.txt b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.12.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.12.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +google-shopping-type diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.13.txt b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.13.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.13.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +google-shopping-type diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.7.txt b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.7.txt new file mode 100644 index 000000000000..130a0c0f80ab --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.7.txt @@ -0,0 +1,11 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.1 +google-auth==2.14.1 +proto-plus==1.22.3 +protobuf==3.20.2 +google-shopping-type==0.1.6 diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.8.txt b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.8.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.8.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +google-shopping-type diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.9.txt b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.9.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.9.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +google-shopping-type diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/test_local_inventory_service.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/test_local_inventory_service.py new file mode 100644 index 000000000000..dd862b8b1671 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/test_local_inventory_service.py @@ -0,0 +1,3612 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable, AsyncIterable +from google.protobuf import json_format +import json +import math +import pytest +from google.api_core import api_core_version +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +try: + from google.auth.aio import credentials as ga_credentials_async + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account +from google.protobuf import timestamp_pb2 # type: ignore +from google.shopping.merchant_inventories_v1beta.services.local_inventory_service import LocalInventoryServiceAsyncClient +from google.shopping.merchant_inventories_v1beta.services.local_inventory_service import LocalInventoryServiceClient +from google.shopping.merchant_inventories_v1beta.services.local_inventory_service import pagers +from google.shopping.merchant_inventories_v1beta.services.local_inventory_service import transports +from google.shopping.merchant_inventories_v1beta.types import localinventory +from google.shopping.type.types import types +from google.type import interval_pb2 # type: ignore +import google.auth + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert LocalInventoryServiceClient._get_default_mtls_endpoint(None) is None + assert LocalInventoryServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert LocalInventoryServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert LocalInventoryServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert LocalInventoryServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert LocalInventoryServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert LocalInventoryServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert LocalInventoryServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert LocalInventoryServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + LocalInventoryServiceClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert LocalInventoryServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert LocalInventoryServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert LocalInventoryServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + LocalInventoryServiceClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert LocalInventoryServiceClient._read_environment_variables() == (False, "auto", "foo.com") + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert LocalInventoryServiceClient._get_client_cert_source(None, False) is None + assert LocalInventoryServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert LocalInventoryServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): + assert LocalInventoryServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert LocalInventoryServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(LocalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceClient)) +@mock.patch.object(LocalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = LocalInventoryServiceClient._DEFAULT_UNIVERSE + default_endpoint = LocalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = LocalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert LocalInventoryServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert LocalInventoryServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == LocalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT + assert LocalInventoryServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert LocalInventoryServiceClient._get_api_endpoint(None, None, default_universe, "always") == LocalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT + assert LocalInventoryServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == LocalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT + assert LocalInventoryServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert LocalInventoryServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + LocalInventoryServiceClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert LocalInventoryServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert LocalInventoryServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert LocalInventoryServiceClient._get_universe_domain(None, None) == LocalInventoryServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + LocalInventoryServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize("client_class,transport_name", [ + (LocalInventoryServiceClient, "grpc"), + (LocalInventoryServiceAsyncClient, "grpc_asyncio"), + (LocalInventoryServiceClient, "rest"), +]) +def test_local_inventory_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'merchantapi.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://merchantapi.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.LocalInventoryServiceGrpcTransport, "grpc"), + (transports.LocalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.LocalInventoryServiceRestTransport, "rest"), +]) +def test_local_inventory_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (LocalInventoryServiceClient, "grpc"), + (LocalInventoryServiceAsyncClient, "grpc_asyncio"), + (LocalInventoryServiceClient, "rest"), +]) +def test_local_inventory_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'merchantapi.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://merchantapi.googleapis.com' + ) + + +def test_local_inventory_service_client_get_transport_class(): + transport = LocalInventoryServiceClient.get_transport_class() + available_transports = [ + transports.LocalInventoryServiceGrpcTransport, + transports.LocalInventoryServiceRestTransport, + ] + assert transport in available_transports + + transport = LocalInventoryServiceClient.get_transport_class("grpc") + assert transport == transports.LocalInventoryServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (LocalInventoryServiceClient, transports.LocalInventoryServiceGrpcTransport, "grpc"), + (LocalInventoryServiceAsyncClient, transports.LocalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (LocalInventoryServiceClient, transports.LocalInventoryServiceRestTransport, "rest"), +]) +@mock.patch.object(LocalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceClient)) +@mock.patch.object(LocalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceAsyncClient)) +def test_local_inventory_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(LocalInventoryServiceClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(LocalInventoryServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (LocalInventoryServiceClient, transports.LocalInventoryServiceGrpcTransport, "grpc", "true"), + (LocalInventoryServiceAsyncClient, transports.LocalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (LocalInventoryServiceClient, transports.LocalInventoryServiceGrpcTransport, "grpc", "false"), + (LocalInventoryServiceAsyncClient, transports.LocalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (LocalInventoryServiceClient, transports.LocalInventoryServiceRestTransport, "rest", "true"), + (LocalInventoryServiceClient, transports.LocalInventoryServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(LocalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceClient)) +@mock.patch.object(LocalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_local_inventory_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + LocalInventoryServiceClient, LocalInventoryServiceAsyncClient +]) +@mock.patch.object(LocalInventoryServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LocalInventoryServiceClient)) +@mock.patch.object(LocalInventoryServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LocalInventoryServiceAsyncClient)) +def test_local_inventory_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + +@pytest.mark.parametrize("client_class", [ + LocalInventoryServiceClient, LocalInventoryServiceAsyncClient +]) +@mock.patch.object(LocalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceClient)) +@mock.patch.object(LocalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceAsyncClient)) +def test_local_inventory_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = LocalInventoryServiceClient._DEFAULT_UNIVERSE + default_endpoint = LocalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = LocalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + else: + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) + assert client.universe_domain == (mock_universe if universe_exists else default_universe) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (LocalInventoryServiceClient, transports.LocalInventoryServiceGrpcTransport, "grpc"), + (LocalInventoryServiceAsyncClient, transports.LocalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (LocalInventoryServiceClient, transports.LocalInventoryServiceRestTransport, "rest"), +]) +def test_local_inventory_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (LocalInventoryServiceClient, transports.LocalInventoryServiceGrpcTransport, "grpc", grpc_helpers), + (LocalInventoryServiceAsyncClient, transports.LocalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (LocalInventoryServiceClient, transports.LocalInventoryServiceRestTransport, "rest", None), +]) +def test_local_inventory_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_local_inventory_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_inventories_v1beta.services.local_inventory_service.transports.LocalInventoryServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = LocalInventoryServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (LocalInventoryServiceClient, transports.LocalInventoryServiceGrpcTransport, "grpc", grpc_helpers), + (LocalInventoryServiceAsyncClient, transports.LocalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_local_inventory_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "merchantapi.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/content', +), + scopes=None, + default_host="merchantapi.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + localinventory.ListLocalInventoriesRequest, + dict, +]) +def test_list_local_inventories(request_type, transport: str = 'grpc'): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_local_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = localinventory.ListLocalInventoriesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = localinventory.ListLocalInventoriesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListLocalInventoriesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_local_inventories_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = localinventory.ListLocalInventoriesRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_local_inventories), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_local_inventories(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == localinventory.ListLocalInventoriesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_local_inventories_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_local_inventories in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_local_inventories] = mock_rpc + request = {} + client.list_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_local_inventories(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_local_inventories_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_local_inventories in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.list_local_inventories] = mock_rpc + + request = {} + await client.list_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_local_inventories(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_local_inventories_async(transport: str = 'grpc_asyncio', request_type=localinventory.ListLocalInventoriesRequest): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_local_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(localinventory.ListLocalInventoriesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = localinventory.ListLocalInventoriesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListLocalInventoriesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_local_inventories_async_from_dict(): + await test_list_local_inventories_async(request_type=dict) + +def test_list_local_inventories_field_headers(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = localinventory.ListLocalInventoriesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_local_inventories), + '__call__') as call: + call.return_value = localinventory.ListLocalInventoriesResponse() + client.list_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_local_inventories_field_headers_async(): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = localinventory.ListLocalInventoriesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_local_inventories), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(localinventory.ListLocalInventoriesResponse()) + await client.list_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_local_inventories_flattened(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_local_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = localinventory.ListLocalInventoriesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_local_inventories( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_local_inventories_flattened_error(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_local_inventories( + localinventory.ListLocalInventoriesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_local_inventories_flattened_async(): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_local_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = localinventory.ListLocalInventoriesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(localinventory.ListLocalInventoriesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_local_inventories( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_local_inventories_flattened_error_async(): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_local_inventories( + localinventory.ListLocalInventoriesRequest(), + parent='parent_value', + ) + + +def test_list_local_inventories_pager(transport_name: str = "grpc"): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_local_inventories), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + localinventory.ListLocalInventoriesResponse( + local_inventories=[ + localinventory.LocalInventory(), + localinventory.LocalInventory(), + localinventory.LocalInventory(), + ], + next_page_token='abc', + ), + localinventory.ListLocalInventoriesResponse( + local_inventories=[], + next_page_token='def', + ), + localinventory.ListLocalInventoriesResponse( + local_inventories=[ + localinventory.LocalInventory(), + ], + next_page_token='ghi', + ), + localinventory.ListLocalInventoriesResponse( + local_inventories=[ + localinventory.LocalInventory(), + localinventory.LocalInventory(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_local_inventories(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, localinventory.LocalInventory) + for i in results) +def test_list_local_inventories_pages(transport_name: str = "grpc"): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_local_inventories), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + localinventory.ListLocalInventoriesResponse( + local_inventories=[ + localinventory.LocalInventory(), + localinventory.LocalInventory(), + localinventory.LocalInventory(), + ], + next_page_token='abc', + ), + localinventory.ListLocalInventoriesResponse( + local_inventories=[], + next_page_token='def', + ), + localinventory.ListLocalInventoriesResponse( + local_inventories=[ + localinventory.LocalInventory(), + ], + next_page_token='ghi', + ), + localinventory.ListLocalInventoriesResponse( + local_inventories=[ + localinventory.LocalInventory(), + localinventory.LocalInventory(), + ], + ), + RuntimeError, + ) + pages = list(client.list_local_inventories(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_local_inventories_async_pager(): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_local_inventories), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + localinventory.ListLocalInventoriesResponse( + local_inventories=[ + localinventory.LocalInventory(), + localinventory.LocalInventory(), + localinventory.LocalInventory(), + ], + next_page_token='abc', + ), + localinventory.ListLocalInventoriesResponse( + local_inventories=[], + next_page_token='def', + ), + localinventory.ListLocalInventoriesResponse( + local_inventories=[ + localinventory.LocalInventory(), + ], + next_page_token='ghi', + ), + localinventory.ListLocalInventoriesResponse( + local_inventories=[ + localinventory.LocalInventory(), + localinventory.LocalInventory(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_local_inventories(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, localinventory.LocalInventory) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_local_inventories_async_pages(): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_local_inventories), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + localinventory.ListLocalInventoriesResponse( + local_inventories=[ + localinventory.LocalInventory(), + localinventory.LocalInventory(), + localinventory.LocalInventory(), + ], + next_page_token='abc', + ), + localinventory.ListLocalInventoriesResponse( + local_inventories=[], + next_page_token='def', + ), + localinventory.ListLocalInventoriesResponse( + local_inventories=[ + localinventory.LocalInventory(), + ], + next_page_token='ghi', + ), + localinventory.ListLocalInventoriesResponse( + local_inventories=[ + localinventory.LocalInventory(), + localinventory.LocalInventory(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_local_inventories(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + localinventory.InsertLocalInventoryRequest, + dict, +]) +def test_insert_local_inventory(request_type, transport: str = 'grpc'): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_local_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = localinventory.LocalInventory( + name='name_value', + account=749, + store_code='store_code_value', + availability='availability_value', + quantity=895, + pickup_method='pickup_method_value', + pickup_sla='pickup_sla_value', + instore_product_location='instore_product_location_value', + ) + response = client.insert_local_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = localinventory.InsertLocalInventoryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, localinventory.LocalInventory) + assert response.name == 'name_value' + assert response.account == 749 + assert response.store_code == 'store_code_value' + assert response.availability == 'availability_value' + assert response.quantity == 895 + assert response.pickup_method == 'pickup_method_value' + assert response.pickup_sla == 'pickup_sla_value' + assert response.instore_product_location == 'instore_product_location_value' + + +def test_insert_local_inventory_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = localinventory.InsertLocalInventoryRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_local_inventory), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.insert_local_inventory(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == localinventory.InsertLocalInventoryRequest( + parent='parent_value', + ) + +def test_insert_local_inventory_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.insert_local_inventory in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.insert_local_inventory] = mock_rpc + request = {} + client.insert_local_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.insert_local_inventory(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_insert_local_inventory_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.insert_local_inventory in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.insert_local_inventory] = mock_rpc + + request = {} + await client.insert_local_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.insert_local_inventory(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_insert_local_inventory_async(transport: str = 'grpc_asyncio', request_type=localinventory.InsertLocalInventoryRequest): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_local_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(localinventory.LocalInventory( + name='name_value', + account=749, + store_code='store_code_value', + availability='availability_value', + quantity=895, + pickup_method='pickup_method_value', + pickup_sla='pickup_sla_value', + instore_product_location='instore_product_location_value', + )) + response = await client.insert_local_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = localinventory.InsertLocalInventoryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, localinventory.LocalInventory) + assert response.name == 'name_value' + assert response.account == 749 + assert response.store_code == 'store_code_value' + assert response.availability == 'availability_value' + assert response.quantity == 895 + assert response.pickup_method == 'pickup_method_value' + assert response.pickup_sla == 'pickup_sla_value' + assert response.instore_product_location == 'instore_product_location_value' + + +@pytest.mark.asyncio +async def test_insert_local_inventory_async_from_dict(): + await test_insert_local_inventory_async(request_type=dict) + +def test_insert_local_inventory_field_headers(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = localinventory.InsertLocalInventoryRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_local_inventory), + '__call__') as call: + call.return_value = localinventory.LocalInventory() + client.insert_local_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_insert_local_inventory_field_headers_async(): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = localinventory.InsertLocalInventoryRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_local_inventory), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(localinventory.LocalInventory()) + await client.insert_local_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + localinventory.DeleteLocalInventoryRequest, + dict, +]) +def test_delete_local_inventory(request_type, transport: str = 'grpc'): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_local_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_local_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = localinventory.DeleteLocalInventoryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_local_inventory_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = localinventory.DeleteLocalInventoryRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_local_inventory), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_local_inventory(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == localinventory.DeleteLocalInventoryRequest( + name='name_value', + ) + +def test_delete_local_inventory_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_local_inventory in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_local_inventory] = mock_rpc + request = {} + client.delete_local_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_local_inventory(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_local_inventory_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_local_inventory in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.delete_local_inventory] = mock_rpc + + request = {} + await client.delete_local_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_local_inventory(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_local_inventory_async(transport: str = 'grpc_asyncio', request_type=localinventory.DeleteLocalInventoryRequest): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_local_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_local_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = localinventory.DeleteLocalInventoryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_local_inventory_async_from_dict(): + await test_delete_local_inventory_async(request_type=dict) + +def test_delete_local_inventory_field_headers(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = localinventory.DeleteLocalInventoryRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_local_inventory), + '__call__') as call: + call.return_value = None + client.delete_local_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_local_inventory_field_headers_async(): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = localinventory.DeleteLocalInventoryRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_local_inventory), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_local_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_local_inventory_flattened(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_local_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_local_inventory( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_local_inventory_flattened_error(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_local_inventory( + localinventory.DeleteLocalInventoryRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_local_inventory_flattened_async(): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_local_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_local_inventory( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_local_inventory_flattened_error_async(): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_local_inventory( + localinventory.DeleteLocalInventoryRequest(), + name='name_value', + ) + + +def test_list_local_inventories_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_local_inventories in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_local_inventories] = mock_rpc + + request = {} + client.list_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_local_inventories(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_local_inventories_rest_required_fields(request_type=localinventory.ListLocalInventoriesRequest): + transport_class = transports.LocalInventoryServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_local_inventories._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_local_inventories._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = localinventory.ListLocalInventoriesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = localinventory.ListLocalInventoriesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_local_inventories(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_local_inventories_rest_unset_required_fields(): + transport = transports.LocalInventoryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_local_inventories._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_local_inventories_rest_flattened(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = localinventory.ListLocalInventoriesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'accounts/sample1/products/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = localinventory.ListLocalInventoriesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_local_inventories(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/inventories/v1beta/{parent=accounts/*/products/*}/localInventories" % client.transport._host, args[1]) + + +def test_list_local_inventories_rest_flattened_error(transport: str = 'rest'): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_local_inventories( + localinventory.ListLocalInventoriesRequest(), + parent='parent_value', + ) + + +def test_list_local_inventories_rest_pager(transport: str = 'rest'): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + localinventory.ListLocalInventoriesResponse( + local_inventories=[ + localinventory.LocalInventory(), + localinventory.LocalInventory(), + localinventory.LocalInventory(), + ], + next_page_token='abc', + ), + localinventory.ListLocalInventoriesResponse( + local_inventories=[], + next_page_token='def', + ), + localinventory.ListLocalInventoriesResponse( + local_inventories=[ + localinventory.LocalInventory(), + ], + next_page_token='ghi', + ), + localinventory.ListLocalInventoriesResponse( + local_inventories=[ + localinventory.LocalInventory(), + localinventory.LocalInventory(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(localinventory.ListLocalInventoriesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'accounts/sample1/products/sample2'} + + pager = client.list_local_inventories(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, localinventory.LocalInventory) + for i in results) + + pages = list(client.list_local_inventories(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_insert_local_inventory_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.insert_local_inventory in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.insert_local_inventory] = mock_rpc + + request = {} + client.insert_local_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.insert_local_inventory(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_insert_local_inventory_rest_required_fields(request_type=localinventory.InsertLocalInventoryRequest): + transport_class = transports.LocalInventoryServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).insert_local_inventory._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).insert_local_inventory._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = localinventory.LocalInventory() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = localinventory.LocalInventory.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.insert_local_inventory(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_insert_local_inventory_rest_unset_required_fields(): + transport = transports.LocalInventoryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.insert_local_inventory._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "localInventory", ))) + + +def test_delete_local_inventory_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_local_inventory in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_local_inventory] = mock_rpc + + request = {} + client.delete_local_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_local_inventory(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_local_inventory_rest_required_fields(request_type=localinventory.DeleteLocalInventoryRequest): + transport_class = transports.LocalInventoryServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_local_inventory._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_local_inventory._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_local_inventory(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_local_inventory_rest_unset_required_fields(): + transport = transports.LocalInventoryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_local_inventory._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_delete_local_inventory_rest_flattened(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/products/sample2/localInventories/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_local_inventory(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/inventories/v1beta/{name=accounts/*/products/*/localInventories/*}" % client.transport._host, args[1]) + + +def test_delete_local_inventory_rest_flattened_error(transport: str = 'rest'): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_local_inventory( + localinventory.DeleteLocalInventoryRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.LocalInventoryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.LocalInventoryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LocalInventoryServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.LocalInventoryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = LocalInventoryServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = LocalInventoryServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.LocalInventoryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LocalInventoryServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.LocalInventoryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = LocalInventoryServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.LocalInventoryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.LocalInventoryServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.LocalInventoryServiceGrpcTransport, + transports.LocalInventoryServiceGrpcAsyncIOTransport, + transports.LocalInventoryServiceRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_kind_grpc(): + transport = LocalInventoryServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_local_inventories_empty_call_grpc(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_local_inventories), + '__call__') as call: + call.return_value = localinventory.ListLocalInventoriesResponse() + client.list_local_inventories(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = localinventory.ListLocalInventoriesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_insert_local_inventory_empty_call_grpc(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.insert_local_inventory), + '__call__') as call: + call.return_value = localinventory.LocalInventory() + client.insert_local_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = localinventory.InsertLocalInventoryRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_local_inventory_empty_call_grpc(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_local_inventory), + '__call__') as call: + call.return_value = None + client.delete_local_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = localinventory.DeleteLocalInventoryRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = LocalInventoryServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_local_inventories_empty_call_grpc_asyncio(): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_local_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(localinventory.ListLocalInventoriesResponse( + next_page_token='next_page_token_value', + )) + await client.list_local_inventories(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = localinventory.ListLocalInventoriesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_insert_local_inventory_empty_call_grpc_asyncio(): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.insert_local_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(localinventory.LocalInventory( + name='name_value', + account=749, + store_code='store_code_value', + availability='availability_value', + quantity=895, + pickup_method='pickup_method_value', + pickup_sla='pickup_sla_value', + instore_product_location='instore_product_location_value', + )) + await client.insert_local_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = localinventory.InsertLocalInventoryRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_local_inventory_empty_call_grpc_asyncio(): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_local_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_local_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = localinventory.DeleteLocalInventoryRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = LocalInventoryServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_local_inventories_rest_bad_request(request_type=localinventory.ListLocalInventoriesRequest): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1/products/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_local_inventories(request) + + +@pytest.mark.parametrize("request_type", [ + localinventory.ListLocalInventoriesRequest, + dict, +]) +def test_list_local_inventories_rest_call_success(request_type): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1/products/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = localinventory.ListLocalInventoriesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = localinventory.ListLocalInventoriesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_local_inventories(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListLocalInventoriesPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_local_inventories_rest_interceptors(null_interceptor): + transport = transports.LocalInventoryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LocalInventoryServiceRestInterceptor(), + ) + client = LocalInventoryServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.LocalInventoryServiceRestInterceptor, "post_list_local_inventories") as post, \ + mock.patch.object(transports.LocalInventoryServiceRestInterceptor, "pre_list_local_inventories") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = localinventory.ListLocalInventoriesRequest.pb(localinventory.ListLocalInventoriesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = localinventory.ListLocalInventoriesResponse.to_json(localinventory.ListLocalInventoriesResponse()) + req.return_value.content = return_value + + request = localinventory.ListLocalInventoriesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = localinventory.ListLocalInventoriesResponse() + + client.list_local_inventories(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_insert_local_inventory_rest_bad_request(request_type=localinventory.InsertLocalInventoryRequest): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1/products/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.insert_local_inventory(request) + + +@pytest.mark.parametrize("request_type", [ + localinventory.InsertLocalInventoryRequest, + dict, +]) +def test_insert_local_inventory_rest_call_success(request_type): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1/products/sample2'} + request_init["local_inventory"] = {'name': 'name_value', 'account': 749, 'store_code': 'store_code_value', 'price': {'amount_micros': 1408, 'currency_code': 'currency_code_value'}, 'sale_price': {}, 'sale_price_effective_date': {'start_time': {'seconds': 751, 'nanos': 543}, 'end_time': {}}, 'availability': 'availability_value', 'quantity': 895, 'pickup_method': 'pickup_method_value', 'pickup_sla': 'pickup_sla_value', 'instore_product_location': 'instore_product_location_value', 'custom_attributes': [{'name': 'name_value', 'value': 'value_value', 'group_values': {}}]} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = localinventory.InsertLocalInventoryRequest.meta.fields["local_inventory"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["local_inventory"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["local_inventory"][field])): + del request_init["local_inventory"][field][i][subfield] + else: + del request_init["local_inventory"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = localinventory.LocalInventory( + name='name_value', + account=749, + store_code='store_code_value', + availability='availability_value', + quantity=895, + pickup_method='pickup_method_value', + pickup_sla='pickup_sla_value', + instore_product_location='instore_product_location_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = localinventory.LocalInventory.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.insert_local_inventory(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, localinventory.LocalInventory) + assert response.name == 'name_value' + assert response.account == 749 + assert response.store_code == 'store_code_value' + assert response.availability == 'availability_value' + assert response.quantity == 895 + assert response.pickup_method == 'pickup_method_value' + assert response.pickup_sla == 'pickup_sla_value' + assert response.instore_product_location == 'instore_product_location_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_insert_local_inventory_rest_interceptors(null_interceptor): + transport = transports.LocalInventoryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LocalInventoryServiceRestInterceptor(), + ) + client = LocalInventoryServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.LocalInventoryServiceRestInterceptor, "post_insert_local_inventory") as post, \ + mock.patch.object(transports.LocalInventoryServiceRestInterceptor, "pre_insert_local_inventory") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = localinventory.InsertLocalInventoryRequest.pb(localinventory.InsertLocalInventoryRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = localinventory.LocalInventory.to_json(localinventory.LocalInventory()) + req.return_value.content = return_value + + request = localinventory.InsertLocalInventoryRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = localinventory.LocalInventory() + + client.insert_local_inventory(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_local_inventory_rest_bad_request(request_type=localinventory.DeleteLocalInventoryRequest): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/products/sample2/localInventories/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_local_inventory(request) + + +@pytest.mark.parametrize("request_type", [ + localinventory.DeleteLocalInventoryRequest, + dict, +]) +def test_delete_local_inventory_rest_call_success(request_type): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/products/sample2/localInventories/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = '' + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_local_inventory(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_local_inventory_rest_interceptors(null_interceptor): + transport = transports.LocalInventoryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LocalInventoryServiceRestInterceptor(), + ) + client = LocalInventoryServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.LocalInventoryServiceRestInterceptor, "pre_delete_local_inventory") as pre: + pre.assert_not_called() + pb_message = localinventory.DeleteLocalInventoryRequest.pb(localinventory.DeleteLocalInventoryRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + request = localinventory.DeleteLocalInventoryRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_local_inventory(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + +def test_initialize_client_w_rest(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_local_inventories_empty_call_rest(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_local_inventories), + '__call__') as call: + client.list_local_inventories(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = localinventory.ListLocalInventoriesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_insert_local_inventory_empty_call_rest(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.insert_local_inventory), + '__call__') as call: + client.insert_local_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = localinventory.InsertLocalInventoryRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_local_inventory_empty_call_rest(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_local_inventory), + '__call__') as call: + client.delete_local_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = localinventory.DeleteLocalInventoryRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.LocalInventoryServiceGrpcTransport, + ) + +def test_local_inventory_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.LocalInventoryServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_local_inventory_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_inventories_v1beta.services.local_inventory_service.transports.LocalInventoryServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.LocalInventoryServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_local_inventories', + 'insert_local_inventory', + 'delete_local_inventory', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_local_inventory_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.shopping.merchant_inventories_v1beta.services.local_inventory_service.transports.LocalInventoryServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.LocalInventoryServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/content', +), + quota_project_id="octopus", + ) + + +def test_local_inventory_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.shopping.merchant_inventories_v1beta.services.local_inventory_service.transports.LocalInventoryServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.LocalInventoryServiceTransport() + adc.assert_called_once() + + +def test_local_inventory_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + LocalInventoryServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/content', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.LocalInventoryServiceGrpcTransport, + transports.LocalInventoryServiceGrpcAsyncIOTransport, + ], +) +def test_local_inventory_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/content',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.LocalInventoryServiceGrpcTransport, + transports.LocalInventoryServiceGrpcAsyncIOTransport, + transports.LocalInventoryServiceRestTransport, + ], +) +def test_local_inventory_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.LocalInventoryServiceGrpcTransport, grpc_helpers), + (transports.LocalInventoryServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_local_inventory_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "merchantapi.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/content', +), + scopes=["1", "2"], + default_host="merchantapi.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.LocalInventoryServiceGrpcTransport, transports.LocalInventoryServiceGrpcAsyncIOTransport]) +def test_local_inventory_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + +def test_local_inventory_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.LocalInventoryServiceRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_local_inventory_service_host_no_port(transport_name): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='merchantapi.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'merchantapi.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://merchantapi.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_local_inventory_service_host_with_port(transport_name): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='merchantapi.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'merchantapi.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://merchantapi.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_local_inventory_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = LocalInventoryServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = LocalInventoryServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_local_inventories._session + session2 = client2.transport.list_local_inventories._session + assert session1 != session2 + session1 = client1.transport.insert_local_inventory._session + session2 = client2.transport.insert_local_inventory._session + assert session1 != session2 + session1 = client1.transport.delete_local_inventory._session + session2 = client2.transport.delete_local_inventory._session + assert session1 != session2 +def test_local_inventory_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.LocalInventoryServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_local_inventory_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.LocalInventoryServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.LocalInventoryServiceGrpcTransport, transports.LocalInventoryServiceGrpcAsyncIOTransport]) +def test_local_inventory_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.LocalInventoryServiceGrpcTransport, transports.LocalInventoryServiceGrpcAsyncIOTransport]) +def test_local_inventory_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_local_inventory_path(): + account = "squid" + product = "clam" + store_code = "whelk" + expected = "accounts/{account}/products/{product}/localInventories/{store_code}".format(account=account, product=product, store_code=store_code, ) + actual = LocalInventoryServiceClient.local_inventory_path(account, product, store_code) + assert expected == actual + + +def test_parse_local_inventory_path(): + expected = { + "account": "octopus", + "product": "oyster", + "store_code": "nudibranch", + } + path = LocalInventoryServiceClient.local_inventory_path(**expected) + + # Check that the path construction is reversible. + actual = LocalInventoryServiceClient.parse_local_inventory_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = LocalInventoryServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = LocalInventoryServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = LocalInventoryServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = LocalInventoryServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = LocalInventoryServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = LocalInventoryServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = LocalInventoryServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = LocalInventoryServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = LocalInventoryServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = LocalInventoryServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = LocalInventoryServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = LocalInventoryServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = LocalInventoryServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = LocalInventoryServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = LocalInventoryServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.LocalInventoryServiceTransport, '_prep_wrapped_messages') as prep: + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.LocalInventoryServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = LocalInventoryServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_transport_close_grpc(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" + ) + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" + ) + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + with mock.patch.object(type(getattr(client.transport, "_session")), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (LocalInventoryServiceClient, transports.LocalInventoryServiceGrpcTransport), + (LocalInventoryServiceAsyncClient, transports.LocalInventoryServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/test_regional_inventory_service.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/test_regional_inventory_service.py new file mode 100644 index 000000000000..59f1d9c2b29c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/test_regional_inventory_service.py @@ -0,0 +1,3584 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable, AsyncIterable +from google.protobuf import json_format +import json +import math +import pytest +from google.api_core import api_core_version +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +try: + from google.auth.aio import credentials as ga_credentials_async + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account +from google.protobuf import timestamp_pb2 # type: ignore +from google.shopping.merchant_inventories_v1beta.services.regional_inventory_service import RegionalInventoryServiceAsyncClient +from google.shopping.merchant_inventories_v1beta.services.regional_inventory_service import RegionalInventoryServiceClient +from google.shopping.merchant_inventories_v1beta.services.regional_inventory_service import pagers +from google.shopping.merchant_inventories_v1beta.services.regional_inventory_service import transports +from google.shopping.merchant_inventories_v1beta.types import regionalinventory +from google.shopping.type.types import types +from google.type import interval_pb2 # type: ignore +import google.auth + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert RegionalInventoryServiceClient._get_default_mtls_endpoint(None) is None + assert RegionalInventoryServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert RegionalInventoryServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert RegionalInventoryServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert RegionalInventoryServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert RegionalInventoryServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert RegionalInventoryServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert RegionalInventoryServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert RegionalInventoryServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + RegionalInventoryServiceClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert RegionalInventoryServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert RegionalInventoryServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert RegionalInventoryServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + RegionalInventoryServiceClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert RegionalInventoryServiceClient._read_environment_variables() == (False, "auto", "foo.com") + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert RegionalInventoryServiceClient._get_client_cert_source(None, False) is None + assert RegionalInventoryServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert RegionalInventoryServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): + assert RegionalInventoryServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert RegionalInventoryServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(RegionalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceClient)) +@mock.patch.object(RegionalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = RegionalInventoryServiceClient._DEFAULT_UNIVERSE + default_endpoint = RegionalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = RegionalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert RegionalInventoryServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert RegionalInventoryServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == RegionalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT + assert RegionalInventoryServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert RegionalInventoryServiceClient._get_api_endpoint(None, None, default_universe, "always") == RegionalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT + assert RegionalInventoryServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == RegionalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT + assert RegionalInventoryServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert RegionalInventoryServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + RegionalInventoryServiceClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert RegionalInventoryServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert RegionalInventoryServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert RegionalInventoryServiceClient._get_universe_domain(None, None) == RegionalInventoryServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + RegionalInventoryServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize("client_class,transport_name", [ + (RegionalInventoryServiceClient, "grpc"), + (RegionalInventoryServiceAsyncClient, "grpc_asyncio"), + (RegionalInventoryServiceClient, "rest"), +]) +def test_regional_inventory_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'merchantapi.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://merchantapi.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.RegionalInventoryServiceGrpcTransport, "grpc"), + (transports.RegionalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.RegionalInventoryServiceRestTransport, "rest"), +]) +def test_regional_inventory_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (RegionalInventoryServiceClient, "grpc"), + (RegionalInventoryServiceAsyncClient, "grpc_asyncio"), + (RegionalInventoryServiceClient, "rest"), +]) +def test_regional_inventory_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'merchantapi.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://merchantapi.googleapis.com' + ) + + +def test_regional_inventory_service_client_get_transport_class(): + transport = RegionalInventoryServiceClient.get_transport_class() + available_transports = [ + transports.RegionalInventoryServiceGrpcTransport, + transports.RegionalInventoryServiceRestTransport, + ] + assert transport in available_transports + + transport = RegionalInventoryServiceClient.get_transport_class("grpc") + assert transport == transports.RegionalInventoryServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (RegionalInventoryServiceClient, transports.RegionalInventoryServiceGrpcTransport, "grpc"), + (RegionalInventoryServiceAsyncClient, transports.RegionalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (RegionalInventoryServiceClient, transports.RegionalInventoryServiceRestTransport, "rest"), +]) +@mock.patch.object(RegionalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceClient)) +@mock.patch.object(RegionalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceAsyncClient)) +def test_regional_inventory_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(RegionalInventoryServiceClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(RegionalInventoryServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (RegionalInventoryServiceClient, transports.RegionalInventoryServiceGrpcTransport, "grpc", "true"), + (RegionalInventoryServiceAsyncClient, transports.RegionalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (RegionalInventoryServiceClient, transports.RegionalInventoryServiceGrpcTransport, "grpc", "false"), + (RegionalInventoryServiceAsyncClient, transports.RegionalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (RegionalInventoryServiceClient, transports.RegionalInventoryServiceRestTransport, "rest", "true"), + (RegionalInventoryServiceClient, transports.RegionalInventoryServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(RegionalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceClient)) +@mock.patch.object(RegionalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_regional_inventory_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + RegionalInventoryServiceClient, RegionalInventoryServiceAsyncClient +]) +@mock.patch.object(RegionalInventoryServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegionalInventoryServiceClient)) +@mock.patch.object(RegionalInventoryServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegionalInventoryServiceAsyncClient)) +def test_regional_inventory_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + +@pytest.mark.parametrize("client_class", [ + RegionalInventoryServiceClient, RegionalInventoryServiceAsyncClient +]) +@mock.patch.object(RegionalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceClient)) +@mock.patch.object(RegionalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceAsyncClient)) +def test_regional_inventory_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = RegionalInventoryServiceClient._DEFAULT_UNIVERSE + default_endpoint = RegionalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = RegionalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + else: + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) + assert client.universe_domain == (mock_universe if universe_exists else default_universe) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (RegionalInventoryServiceClient, transports.RegionalInventoryServiceGrpcTransport, "grpc"), + (RegionalInventoryServiceAsyncClient, transports.RegionalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (RegionalInventoryServiceClient, transports.RegionalInventoryServiceRestTransport, "rest"), +]) +def test_regional_inventory_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (RegionalInventoryServiceClient, transports.RegionalInventoryServiceGrpcTransport, "grpc", grpc_helpers), + (RegionalInventoryServiceAsyncClient, transports.RegionalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (RegionalInventoryServiceClient, transports.RegionalInventoryServiceRestTransport, "rest", None), +]) +def test_regional_inventory_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_regional_inventory_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.transports.RegionalInventoryServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = RegionalInventoryServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (RegionalInventoryServiceClient, transports.RegionalInventoryServiceGrpcTransport, "grpc", grpc_helpers), + (RegionalInventoryServiceAsyncClient, transports.RegionalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_regional_inventory_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "merchantapi.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/content', +), + scopes=None, + default_host="merchantapi.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + regionalinventory.ListRegionalInventoriesRequest, + dict, +]) +def test_list_regional_inventories(request_type, transport: str = 'grpc'): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_regional_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = regionalinventory.ListRegionalInventoriesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_regional_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = regionalinventory.ListRegionalInventoriesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRegionalInventoriesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_regional_inventories_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = regionalinventory.ListRegionalInventoriesRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_regional_inventories), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_regional_inventories(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == regionalinventory.ListRegionalInventoriesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_regional_inventories_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_regional_inventories in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_regional_inventories] = mock_rpc + request = {} + client.list_regional_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_regional_inventories(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_regional_inventories_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_regional_inventories in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.list_regional_inventories] = mock_rpc + + request = {} + await client.list_regional_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_regional_inventories(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_regional_inventories_async(transport: str = 'grpc_asyncio', request_type=regionalinventory.ListRegionalInventoriesRequest): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_regional_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(regionalinventory.ListRegionalInventoriesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_regional_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = regionalinventory.ListRegionalInventoriesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRegionalInventoriesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_regional_inventories_async_from_dict(): + await test_list_regional_inventories_async(request_type=dict) + +def test_list_regional_inventories_field_headers(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = regionalinventory.ListRegionalInventoriesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_regional_inventories), + '__call__') as call: + call.return_value = regionalinventory.ListRegionalInventoriesResponse() + client.list_regional_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_regional_inventories_field_headers_async(): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = regionalinventory.ListRegionalInventoriesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_regional_inventories), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regionalinventory.ListRegionalInventoriesResponse()) + await client.list_regional_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_regional_inventories_flattened(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_regional_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = regionalinventory.ListRegionalInventoriesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_regional_inventories( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_regional_inventories_flattened_error(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_regional_inventories( + regionalinventory.ListRegionalInventoriesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_regional_inventories_flattened_async(): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_regional_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = regionalinventory.ListRegionalInventoriesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regionalinventory.ListRegionalInventoriesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_regional_inventories( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_regional_inventories_flattened_error_async(): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_regional_inventories( + regionalinventory.ListRegionalInventoriesRequest(), + parent='parent_value', + ) + + +def test_list_regional_inventories_pager(transport_name: str = "grpc"): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_regional_inventories), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[ + regionalinventory.RegionalInventory(), + regionalinventory.RegionalInventory(), + regionalinventory.RegionalInventory(), + ], + next_page_token='abc', + ), + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[], + next_page_token='def', + ), + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[ + regionalinventory.RegionalInventory(), + ], + next_page_token='ghi', + ), + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[ + regionalinventory.RegionalInventory(), + regionalinventory.RegionalInventory(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_regional_inventories(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, regionalinventory.RegionalInventory) + for i in results) +def test_list_regional_inventories_pages(transport_name: str = "grpc"): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_regional_inventories), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[ + regionalinventory.RegionalInventory(), + regionalinventory.RegionalInventory(), + regionalinventory.RegionalInventory(), + ], + next_page_token='abc', + ), + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[], + next_page_token='def', + ), + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[ + regionalinventory.RegionalInventory(), + ], + next_page_token='ghi', + ), + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[ + regionalinventory.RegionalInventory(), + regionalinventory.RegionalInventory(), + ], + ), + RuntimeError, + ) + pages = list(client.list_regional_inventories(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_regional_inventories_async_pager(): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_regional_inventories), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[ + regionalinventory.RegionalInventory(), + regionalinventory.RegionalInventory(), + regionalinventory.RegionalInventory(), + ], + next_page_token='abc', + ), + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[], + next_page_token='def', + ), + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[ + regionalinventory.RegionalInventory(), + ], + next_page_token='ghi', + ), + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[ + regionalinventory.RegionalInventory(), + regionalinventory.RegionalInventory(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_regional_inventories(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, regionalinventory.RegionalInventory) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_regional_inventories_async_pages(): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_regional_inventories), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[ + regionalinventory.RegionalInventory(), + regionalinventory.RegionalInventory(), + regionalinventory.RegionalInventory(), + ], + next_page_token='abc', + ), + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[], + next_page_token='def', + ), + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[ + regionalinventory.RegionalInventory(), + ], + next_page_token='ghi', + ), + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[ + regionalinventory.RegionalInventory(), + regionalinventory.RegionalInventory(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_regional_inventories(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + regionalinventory.InsertRegionalInventoryRequest, + dict, +]) +def test_insert_regional_inventory(request_type, transport: str = 'grpc'): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_regional_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = regionalinventory.RegionalInventory( + name='name_value', + account=749, + region='region_value', + availability='availability_value', + ) + response = client.insert_regional_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = regionalinventory.InsertRegionalInventoryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, regionalinventory.RegionalInventory) + assert response.name == 'name_value' + assert response.account == 749 + assert response.region == 'region_value' + assert response.availability == 'availability_value' + + +def test_insert_regional_inventory_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = regionalinventory.InsertRegionalInventoryRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_regional_inventory), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.insert_regional_inventory(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == regionalinventory.InsertRegionalInventoryRequest( + parent='parent_value', + ) + +def test_insert_regional_inventory_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.insert_regional_inventory in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.insert_regional_inventory] = mock_rpc + request = {} + client.insert_regional_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.insert_regional_inventory(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_insert_regional_inventory_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.insert_regional_inventory in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.insert_regional_inventory] = mock_rpc + + request = {} + await client.insert_regional_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.insert_regional_inventory(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_insert_regional_inventory_async(transport: str = 'grpc_asyncio', request_type=regionalinventory.InsertRegionalInventoryRequest): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_regional_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(regionalinventory.RegionalInventory( + name='name_value', + account=749, + region='region_value', + availability='availability_value', + )) + response = await client.insert_regional_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = regionalinventory.InsertRegionalInventoryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, regionalinventory.RegionalInventory) + assert response.name == 'name_value' + assert response.account == 749 + assert response.region == 'region_value' + assert response.availability == 'availability_value' + + +@pytest.mark.asyncio +async def test_insert_regional_inventory_async_from_dict(): + await test_insert_regional_inventory_async(request_type=dict) + +def test_insert_regional_inventory_field_headers(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = regionalinventory.InsertRegionalInventoryRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_regional_inventory), + '__call__') as call: + call.return_value = regionalinventory.RegionalInventory() + client.insert_regional_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_insert_regional_inventory_field_headers_async(): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = regionalinventory.InsertRegionalInventoryRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_regional_inventory), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regionalinventory.RegionalInventory()) + await client.insert_regional_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + regionalinventory.DeleteRegionalInventoryRequest, + dict, +]) +def test_delete_regional_inventory(request_type, transport: str = 'grpc'): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_regional_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_regional_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = regionalinventory.DeleteRegionalInventoryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_regional_inventory_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = regionalinventory.DeleteRegionalInventoryRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_regional_inventory), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_regional_inventory(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == regionalinventory.DeleteRegionalInventoryRequest( + name='name_value', + ) + +def test_delete_regional_inventory_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_regional_inventory in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_regional_inventory] = mock_rpc + request = {} + client.delete_regional_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_regional_inventory(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_regional_inventory_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_regional_inventory in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.delete_regional_inventory] = mock_rpc + + request = {} + await client.delete_regional_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_regional_inventory(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_regional_inventory_async(transport: str = 'grpc_asyncio', request_type=regionalinventory.DeleteRegionalInventoryRequest): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_regional_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_regional_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = regionalinventory.DeleteRegionalInventoryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_regional_inventory_async_from_dict(): + await test_delete_regional_inventory_async(request_type=dict) + +def test_delete_regional_inventory_field_headers(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = regionalinventory.DeleteRegionalInventoryRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_regional_inventory), + '__call__') as call: + call.return_value = None + client.delete_regional_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_regional_inventory_field_headers_async(): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = regionalinventory.DeleteRegionalInventoryRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_regional_inventory), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_regional_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_regional_inventory_flattened(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_regional_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_regional_inventory( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_regional_inventory_flattened_error(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_regional_inventory( + regionalinventory.DeleteRegionalInventoryRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_regional_inventory_flattened_async(): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_regional_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_regional_inventory( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_regional_inventory_flattened_error_async(): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_regional_inventory( + regionalinventory.DeleteRegionalInventoryRequest(), + name='name_value', + ) + + +def test_list_regional_inventories_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_regional_inventories in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_regional_inventories] = mock_rpc + + request = {} + client.list_regional_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_regional_inventories(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_regional_inventories_rest_required_fields(request_type=regionalinventory.ListRegionalInventoriesRequest): + transport_class = transports.RegionalInventoryServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_regional_inventories._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_regional_inventories._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = regionalinventory.ListRegionalInventoriesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = regionalinventory.ListRegionalInventoriesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_regional_inventories(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_regional_inventories_rest_unset_required_fields(): + transport = transports.RegionalInventoryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_regional_inventories._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_regional_inventories_rest_flattened(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = regionalinventory.ListRegionalInventoriesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'accounts/sample1/products/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = regionalinventory.ListRegionalInventoriesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_regional_inventories(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/inventories/v1beta/{parent=accounts/*/products/*}/regionalInventories" % client.transport._host, args[1]) + + +def test_list_regional_inventories_rest_flattened_error(transport: str = 'rest'): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_regional_inventories( + regionalinventory.ListRegionalInventoriesRequest(), + parent='parent_value', + ) + + +def test_list_regional_inventories_rest_pager(transport: str = 'rest'): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[ + regionalinventory.RegionalInventory(), + regionalinventory.RegionalInventory(), + regionalinventory.RegionalInventory(), + ], + next_page_token='abc', + ), + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[], + next_page_token='def', + ), + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[ + regionalinventory.RegionalInventory(), + ], + next_page_token='ghi', + ), + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[ + regionalinventory.RegionalInventory(), + regionalinventory.RegionalInventory(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(regionalinventory.ListRegionalInventoriesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'accounts/sample1/products/sample2'} + + pager = client.list_regional_inventories(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, regionalinventory.RegionalInventory) + for i in results) + + pages = list(client.list_regional_inventories(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_insert_regional_inventory_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.insert_regional_inventory in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.insert_regional_inventory] = mock_rpc + + request = {} + client.insert_regional_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.insert_regional_inventory(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_insert_regional_inventory_rest_required_fields(request_type=regionalinventory.InsertRegionalInventoryRequest): + transport_class = transports.RegionalInventoryServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).insert_regional_inventory._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).insert_regional_inventory._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = regionalinventory.RegionalInventory() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = regionalinventory.RegionalInventory.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.insert_regional_inventory(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_insert_regional_inventory_rest_unset_required_fields(): + transport = transports.RegionalInventoryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.insert_regional_inventory._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "regionalInventory", ))) + + +def test_delete_regional_inventory_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_regional_inventory in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_regional_inventory] = mock_rpc + + request = {} + client.delete_regional_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_regional_inventory(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_regional_inventory_rest_required_fields(request_type=regionalinventory.DeleteRegionalInventoryRequest): + transport_class = transports.RegionalInventoryServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_regional_inventory._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_regional_inventory._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_regional_inventory(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_regional_inventory_rest_unset_required_fields(): + transport = transports.RegionalInventoryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_regional_inventory._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_delete_regional_inventory_rest_flattened(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/products/sample2/regionalInventories/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_regional_inventory(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/inventories/v1beta/{name=accounts/*/products/*/regionalInventories/*}" % client.transport._host, args[1]) + + +def test_delete_regional_inventory_rest_flattened_error(transport: str = 'rest'): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_regional_inventory( + regionalinventory.DeleteRegionalInventoryRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.RegionalInventoryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.RegionalInventoryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegionalInventoryServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.RegionalInventoryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RegionalInventoryServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RegionalInventoryServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.RegionalInventoryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegionalInventoryServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.RegionalInventoryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = RegionalInventoryServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.RegionalInventoryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.RegionalInventoryServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.RegionalInventoryServiceGrpcTransport, + transports.RegionalInventoryServiceGrpcAsyncIOTransport, + transports.RegionalInventoryServiceRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_kind_grpc(): + transport = RegionalInventoryServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_regional_inventories_empty_call_grpc(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_regional_inventories), + '__call__') as call: + call.return_value = regionalinventory.ListRegionalInventoriesResponse() + client.list_regional_inventories(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regionalinventory.ListRegionalInventoriesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_insert_regional_inventory_empty_call_grpc(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.insert_regional_inventory), + '__call__') as call: + call.return_value = regionalinventory.RegionalInventory() + client.insert_regional_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regionalinventory.InsertRegionalInventoryRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_regional_inventory_empty_call_grpc(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_regional_inventory), + '__call__') as call: + call.return_value = None + client.delete_regional_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regionalinventory.DeleteRegionalInventoryRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = RegionalInventoryServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_regional_inventories_empty_call_grpc_asyncio(): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_regional_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regionalinventory.ListRegionalInventoriesResponse( + next_page_token='next_page_token_value', + )) + await client.list_regional_inventories(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regionalinventory.ListRegionalInventoriesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_insert_regional_inventory_empty_call_grpc_asyncio(): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.insert_regional_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regionalinventory.RegionalInventory( + name='name_value', + account=749, + region='region_value', + availability='availability_value', + )) + await client.insert_regional_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regionalinventory.InsertRegionalInventoryRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_regional_inventory_empty_call_grpc_asyncio(): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_regional_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_regional_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regionalinventory.DeleteRegionalInventoryRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = RegionalInventoryServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_regional_inventories_rest_bad_request(request_type=regionalinventory.ListRegionalInventoriesRequest): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1/products/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_regional_inventories(request) + + +@pytest.mark.parametrize("request_type", [ + regionalinventory.ListRegionalInventoriesRequest, + dict, +]) +def test_list_regional_inventories_rest_call_success(request_type): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1/products/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = regionalinventory.ListRegionalInventoriesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = regionalinventory.ListRegionalInventoriesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_regional_inventories(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRegionalInventoriesPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_regional_inventories_rest_interceptors(null_interceptor): + transport = transports.RegionalInventoryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegionalInventoryServiceRestInterceptor(), + ) + client = RegionalInventoryServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RegionalInventoryServiceRestInterceptor, "post_list_regional_inventories") as post, \ + mock.patch.object(transports.RegionalInventoryServiceRestInterceptor, "pre_list_regional_inventories") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = regionalinventory.ListRegionalInventoriesRequest.pb(regionalinventory.ListRegionalInventoriesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = regionalinventory.ListRegionalInventoriesResponse.to_json(regionalinventory.ListRegionalInventoriesResponse()) + req.return_value.content = return_value + + request = regionalinventory.ListRegionalInventoriesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = regionalinventory.ListRegionalInventoriesResponse() + + client.list_regional_inventories(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_insert_regional_inventory_rest_bad_request(request_type=regionalinventory.InsertRegionalInventoryRequest): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1/products/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.insert_regional_inventory(request) + + +@pytest.mark.parametrize("request_type", [ + regionalinventory.InsertRegionalInventoryRequest, + dict, +]) +def test_insert_regional_inventory_rest_call_success(request_type): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1/products/sample2'} + request_init["regional_inventory"] = {'name': 'name_value', 'account': 749, 'region': 'region_value', 'price': {'amount_micros': 1408, 'currency_code': 'currency_code_value'}, 'sale_price': {}, 'sale_price_effective_date': {'start_time': {'seconds': 751, 'nanos': 543}, 'end_time': {}}, 'availability': 'availability_value', 'custom_attributes': [{'name': 'name_value', 'value': 'value_value', 'group_values': {}}]} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = regionalinventory.InsertRegionalInventoryRequest.meta.fields["regional_inventory"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["regional_inventory"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["regional_inventory"][field])): + del request_init["regional_inventory"][field][i][subfield] + else: + del request_init["regional_inventory"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = regionalinventory.RegionalInventory( + name='name_value', + account=749, + region='region_value', + availability='availability_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = regionalinventory.RegionalInventory.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.insert_regional_inventory(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, regionalinventory.RegionalInventory) + assert response.name == 'name_value' + assert response.account == 749 + assert response.region == 'region_value' + assert response.availability == 'availability_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_insert_regional_inventory_rest_interceptors(null_interceptor): + transport = transports.RegionalInventoryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegionalInventoryServiceRestInterceptor(), + ) + client = RegionalInventoryServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RegionalInventoryServiceRestInterceptor, "post_insert_regional_inventory") as post, \ + mock.patch.object(transports.RegionalInventoryServiceRestInterceptor, "pre_insert_regional_inventory") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = regionalinventory.InsertRegionalInventoryRequest.pb(regionalinventory.InsertRegionalInventoryRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = regionalinventory.RegionalInventory.to_json(regionalinventory.RegionalInventory()) + req.return_value.content = return_value + + request = regionalinventory.InsertRegionalInventoryRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = regionalinventory.RegionalInventory() + + client.insert_regional_inventory(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_regional_inventory_rest_bad_request(request_type=regionalinventory.DeleteRegionalInventoryRequest): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/products/sample2/regionalInventories/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_regional_inventory(request) + + +@pytest.mark.parametrize("request_type", [ + regionalinventory.DeleteRegionalInventoryRequest, + dict, +]) +def test_delete_regional_inventory_rest_call_success(request_type): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/products/sample2/regionalInventories/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = '' + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_regional_inventory(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_regional_inventory_rest_interceptors(null_interceptor): + transport = transports.RegionalInventoryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegionalInventoryServiceRestInterceptor(), + ) + client = RegionalInventoryServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RegionalInventoryServiceRestInterceptor, "pre_delete_regional_inventory") as pre: + pre.assert_not_called() + pb_message = regionalinventory.DeleteRegionalInventoryRequest.pb(regionalinventory.DeleteRegionalInventoryRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + request = regionalinventory.DeleteRegionalInventoryRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_regional_inventory(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + +def test_initialize_client_w_rest(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_regional_inventories_empty_call_rest(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_regional_inventories), + '__call__') as call: + client.list_regional_inventories(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regionalinventory.ListRegionalInventoriesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_insert_regional_inventory_empty_call_rest(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.insert_regional_inventory), + '__call__') as call: + client.insert_regional_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regionalinventory.InsertRegionalInventoryRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_regional_inventory_empty_call_rest(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_regional_inventory), + '__call__') as call: + client.delete_regional_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regionalinventory.DeleteRegionalInventoryRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.RegionalInventoryServiceGrpcTransport, + ) + +def test_regional_inventory_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.RegionalInventoryServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_regional_inventory_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.transports.RegionalInventoryServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.RegionalInventoryServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_regional_inventories', + 'insert_regional_inventory', + 'delete_regional_inventory', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_regional_inventory_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.transports.RegionalInventoryServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegionalInventoryServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/content', +), + quota_project_id="octopus", + ) + + +def test_regional_inventory_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.transports.RegionalInventoryServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegionalInventoryServiceTransport() + adc.assert_called_once() + + +def test_regional_inventory_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + RegionalInventoryServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/content', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RegionalInventoryServiceGrpcTransport, + transports.RegionalInventoryServiceGrpcAsyncIOTransport, + ], +) +def test_regional_inventory_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/content',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RegionalInventoryServiceGrpcTransport, + transports.RegionalInventoryServiceGrpcAsyncIOTransport, + transports.RegionalInventoryServiceRestTransport, + ], +) +def test_regional_inventory_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.RegionalInventoryServiceGrpcTransport, grpc_helpers), + (transports.RegionalInventoryServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_regional_inventory_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "merchantapi.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/content', +), + scopes=["1", "2"], + default_host="merchantapi.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.RegionalInventoryServiceGrpcTransport, transports.RegionalInventoryServiceGrpcAsyncIOTransport]) +def test_regional_inventory_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + +def test_regional_inventory_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.RegionalInventoryServiceRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_regional_inventory_service_host_no_port(transport_name): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='merchantapi.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'merchantapi.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://merchantapi.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_regional_inventory_service_host_with_port(transport_name): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='merchantapi.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'merchantapi.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://merchantapi.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_regional_inventory_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = RegionalInventoryServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = RegionalInventoryServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_regional_inventories._session + session2 = client2.transport.list_regional_inventories._session + assert session1 != session2 + session1 = client1.transport.insert_regional_inventory._session + session2 = client2.transport.insert_regional_inventory._session + assert session1 != session2 + session1 = client1.transport.delete_regional_inventory._session + session2 = client2.transport.delete_regional_inventory._session + assert session1 != session2 +def test_regional_inventory_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.RegionalInventoryServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_regional_inventory_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.RegionalInventoryServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.RegionalInventoryServiceGrpcTransport, transports.RegionalInventoryServiceGrpcAsyncIOTransport]) +def test_regional_inventory_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.RegionalInventoryServiceGrpcTransport, transports.RegionalInventoryServiceGrpcAsyncIOTransport]) +def test_regional_inventory_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_regional_inventory_path(): + account = "squid" + product = "clam" + region = "whelk" + expected = "accounts/{account}/products/{product}/regionalInventories/{region}".format(account=account, product=product, region=region, ) + actual = RegionalInventoryServiceClient.regional_inventory_path(account, product, region) + assert expected == actual + + +def test_parse_regional_inventory_path(): + expected = { + "account": "octopus", + "product": "oyster", + "region": "nudibranch", + } + path = RegionalInventoryServiceClient.regional_inventory_path(**expected) + + # Check that the path construction is reversible. + actual = RegionalInventoryServiceClient.parse_regional_inventory_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = RegionalInventoryServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = RegionalInventoryServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = RegionalInventoryServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = RegionalInventoryServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = RegionalInventoryServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = RegionalInventoryServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = RegionalInventoryServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = RegionalInventoryServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = RegionalInventoryServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = RegionalInventoryServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = RegionalInventoryServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = RegionalInventoryServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = RegionalInventoryServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = RegionalInventoryServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = RegionalInventoryServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.RegionalInventoryServiceTransport, '_prep_wrapped_messages') as prep: + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.RegionalInventoryServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = RegionalInventoryServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_transport_close_grpc(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" + ) + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" + ) + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + with mock.patch.object(type(getattr(client.transport, "_session")), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (RegionalInventoryServiceClient, transports.RegionalInventoryServiceGrpcTransport), + (RegionalInventoryServiceAsyncClient, transports.RegionalInventoryServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/.coveragerc b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/.coveragerc new file mode 100644 index 000000000000..b0d5d8ec19fc --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/shopping/merchant_lfp/__init__.py + google/shopping/merchant_lfp/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-lfp/v1beta/.flake8 b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/MANIFEST.in b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/MANIFEST.in new file mode 100644 index 000000000000..f8f949b2a9d9 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/shopping/merchant_lfp *.py +recursive-include google/shopping/merchant_lfp_v1beta *.py diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/README.rst b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/README.rst new file mode 100644 index 000000000000..10235930e853 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Shopping Merchant Lfp 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 Lfp 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 diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/_static/custom.css b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/conf.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/conf.py new file mode 100644 index 000000000000..666ccbca902c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-lfp 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("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# 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.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +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-lfp" +copyright = u"2023, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# 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 = 'en' + +# 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"] + +# 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 Python", + "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-lfp-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-lfp.tex", + u"google-shopping-merchant-lfp 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-lfp", + u"Google Shopping Merchant Lfp 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-lfp", + u"google-shopping-merchant-lfp Documentation", + author, + "google-shopping-merchant-lfp", + "GAPIC library for Google Shopping Merchant Lfp API", + "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": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", 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-lfp/v1beta/docs/index.rst b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/index.rst new file mode 100644 index 000000000000..da51952965f1 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + merchant_lfp_v1beta/services_ + merchant_lfp_v1beta/types_ diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/merchant_lfp_v1beta/lfp_inventory_service.rst b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/merchant_lfp_v1beta/lfp_inventory_service.rst new file mode 100644 index 000000000000..bec997d8d55e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/merchant_lfp_v1beta/lfp_inventory_service.rst @@ -0,0 +1,6 @@ +LfpInventoryService +------------------------------------- + +.. automodule:: google.shopping.merchant_lfp_v1beta.services.lfp_inventory_service + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/merchant_lfp_v1beta/lfp_sale_service.rst b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/merchant_lfp_v1beta/lfp_sale_service.rst new file mode 100644 index 000000000000..0d6ff3402769 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/merchant_lfp_v1beta/lfp_sale_service.rst @@ -0,0 +1,6 @@ +LfpSaleService +-------------------------------- + +.. automodule:: google.shopping.merchant_lfp_v1beta.services.lfp_sale_service + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/merchant_lfp_v1beta/lfp_store_service.rst b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/merchant_lfp_v1beta/lfp_store_service.rst new file mode 100644 index 000000000000..5c836ac7e718 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/merchant_lfp_v1beta/lfp_store_service.rst @@ -0,0 +1,10 @@ +LfpStoreService +--------------------------------- + +.. automodule:: google.shopping.merchant_lfp_v1beta.services.lfp_store_service + :members: + :inherited-members: + +.. automodule:: google.shopping.merchant_lfp_v1beta.services.lfp_store_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/merchant_lfp_v1beta/services_.rst b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/merchant_lfp_v1beta/services_.rst new file mode 100644 index 000000000000..799a587ac9ec --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/merchant_lfp_v1beta/services_.rst @@ -0,0 +1,8 @@ +Services for Google Shopping Merchant Lfp v1beta API +==================================================== +.. toctree:: + :maxdepth: 2 + + lfp_inventory_service + lfp_sale_service + lfp_store_service diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/merchant_lfp_v1beta/types_.rst b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/merchant_lfp_v1beta/types_.rst new file mode 100644 index 000000000000..71508ca1ae9e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/merchant_lfp_v1beta/types_.rst @@ -0,0 +1,6 @@ +Types for Google Shopping Merchant Lfp v1beta API +================================================= + +.. automodule:: google.shopping.merchant_lfp_v1beta.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp/__init__.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp/__init__.py new file mode 100644 index 000000000000..6a3c87cb8651 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp/__init__.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_lfp import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.shopping.merchant_lfp_v1beta.services.lfp_inventory_service.client import LfpInventoryServiceClient +from google.shopping.merchant_lfp_v1beta.services.lfp_inventory_service.async_client import LfpInventoryServiceAsyncClient +from google.shopping.merchant_lfp_v1beta.services.lfp_sale_service.client import LfpSaleServiceClient +from google.shopping.merchant_lfp_v1beta.services.lfp_sale_service.async_client import LfpSaleServiceAsyncClient +from google.shopping.merchant_lfp_v1beta.services.lfp_store_service.client import LfpStoreServiceClient +from google.shopping.merchant_lfp_v1beta.services.lfp_store_service.async_client import LfpStoreServiceAsyncClient + +from google.shopping.merchant_lfp_v1beta.types.lfpinventory import InsertLfpInventoryRequest +from google.shopping.merchant_lfp_v1beta.types.lfpinventory import LfpInventory +from google.shopping.merchant_lfp_v1beta.types.lfpsale import InsertLfpSaleRequest +from google.shopping.merchant_lfp_v1beta.types.lfpsale import LfpSale +from google.shopping.merchant_lfp_v1beta.types.lfpstore import DeleteLfpStoreRequest +from google.shopping.merchant_lfp_v1beta.types.lfpstore import GetLfpStoreRequest +from google.shopping.merchant_lfp_v1beta.types.lfpstore import InsertLfpStoreRequest +from google.shopping.merchant_lfp_v1beta.types.lfpstore import LfpStore +from google.shopping.merchant_lfp_v1beta.types.lfpstore import ListLfpStoresRequest +from google.shopping.merchant_lfp_v1beta.types.lfpstore import ListLfpStoresResponse + +__all__ = ('LfpInventoryServiceClient', + 'LfpInventoryServiceAsyncClient', + 'LfpSaleServiceClient', + 'LfpSaleServiceAsyncClient', + 'LfpStoreServiceClient', + 'LfpStoreServiceAsyncClient', + 'InsertLfpInventoryRequest', + 'LfpInventory', + 'InsertLfpSaleRequest', + 'LfpSale', + 'DeleteLfpStoreRequest', + 'GetLfpStoreRequest', + 'InsertLfpStoreRequest', + 'LfpStore', + 'ListLfpStoresRequest', + 'ListLfpStoresResponse', +) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp/gapic_version.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-lfp/v1beta/google/shopping/merchant_lfp/py.typed b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp/py.typed new file mode 100644 index 000000000000..da994d195527 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-shopping-merchant-lfp package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/__init__.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/__init__.py new file mode 100644 index 000000000000..f5221f93e79c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/__init__.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_lfp_v1beta import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.lfp_inventory_service import LfpInventoryServiceClient +from .services.lfp_inventory_service import LfpInventoryServiceAsyncClient +from .services.lfp_sale_service import LfpSaleServiceClient +from .services.lfp_sale_service import LfpSaleServiceAsyncClient +from .services.lfp_store_service import LfpStoreServiceClient +from .services.lfp_store_service import LfpStoreServiceAsyncClient + +from .types.lfpinventory import InsertLfpInventoryRequest +from .types.lfpinventory import LfpInventory +from .types.lfpsale import InsertLfpSaleRequest +from .types.lfpsale import LfpSale +from .types.lfpstore import DeleteLfpStoreRequest +from .types.lfpstore import GetLfpStoreRequest +from .types.lfpstore import InsertLfpStoreRequest +from .types.lfpstore import LfpStore +from .types.lfpstore import ListLfpStoresRequest +from .types.lfpstore import ListLfpStoresResponse + +__all__ = ( + 'LfpInventoryServiceAsyncClient', + 'LfpSaleServiceAsyncClient', + 'LfpStoreServiceAsyncClient', +'DeleteLfpStoreRequest', +'GetLfpStoreRequest', +'InsertLfpInventoryRequest', +'InsertLfpSaleRequest', +'InsertLfpStoreRequest', +'LfpInventory', +'LfpInventoryServiceClient', +'LfpSale', +'LfpSaleServiceClient', +'LfpStore', +'LfpStoreServiceClient', +'ListLfpStoresRequest', +'ListLfpStoresResponse', +) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/gapic_metadata.json b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/gapic_metadata.json new file mode 100644 index 000000000000..8f3360964705 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/gapic_metadata.json @@ -0,0 +1,156 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.shopping.merchant_lfp_v1beta", + "protoPackage": "google.shopping.merchant.lfp.v1beta", + "schema": "1.0", + "services": { + "LfpInventoryService": { + "clients": { + "grpc": { + "libraryClient": "LfpInventoryServiceClient", + "rpcs": { + "InsertLfpInventory": { + "methods": [ + "insert_lfp_inventory" + ] + } + } + }, + "grpc-async": { + "libraryClient": "LfpInventoryServiceAsyncClient", + "rpcs": { + "InsertLfpInventory": { + "methods": [ + "insert_lfp_inventory" + ] + } + } + }, + "rest": { + "libraryClient": "LfpInventoryServiceClient", + "rpcs": { + "InsertLfpInventory": { + "methods": [ + "insert_lfp_inventory" + ] + } + } + } + } + }, + "LfpSaleService": { + "clients": { + "grpc": { + "libraryClient": "LfpSaleServiceClient", + "rpcs": { + "InsertLfpSale": { + "methods": [ + "insert_lfp_sale" + ] + } + } + }, + "grpc-async": { + "libraryClient": "LfpSaleServiceAsyncClient", + "rpcs": { + "InsertLfpSale": { + "methods": [ + "insert_lfp_sale" + ] + } + } + }, + "rest": { + "libraryClient": "LfpSaleServiceClient", + "rpcs": { + "InsertLfpSale": { + "methods": [ + "insert_lfp_sale" + ] + } + } + } + } + }, + "LfpStoreService": { + "clients": { + "grpc": { + "libraryClient": "LfpStoreServiceClient", + "rpcs": { + "DeleteLfpStore": { + "methods": [ + "delete_lfp_store" + ] + }, + "GetLfpStore": { + "methods": [ + "get_lfp_store" + ] + }, + "InsertLfpStore": { + "methods": [ + "insert_lfp_store" + ] + }, + "ListLfpStores": { + "methods": [ + "list_lfp_stores" + ] + } + } + }, + "grpc-async": { + "libraryClient": "LfpStoreServiceAsyncClient", + "rpcs": { + "DeleteLfpStore": { + "methods": [ + "delete_lfp_store" + ] + }, + "GetLfpStore": { + "methods": [ + "get_lfp_store" + ] + }, + "InsertLfpStore": { + "methods": [ + "insert_lfp_store" + ] + }, + "ListLfpStores": { + "methods": [ + "list_lfp_stores" + ] + } + } + }, + "rest": { + "libraryClient": "LfpStoreServiceClient", + "rpcs": { + "DeleteLfpStore": { + "methods": [ + "delete_lfp_store" + ] + }, + "GetLfpStore": { + "methods": [ + "get_lfp_store" + ] + }, + "InsertLfpStore": { + "methods": [ + "insert_lfp_store" + ] + }, + "ListLfpStores": { + "methods": [ + "list_lfp_stores" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/gapic_version.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-lfp/v1beta/google/shopping/merchant_lfp_v1beta/py.typed b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/py.typed new file mode 100644 index 000000000000..da994d195527 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-shopping-merchant-lfp package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/__init__.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/__init__.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/__init__.py new file mode 100644 index 000000000000..ee83eecc3a55 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 LfpInventoryServiceClient +from .async_client import LfpInventoryServiceAsyncClient + +__all__ = ( + 'LfpInventoryServiceClient', + 'LfpInventoryServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/async_client.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/async_client.py new file mode 100644 index 000000000000..5d709f778740 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/async_client.py @@ -0,0 +1,357 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_lfp_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 + + +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 timestamp_pb2 # type: ignore +from google.shopping.merchant_lfp_v1beta.types import lfpinventory +from google.shopping.type.types import types +from .transports.base import LfpInventoryServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import LfpInventoryServiceGrpcAsyncIOTransport +from .client import LfpInventoryServiceClient + +try: + from google.api_core import client_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 LfpInventoryServiceAsyncClient: + """Service for a `LFP + partner `__ to + submit local inventories for a merchant. + """ + + _client: LfpInventoryServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = LfpInventoryServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = LfpInventoryServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = LfpInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = LfpInventoryServiceClient._DEFAULT_UNIVERSE + + lfp_inventory_path = staticmethod(LfpInventoryServiceClient.lfp_inventory_path) + parse_lfp_inventory_path = staticmethod(LfpInventoryServiceClient.parse_lfp_inventory_path) + common_billing_account_path = staticmethod(LfpInventoryServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(LfpInventoryServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(LfpInventoryServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(LfpInventoryServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(LfpInventoryServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(LfpInventoryServiceClient.parse_common_organization_path) + common_project_path = staticmethod(LfpInventoryServiceClient.common_project_path) + parse_common_project_path = staticmethod(LfpInventoryServiceClient.parse_common_project_path) + common_location_path = staticmethod(LfpInventoryServiceClient.common_location_path) + parse_common_location_path = staticmethod(LfpInventoryServiceClient.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: + LfpInventoryServiceAsyncClient: The constructed client. + """ + return LfpInventoryServiceClient.from_service_account_info.__func__(LfpInventoryServiceAsyncClient, 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: + LfpInventoryServiceAsyncClient: The constructed client. + """ + return LfpInventoryServiceClient.from_service_account_file.__func__(LfpInventoryServiceAsyncClient, 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 LfpInventoryServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> LfpInventoryServiceTransport: + """Returns the transport used by the client instance. + + Returns: + LfpInventoryServiceTransport: 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 = LfpInventoryServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, LfpInventoryServiceTransport, Callable[..., LfpInventoryServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the lfp inventory service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,LfpInventoryServiceTransport,Callable[..., LfpInventoryServiceTransport]]]): + 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 LfpInventoryServiceTransport 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 = LfpInventoryServiceClient( + 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.lfp_v1beta.LfpInventoryServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.lfp.v1beta.LfpInventoryService", + "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.lfp.v1beta.LfpInventoryService", + "credentialsType": None, + } + ) + + async def insert_lfp_inventory(self, + request: Optional[Union[lfpinventory.InsertLfpInventoryRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> lfpinventory.LfpInventory: + r"""Inserts a ``LfpInventory`` resource for the given target + merchant account. If the resource already exists, it will be + replaced. The inventory automatically expires after 30 days. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_lfp_v1beta + + async def sample_insert_lfp_inventory(): + # Create a client + client = merchant_lfp_v1beta.LfpInventoryServiceAsyncClient() + + # Initialize request argument(s) + lfp_inventory = merchant_lfp_v1beta.LfpInventory() + lfp_inventory.target_account = 1491 + lfp_inventory.store_code = "store_code_value" + lfp_inventory.offer_id = "offer_id_value" + lfp_inventory.region_code = "region_code_value" + lfp_inventory.content_language = "content_language_value" + lfp_inventory.availability = "availability_value" + + request = merchant_lfp_v1beta.InsertLfpInventoryRequest( + parent="parent_value", + lfp_inventory=lfp_inventory, + ) + + # Make the request + response = await client.insert_lfp_inventory(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_lfp_v1beta.types.InsertLfpInventoryRequest, dict]]): + The request object. Request message for the ``InsertLfpInventory`` 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_lfp_v1beta.types.LfpInventory: + Local Inventory for the merchant. + """ + # 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, lfpinventory.InsertLfpInventoryRequest): + request = lfpinventory.InsertLfpInventoryRequest(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_lfp_inventory] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "LfpInventoryServiceAsyncClient": + 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__) + + +__all__ = ( + "LfpInventoryServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/client.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/client.py new file mode 100644 index 000000000000..64e3e171ba8f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/client.py @@ -0,0 +1,693 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +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_lfp_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 + +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 timestamp_pb2 # type: ignore +from google.shopping.merchant_lfp_v1beta.types import lfpinventory +from google.shopping.type.types import types +from .transports.base import LfpInventoryServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import LfpInventoryServiceGrpcTransport +from .transports.grpc_asyncio import LfpInventoryServiceGrpcAsyncIOTransport +from .transports.rest import LfpInventoryServiceRestTransport + + +class LfpInventoryServiceClientMeta(type): + """Metaclass for the LfpInventoryService 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[LfpInventoryServiceTransport]] + _transport_registry["grpc"] = LfpInventoryServiceGrpcTransport + _transport_registry["grpc_asyncio"] = LfpInventoryServiceGrpcAsyncIOTransport + _transport_registry["rest"] = LfpInventoryServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[LfpInventoryServiceTransport]: + """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 LfpInventoryServiceClient(metaclass=LfpInventoryServiceClientMeta): + """Service for a `LFP + partner `__ to + submit local inventories for a merchant. + """ + + @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: + LfpInventoryServiceClient: 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: + LfpInventoryServiceClient: 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) -> LfpInventoryServiceTransport: + """Returns the transport used by the client instance. + + Returns: + LfpInventoryServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def lfp_inventory_path(account: str,target_merchant: str,store_code: str,offer: str,) -> str: + """Returns a fully-qualified lfp_inventory string.""" + return "accounts/{account}/lfpInventories/{target_merchant}~{store_code}~{offer}".format(account=account, target_merchant=target_merchant, store_code=store_code, offer=offer, ) + + @staticmethod + def parse_lfp_inventory_path(path: str) -> Dict[str,str]: + """Parses a lfp_inventory path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/lfpInventories/(?P.+?)~(?P.+?)~(?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 = LfpInventoryServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = LfpInventoryServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = LfpInventoryServiceClient._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 = LfpInventoryServiceClient._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 + + @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, LfpInventoryServiceTransport, Callable[..., LfpInventoryServiceTransport]]] = 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 inventory service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,LfpInventoryServiceTransport,Callable[..., LfpInventoryServiceTransport]]]): + 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 LfpInventoryServiceTransport 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 = LfpInventoryServiceClient._read_environment_variables() + self._client_cert_source = LfpInventoryServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = LfpInventoryServiceClient._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, LfpInventoryServiceTransport) + if transport_provided: + # transport is a LfpInventoryServiceTransport 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(LfpInventoryServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + LfpInventoryServiceClient._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[LfpInventoryServiceTransport], Callable[..., LfpInventoryServiceTransport]] = ( + LfpInventoryServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., LfpInventoryServiceTransport], 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.lfp_v1beta.LfpInventoryServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.lfp.v1beta.LfpInventoryService", + "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.lfp.v1beta.LfpInventoryService", + "credentialsType": None, + } + ) + + def insert_lfp_inventory(self, + request: Optional[Union[lfpinventory.InsertLfpInventoryRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> lfpinventory.LfpInventory: + r"""Inserts a ``LfpInventory`` resource for the given target + merchant account. If the resource already exists, it will be + replaced. The inventory automatically expires after 30 days. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_lfp_v1beta + + def sample_insert_lfp_inventory(): + # Create a client + client = merchant_lfp_v1beta.LfpInventoryServiceClient() + + # Initialize request argument(s) + lfp_inventory = merchant_lfp_v1beta.LfpInventory() + lfp_inventory.target_account = 1491 + lfp_inventory.store_code = "store_code_value" + lfp_inventory.offer_id = "offer_id_value" + lfp_inventory.region_code = "region_code_value" + lfp_inventory.content_language = "content_language_value" + lfp_inventory.availability = "availability_value" + + request = merchant_lfp_v1beta.InsertLfpInventoryRequest( + parent="parent_value", + lfp_inventory=lfp_inventory, + ) + + # Make the request + response = client.insert_lfp_inventory(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_lfp_v1beta.types.InsertLfpInventoryRequest, dict]): + The request object. Request message for the ``InsertLfpInventory`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.shopping.merchant_lfp_v1beta.types.LfpInventory: + Local Inventory for the merchant. + """ + # 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, lfpinventory.InsertLfpInventoryRequest): + request = lfpinventory.InsertLfpInventoryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.insert_lfp_inventory] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "LfpInventoryServiceClient": + 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__) + + +__all__ = ( + "LfpInventoryServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/README.rst new file mode 100644 index 000000000000..c4b5f2586c1a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`LfpInventoryServiceTransport` is the ABC for all transports. +- public child `LfpInventoryServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `LfpInventoryServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseLfpInventoryServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `LfpInventoryServiceRestTransport` 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-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/__init__.py new file mode 100644 index 000000000000..0d9048eb741f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 LfpInventoryServiceTransport +from .grpc import LfpInventoryServiceGrpcTransport +from .grpc_asyncio import LfpInventoryServiceGrpcAsyncIOTransport +from .rest import LfpInventoryServiceRestTransport +from .rest import LfpInventoryServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[LfpInventoryServiceTransport]] +_transport_registry['grpc'] = LfpInventoryServiceGrpcTransport +_transport_registry['grpc_asyncio'] = LfpInventoryServiceGrpcAsyncIOTransport +_transport_registry['rest'] = LfpInventoryServiceRestTransport + +__all__ = ( + 'LfpInventoryServiceTransport', + 'LfpInventoryServiceGrpcTransport', + 'LfpInventoryServiceGrpcAsyncIOTransport', + 'LfpInventoryServiceRestTransport', + 'LfpInventoryServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/base.py new file mode 100644 index 000000000000..73a179941ae6 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/base.py @@ -0,0 +1,154 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_lfp_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 + +from google.shopping.merchant_lfp_v1beta.types import lfpinventory + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class LfpInventoryServiceTransport(abc.ABC): + """Abstract transport class for LfpInventoryService.""" + + 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.insert_lfp_inventory: gapic_v1.method.wrap_method( + self.insert_lfp_inventory, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def insert_lfp_inventory(self) -> Callable[ + [lfpinventory.InsertLfpInventoryRequest], + Union[ + lfpinventory.LfpInventory, + Awaitable[lfpinventory.LfpInventory] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'LfpInventoryServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/grpc.py new file mode 100644 index 000000000000..d5f88e0239d8 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/grpc.py @@ -0,0 +1,351 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_lfp_v1beta.types import lfpinventory +from .base import LfpInventoryServiceTransport, 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.lfp.v1beta.LfpInventoryService", + "rpcName": 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.lfp.v1beta.LfpInventoryService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class LfpInventoryServiceGrpcTransport(LfpInventoryServiceTransport): + """gRPC backend transport for LfpInventoryService. + + Service for a `LFP + partner `__ to + submit local inventories for a merchant. + + This 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 insert_lfp_inventory(self) -> Callable[ + [lfpinventory.InsertLfpInventoryRequest], + lfpinventory.LfpInventory]: + r"""Return a callable for the insert lfp inventory method over gRPC. + + Inserts a ``LfpInventory`` resource for the given target + merchant account. If the resource already exists, it will be + replaced. The inventory automatically expires after 30 days. + + Returns: + Callable[[~.InsertLfpInventoryRequest], + ~.LfpInventory]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_lfp_inventory' not in self._stubs: + self._stubs['insert_lfp_inventory'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.lfp.v1beta.LfpInventoryService/InsertLfpInventory', + request_serializer=lfpinventory.InsertLfpInventoryRequest.serialize, + response_deserializer=lfpinventory.LfpInventory.deserialize, + ) + return self._stubs['insert_lfp_inventory'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'LfpInventoryServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..0f89e2fcd73c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/grpc_asyncio.py @@ -0,0 +1,371 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_lfp_v1beta.types import lfpinventory +from .base import LfpInventoryServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import LfpInventoryServiceGrpcTransport + +try: + from google.api_core import client_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.lfp.v1beta.LfpInventoryService", + "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.lfp.v1beta.LfpInventoryService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class LfpInventoryServiceGrpcAsyncIOTransport(LfpInventoryServiceTransport): + """gRPC AsyncIO backend transport for LfpInventoryService. + + Service for a `LFP + partner `__ to + submit local inventories for a merchant. + + This 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 insert_lfp_inventory(self) -> Callable[ + [lfpinventory.InsertLfpInventoryRequest], + Awaitable[lfpinventory.LfpInventory]]: + r"""Return a callable for the insert lfp inventory method over gRPC. + + Inserts a ``LfpInventory`` resource for the given target + merchant account. If the resource already exists, it will be + replaced. The inventory automatically expires after 30 days. + + Returns: + Callable[[~.InsertLfpInventoryRequest], + Awaitable[~.LfpInventory]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_lfp_inventory' not in self._stubs: + self._stubs['insert_lfp_inventory'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.lfp.v1beta.LfpInventoryService/InsertLfpInventory', + request_serializer=lfpinventory.InsertLfpInventoryRequest.serialize, + response_deserializer=lfpinventory.LfpInventory.deserialize, + ) + return self._stubs['insert_lfp_inventory'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.insert_lfp_inventory: self._wrap_method( + self.insert_lfp_inventory, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + +__all__ = ( + 'LfpInventoryServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/rest.py new file mode 100644 index 000000000000..88744ba1d88c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/rest.py @@ -0,0 +1,331 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +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_lfp_v1beta.types import lfpinventory + + +from .rest_base import _BaseLfpInventoryServiceRestTransport +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}", +) + + +class LfpInventoryServiceRestInterceptor: + """Interceptor for LfpInventoryService. + + 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 LfpInventoryServiceRestTransport. + + .. code-block:: python + class MyCustomLfpInventoryServiceInterceptor(LfpInventoryServiceRestInterceptor): + def pre_insert_lfp_inventory(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_insert_lfp_inventory(self, response): + logging.log(f"Received response: {response}") + return response + + transport = LfpInventoryServiceRestTransport(interceptor=MyCustomLfpInventoryServiceInterceptor()) + client = LfpInventoryServiceClient(transport=transport) + + + """ + def pre_insert_lfp_inventory(self, request: lfpinventory.InsertLfpInventoryRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[lfpinventory.InsertLfpInventoryRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for insert_lfp_inventory + + Override in a subclass to manipulate the request or metadata + before they are sent to the LfpInventoryService server. + """ + return request, metadata + + def post_insert_lfp_inventory(self, response: lfpinventory.LfpInventory) -> lfpinventory.LfpInventory: + """Post-rpc interceptor for insert_lfp_inventory + + Override in a subclass to manipulate the response + after it is returned by the LfpInventoryService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class LfpInventoryServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: LfpInventoryServiceRestInterceptor + + +class LfpInventoryServiceRestTransport(_BaseLfpInventoryServiceRestTransport): + """REST backend synchronous transport for LfpInventoryService. + + Service for a `LFP + partner `__ to + submit local inventories for a merchant. + + This 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[LfpInventoryServiceRestInterceptor] = 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 LfpInventoryServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _InsertLfpInventory(_BaseLfpInventoryServiceRestTransport._BaseInsertLfpInventory, LfpInventoryServiceRestStub): + def __hash__(self): + return hash("LfpInventoryServiceRestTransport.InsertLfpInventory") + + @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: lfpinventory.InsertLfpInventoryRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> lfpinventory.LfpInventory: + r"""Call the insert lfp inventory method over HTTP. + + Args: + request (~.lfpinventory.InsertLfpInventoryRequest): + The request object. Request message for the ``InsertLfpInventory`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.lfpinventory.LfpInventory: + Local Inventory for the merchant. + """ + + http_options = _BaseLfpInventoryServiceRestTransport._BaseInsertLfpInventory._get_http_options() + + request, metadata = self._interceptor.pre_insert_lfp_inventory(request, metadata) + transcoded_request = _BaseLfpInventoryServiceRestTransport._BaseInsertLfpInventory._get_transcoded_request(http_options, request) + + body = _BaseLfpInventoryServiceRestTransport._BaseInsertLfpInventory._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseLfpInventoryServiceRestTransport._BaseInsertLfpInventory._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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.lfp_v1beta.LfpInventoryServiceClient.InsertLfpInventory", + extra = { + "serviceName": "google.shopping.merchant.lfp.v1beta.LfpInventoryService", + "rpcName": "InsertLfpInventory", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = LfpInventoryServiceRestTransport._InsertLfpInventory._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 = lfpinventory.LfpInventory() + pb_resp = lfpinventory.LfpInventory.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_insert_lfp_inventory(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = lfpinventory.LfpInventory.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.lfp_v1beta.LfpInventoryServiceClient.insert_lfp_inventory", + extra = { + "serviceName": "google.shopping.merchant.lfp.v1beta.LfpInventoryService", + "rpcName": "InsertLfpInventory", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def insert_lfp_inventory(self) -> Callable[ + [lfpinventory.InsertLfpInventoryRequest], + lfpinventory.LfpInventory]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._InsertLfpInventory(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'LfpInventoryServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/rest_base.py new file mode 100644 index 000000000000..5d4ac2c2f2b4 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/rest_base.py @@ -0,0 +1,138 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 LfpInventoryServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.shopping.merchant_lfp_v1beta.types import lfpinventory + + +class _BaseLfpInventoryServiceRestTransport(LfpInventoryServiceTransport): + """Base REST backend transport for LfpInventoryService. + + 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 _BaseInsertLfpInventory: + 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': '/lfp/v1beta/{parent=accounts/*}/lfpInventories:insert', + 'body': 'lfp_inventory', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = lfpinventory.InsertLfpInventoryRequest.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(_BaseLfpInventoryServiceRestTransport._BaseInsertLfpInventory._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseLfpInventoryServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/__init__.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/__init__.py new file mode 100644 index 000000000000..480f390ef2d5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 LfpSaleServiceClient +from .async_client import LfpSaleServiceAsyncClient + +__all__ = ( + 'LfpSaleServiceClient', + 'LfpSaleServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/async_client.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/async_client.py new file mode 100644 index 000000000000..f3636dc14aa0 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/async_client.py @@ -0,0 +1,357 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_lfp_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 + + +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 timestamp_pb2 # type: ignore +from google.shopping.merchant_lfp_v1beta.types import lfpsale +from google.shopping.type.types import types +from .transports.base import LfpSaleServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import LfpSaleServiceGrpcAsyncIOTransport +from .client import LfpSaleServiceClient + +try: + from google.api_core import client_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 LfpSaleServiceAsyncClient: + """Service for a `LFP + partner `__ to + submit sales data for a merchant. + """ + + _client: LfpSaleServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = LfpSaleServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = LfpSaleServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = LfpSaleServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = LfpSaleServiceClient._DEFAULT_UNIVERSE + + lfp_sale_path = staticmethod(LfpSaleServiceClient.lfp_sale_path) + parse_lfp_sale_path = staticmethod(LfpSaleServiceClient.parse_lfp_sale_path) + common_billing_account_path = staticmethod(LfpSaleServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(LfpSaleServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(LfpSaleServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(LfpSaleServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(LfpSaleServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(LfpSaleServiceClient.parse_common_organization_path) + common_project_path = staticmethod(LfpSaleServiceClient.common_project_path) + parse_common_project_path = staticmethod(LfpSaleServiceClient.parse_common_project_path) + common_location_path = staticmethod(LfpSaleServiceClient.common_location_path) + parse_common_location_path = staticmethod(LfpSaleServiceClient.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: + LfpSaleServiceAsyncClient: The constructed client. + """ + return LfpSaleServiceClient.from_service_account_info.__func__(LfpSaleServiceAsyncClient, 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: + LfpSaleServiceAsyncClient: The constructed client. + """ + return LfpSaleServiceClient.from_service_account_file.__func__(LfpSaleServiceAsyncClient, 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 LfpSaleServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> LfpSaleServiceTransport: + """Returns the transport used by the client instance. + + Returns: + LfpSaleServiceTransport: 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 = LfpSaleServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, LfpSaleServiceTransport, Callable[..., LfpSaleServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the lfp sale 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,LfpSaleServiceTransport,Callable[..., LfpSaleServiceTransport]]]): + 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 LfpSaleServiceTransport 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 = LfpSaleServiceClient( + 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.lfp_v1beta.LfpSaleServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.lfp.v1beta.LfpSaleService", + "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.lfp.v1beta.LfpSaleService", + "credentialsType": None, + } + ) + + async def insert_lfp_sale(self, + request: Optional[Union[lfpsale.InsertLfpSaleRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> lfpsale.LfpSale: + r"""Inserts a ``LfpSale`` 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_lfp_v1beta + + async def sample_insert_lfp_sale(): + # Create a client + client = merchant_lfp_v1beta.LfpSaleServiceAsyncClient() + + # Initialize request argument(s) + lfp_sale = merchant_lfp_v1beta.LfpSale() + lfp_sale.target_account = 1491 + lfp_sale.store_code = "store_code_value" + lfp_sale.offer_id = "offer_id_value" + lfp_sale.region_code = "region_code_value" + lfp_sale.content_language = "content_language_value" + lfp_sale.gtin = "gtin_value" + lfp_sale.quantity = 895 + + request = merchant_lfp_v1beta.InsertLfpSaleRequest( + parent="parent_value", + lfp_sale=lfp_sale, + ) + + # Make the request + response = await client.insert_lfp_sale(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_lfp_v1beta.types.InsertLfpSaleRequest, dict]]): + The request object. Request message for the InsertLfpSale + 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_lfp_v1beta.types.LfpSale: + A sale for the merchant. + """ + # 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, lfpsale.InsertLfpSaleRequest): + request = lfpsale.InsertLfpSaleRequest(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_lfp_sale] + + # Certain 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) -> "LfpSaleServiceAsyncClient": + 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__) + + +__all__ = ( + "LfpSaleServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/client.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/client.py new file mode 100644 index 000000000000..1865b4bb14b0 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/client.py @@ -0,0 +1,693 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +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_lfp_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 + +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 timestamp_pb2 # type: ignore +from google.shopping.merchant_lfp_v1beta.types import lfpsale +from google.shopping.type.types import types +from .transports.base import LfpSaleServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import LfpSaleServiceGrpcTransport +from .transports.grpc_asyncio import LfpSaleServiceGrpcAsyncIOTransport +from .transports.rest import LfpSaleServiceRestTransport + + +class LfpSaleServiceClientMeta(type): + """Metaclass for the LfpSaleService 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[LfpSaleServiceTransport]] + _transport_registry["grpc"] = LfpSaleServiceGrpcTransport + _transport_registry["grpc_asyncio"] = LfpSaleServiceGrpcAsyncIOTransport + _transport_registry["rest"] = LfpSaleServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[LfpSaleServiceTransport]: + """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 LfpSaleServiceClient(metaclass=LfpSaleServiceClientMeta): + """Service for a `LFP + partner `__ to + submit sales data for a merchant. + """ + + @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: + LfpSaleServiceClient: 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: + LfpSaleServiceClient: 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) -> LfpSaleServiceTransport: + """Returns the transport used by the client instance. + + Returns: + LfpSaleServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def lfp_sale_path(account: str,sale: str,) -> str: + """Returns a fully-qualified lfp_sale string.""" + return "accounts/{account}/lfpSales/{sale}".format(account=account, sale=sale, ) + + @staticmethod + def parse_lfp_sale_path(path: str) -> Dict[str,str]: + """Parses a lfp_sale path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/lfpSales/(?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 = LfpSaleServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = LfpSaleServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = LfpSaleServiceClient._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 = LfpSaleServiceClient._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 + + @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, LfpSaleServiceTransport, Callable[..., LfpSaleServiceTransport]]] = 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 sale 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,LfpSaleServiceTransport,Callable[..., LfpSaleServiceTransport]]]): + 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 LfpSaleServiceTransport 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 = LfpSaleServiceClient._read_environment_variables() + self._client_cert_source = LfpSaleServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = LfpSaleServiceClient._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, LfpSaleServiceTransport) + if transport_provided: + # transport is a LfpSaleServiceTransport 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(LfpSaleServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + LfpSaleServiceClient._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[LfpSaleServiceTransport], Callable[..., LfpSaleServiceTransport]] = ( + LfpSaleServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., LfpSaleServiceTransport], 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.lfp_v1beta.LfpSaleServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.lfp.v1beta.LfpSaleService", + "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.lfp.v1beta.LfpSaleService", + "credentialsType": None, + } + ) + + def insert_lfp_sale(self, + request: Optional[Union[lfpsale.InsertLfpSaleRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> lfpsale.LfpSale: + r"""Inserts a ``LfpSale`` 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_lfp_v1beta + + def sample_insert_lfp_sale(): + # Create a client + client = merchant_lfp_v1beta.LfpSaleServiceClient() + + # Initialize request argument(s) + lfp_sale = merchant_lfp_v1beta.LfpSale() + lfp_sale.target_account = 1491 + lfp_sale.store_code = "store_code_value" + lfp_sale.offer_id = "offer_id_value" + lfp_sale.region_code = "region_code_value" + lfp_sale.content_language = "content_language_value" + lfp_sale.gtin = "gtin_value" + lfp_sale.quantity = 895 + + request = merchant_lfp_v1beta.InsertLfpSaleRequest( + parent="parent_value", + lfp_sale=lfp_sale, + ) + + # Make the request + response = client.insert_lfp_sale(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_lfp_v1beta.types.InsertLfpSaleRequest, dict]): + The request object. Request message for the InsertLfpSale + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.shopping.merchant_lfp_v1beta.types.LfpSale: + A sale for the merchant. + """ + # 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, lfpsale.InsertLfpSaleRequest): + request = lfpsale.InsertLfpSaleRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.insert_lfp_sale] + + # Certain 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) -> "LfpSaleServiceClient": + 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__) + + +__all__ = ( + "LfpSaleServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/README.rst new file mode 100644 index 000000000000..5a2eb4c5a035 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`LfpSaleServiceTransport` is the ABC for all transports. +- public child `LfpSaleServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `LfpSaleServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseLfpSaleServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `LfpSaleServiceRestTransport` 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-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/__init__.py new file mode 100644 index 000000000000..1d8c06407377 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 LfpSaleServiceTransport +from .grpc import LfpSaleServiceGrpcTransport +from .grpc_asyncio import LfpSaleServiceGrpcAsyncIOTransport +from .rest import LfpSaleServiceRestTransport +from .rest import LfpSaleServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[LfpSaleServiceTransport]] +_transport_registry['grpc'] = LfpSaleServiceGrpcTransport +_transport_registry['grpc_asyncio'] = LfpSaleServiceGrpcAsyncIOTransport +_transport_registry['rest'] = LfpSaleServiceRestTransport + +__all__ = ( + 'LfpSaleServiceTransport', + 'LfpSaleServiceGrpcTransport', + 'LfpSaleServiceGrpcAsyncIOTransport', + 'LfpSaleServiceRestTransport', + 'LfpSaleServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/base.py new file mode 100644 index 000000000000..19ed7312d61e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/base.py @@ -0,0 +1,154 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_lfp_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 + +from google.shopping.merchant_lfp_v1beta.types import lfpsale + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class LfpSaleServiceTransport(abc.ABC): + """Abstract transport class for LfpSaleService.""" + + 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.insert_lfp_sale: gapic_v1.method.wrap_method( + self.insert_lfp_sale, + 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 insert_lfp_sale(self) -> Callable[ + [lfpsale.InsertLfpSaleRequest], + Union[ + lfpsale.LfpSale, + Awaitable[lfpsale.LfpSale] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'LfpSaleServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/grpc.py new file mode 100644 index 000000000000..db72f06dd688 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/grpc.py @@ -0,0 +1,349 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_lfp_v1beta.types import lfpsale +from .base import LfpSaleServiceTransport, 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.lfp.v1beta.LfpSaleService", + "rpcName": 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.lfp.v1beta.LfpSaleService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class LfpSaleServiceGrpcTransport(LfpSaleServiceTransport): + """gRPC backend transport for LfpSaleService. + + Service for a `LFP + partner `__ to + submit sales data for a merchant. + + This 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 insert_lfp_sale(self) -> Callable[ + [lfpsale.InsertLfpSaleRequest], + lfpsale.LfpSale]: + r"""Return a callable for the insert lfp sale method over gRPC. + + Inserts a ``LfpSale`` for the given merchant. + + Returns: + Callable[[~.InsertLfpSaleRequest], + ~.LfpSale]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_lfp_sale' not in self._stubs: + self._stubs['insert_lfp_sale'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.lfp.v1beta.LfpSaleService/InsertLfpSale', + request_serializer=lfpsale.InsertLfpSaleRequest.serialize, + response_deserializer=lfpsale.LfpSale.deserialize, + ) + return self._stubs['insert_lfp_sale'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'LfpSaleServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..90493a146911 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/grpc_asyncio.py @@ -0,0 +1,369 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_lfp_v1beta.types import lfpsale +from .base import LfpSaleServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import LfpSaleServiceGrpcTransport + +try: + from google.api_core import client_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.lfp.v1beta.LfpSaleService", + "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.lfp.v1beta.LfpSaleService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class LfpSaleServiceGrpcAsyncIOTransport(LfpSaleServiceTransport): + """gRPC AsyncIO backend transport for LfpSaleService. + + Service for a `LFP + partner `__ to + submit sales data for a merchant. + + This 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 insert_lfp_sale(self) -> Callable[ + [lfpsale.InsertLfpSaleRequest], + Awaitable[lfpsale.LfpSale]]: + r"""Return a callable for the insert lfp sale method over gRPC. + + Inserts a ``LfpSale`` for the given merchant. + + Returns: + Callable[[~.InsertLfpSaleRequest], + Awaitable[~.LfpSale]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_lfp_sale' not in self._stubs: + self._stubs['insert_lfp_sale'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.lfp.v1beta.LfpSaleService/InsertLfpSale', + request_serializer=lfpsale.InsertLfpSaleRequest.serialize, + response_deserializer=lfpsale.LfpSale.deserialize, + ) + return self._stubs['insert_lfp_sale'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.insert_lfp_sale: self._wrap_method( + self.insert_lfp_sale, + 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__ = ( + 'LfpSaleServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/rest.py new file mode 100644 index 000000000000..68c8a9d5dc68 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/rest.py @@ -0,0 +1,332 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +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_lfp_v1beta.types import lfpsale + + +from .rest_base import _BaseLfpSaleServiceRestTransport +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}", +) + + +class LfpSaleServiceRestInterceptor: + """Interceptor for LfpSaleService. + + 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 LfpSaleServiceRestTransport. + + .. code-block:: python + class MyCustomLfpSaleServiceInterceptor(LfpSaleServiceRestInterceptor): + def pre_insert_lfp_sale(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_insert_lfp_sale(self, response): + logging.log(f"Received response: {response}") + return response + + transport = LfpSaleServiceRestTransport(interceptor=MyCustomLfpSaleServiceInterceptor()) + client = LfpSaleServiceClient(transport=transport) + + + """ + def pre_insert_lfp_sale(self, request: lfpsale.InsertLfpSaleRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[lfpsale.InsertLfpSaleRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for insert_lfp_sale + + Override in a subclass to manipulate the request or metadata + before they are sent to the LfpSaleService server. + """ + return request, metadata + + def post_insert_lfp_sale(self, response: lfpsale.LfpSale) -> lfpsale.LfpSale: + """Post-rpc interceptor for insert_lfp_sale + + Override in a subclass to manipulate the response + after it is returned by the LfpSaleService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class LfpSaleServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: LfpSaleServiceRestInterceptor + + +class LfpSaleServiceRestTransport(_BaseLfpSaleServiceRestTransport): + """REST backend synchronous transport for LfpSaleService. + + Service for a `LFP + partner `__ to + submit sales data for a merchant. + + This 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[LfpSaleServiceRestInterceptor] = 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 LfpSaleServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _InsertLfpSale(_BaseLfpSaleServiceRestTransport._BaseInsertLfpSale, LfpSaleServiceRestStub): + def __hash__(self): + return hash("LfpSaleServiceRestTransport.InsertLfpSale") + + @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: lfpsale.InsertLfpSaleRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> lfpsale.LfpSale: + r"""Call the insert lfp sale method over HTTP. + + Args: + request (~.lfpsale.InsertLfpSaleRequest): + The request object. Request message for the InsertLfpSale + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.lfpsale.LfpSale: + A sale for the merchant. + """ + + http_options = _BaseLfpSaleServiceRestTransport._BaseInsertLfpSale._get_http_options() + + request, metadata = self._interceptor.pre_insert_lfp_sale(request, metadata) + transcoded_request = _BaseLfpSaleServiceRestTransport._BaseInsertLfpSale._get_transcoded_request(http_options, request) + + body = _BaseLfpSaleServiceRestTransport._BaseInsertLfpSale._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseLfpSaleServiceRestTransport._BaseInsertLfpSale._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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.lfp_v1beta.LfpSaleServiceClient.InsertLfpSale", + extra = { + "serviceName": "google.shopping.merchant.lfp.v1beta.LfpSaleService", + "rpcName": "InsertLfpSale", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = LfpSaleServiceRestTransport._InsertLfpSale._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 = lfpsale.LfpSale() + pb_resp = lfpsale.LfpSale.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_insert_lfp_sale(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = lfpsale.LfpSale.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.lfp_v1beta.LfpSaleServiceClient.insert_lfp_sale", + extra = { + "serviceName": "google.shopping.merchant.lfp.v1beta.LfpSaleService", + "rpcName": "InsertLfpSale", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def insert_lfp_sale(self) -> Callable[ + [lfpsale.InsertLfpSaleRequest], + lfpsale.LfpSale]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._InsertLfpSale(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'LfpSaleServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/rest_base.py new file mode 100644 index 000000000000..f5f597e2210e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/rest_base.py @@ -0,0 +1,138 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 LfpSaleServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.shopping.merchant_lfp_v1beta.types import lfpsale + + +class _BaseLfpSaleServiceRestTransport(LfpSaleServiceTransport): + """Base REST backend transport for LfpSaleService. + + 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 _BaseInsertLfpSale: + 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': '/lfp/v1beta/{parent=accounts/*}/lfpSales:insert', + 'body': 'lfp_sale', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = lfpsale.InsertLfpSaleRequest.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(_BaseLfpSaleServiceRestTransport._BaseInsertLfpSale._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseLfpSaleServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/__init__.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/__init__.py new file mode 100644 index 000000000000..097d5476e3d9 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 LfpStoreServiceClient +from .async_client import LfpStoreServiceAsyncClient + +__all__ = ( + 'LfpStoreServiceClient', + 'LfpStoreServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/async_client.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/async_client.py new file mode 100644 index 000000000000..9b5b71901cf3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/async_client.py @@ -0,0 +1,714 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_lfp_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 + + +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_lfp_v1beta.services.lfp_store_service import pagers +from google.shopping.merchant_lfp_v1beta.types import lfpstore +from .transports.base import LfpStoreServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import LfpStoreServiceGrpcAsyncIOTransport +from .client import LfpStoreServiceClient + +try: + from google.api_core import client_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 LfpStoreServiceAsyncClient: + """Service for a `LFP + partner `__ to + submit local stores for a merchant. + """ + + _client: LfpStoreServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = LfpStoreServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = LfpStoreServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = LfpStoreServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = LfpStoreServiceClient._DEFAULT_UNIVERSE + + lfp_store_path = staticmethod(LfpStoreServiceClient.lfp_store_path) + parse_lfp_store_path = staticmethod(LfpStoreServiceClient.parse_lfp_store_path) + common_billing_account_path = staticmethod(LfpStoreServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(LfpStoreServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(LfpStoreServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(LfpStoreServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(LfpStoreServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(LfpStoreServiceClient.parse_common_organization_path) + common_project_path = staticmethod(LfpStoreServiceClient.common_project_path) + parse_common_project_path = staticmethod(LfpStoreServiceClient.parse_common_project_path) + common_location_path = staticmethod(LfpStoreServiceClient.common_location_path) + parse_common_location_path = staticmethod(LfpStoreServiceClient.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: + LfpStoreServiceAsyncClient: The constructed client. + """ + return LfpStoreServiceClient.from_service_account_info.__func__(LfpStoreServiceAsyncClient, 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: + LfpStoreServiceAsyncClient: The constructed client. + """ + return LfpStoreServiceClient.from_service_account_file.__func__(LfpStoreServiceAsyncClient, 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 LfpStoreServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> LfpStoreServiceTransport: + """Returns the transport used by the client instance. + + Returns: + LfpStoreServiceTransport: 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 = LfpStoreServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, LfpStoreServiceTransport, Callable[..., LfpStoreServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the lfp store 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,LfpStoreServiceTransport,Callable[..., LfpStoreServiceTransport]]]): + 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 LfpStoreServiceTransport 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 = LfpStoreServiceClient( + 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.lfp_v1beta.LfpStoreServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.lfp.v1beta.LfpStoreService", + "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.lfp.v1beta.LfpStoreService", + "credentialsType": None, + } + ) + + async def get_lfp_store(self, + request: Optional[Union[lfpstore.GetLfpStoreRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> lfpstore.LfpStore: + r"""Retrieves information about a store. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_lfp_v1beta + + async def sample_get_lfp_store(): + # Create a client + client = merchant_lfp_v1beta.LfpStoreServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_lfp_v1beta.GetLfpStoreRequest( + name="name_value", + ) + + # Make the request + response = await client.get_lfp_store(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_lfp_v1beta.types.GetLfpStoreRequest, dict]]): + The request object. Request message for the ``GetLfpStore`` method. + name (:class:`str`): + Required. The name of the store to retrieve. Format: + ``accounts/{account}/lfpStores/{target_merchant}~{store_code}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.shopping.merchant_lfp_v1beta.types.LfpStore: + A store for the merchant. This will + be used to match to a store under the + Google Business Profile of the target + merchant. If a matching store can't be + found, the inventories or sales + submitted with the store code will not + be used. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lfpstore.GetLfpStoreRequest): + request = lfpstore.GetLfpStoreRequest(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_lfp_store] + + # Certain 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_lfp_store(self, + request: Optional[Union[lfpstore.InsertLfpStoreRequest, dict]] = None, + *, + parent: Optional[str] = None, + lfp_store: Optional[lfpstore.LfpStore] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> lfpstore.LfpStore: + r"""Inserts a store for the target merchant. If the store + with the same store code already exists, it will be + replaced. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_lfp_v1beta + + async def sample_insert_lfp_store(): + # Create a client + client = merchant_lfp_v1beta.LfpStoreServiceAsyncClient() + + # Initialize request argument(s) + lfp_store = merchant_lfp_v1beta.LfpStore() + lfp_store.target_account = 1491 + lfp_store.store_code = "store_code_value" + lfp_store.store_address = "store_address_value" + + request = merchant_lfp_v1beta.InsertLfpStoreRequest( + parent="parent_value", + lfp_store=lfp_store, + ) + + # Make the request + response = await client.insert_lfp_store(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_lfp_v1beta.types.InsertLfpStoreRequest, dict]]): + The request object. Request message for the + InsertLfpStore method. + parent (:class:`str`): + Required. The LFP provider account Format: + ``accounts/{account}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + lfp_store (:class:`google.shopping.merchant_lfp_v1beta.types.LfpStore`): + Required. The store to insert. + This corresponds to the ``lfp_store`` 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_lfp_v1beta.types.LfpStore: + A store for the merchant. This will + be used to match to a store under the + Google Business Profile of the target + merchant. If a matching store can't be + found, the inventories or sales + submitted with the store code will not + be used. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, lfp_store]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lfpstore.InsertLfpStoreRequest): + request = lfpstore.InsertLfpStoreRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if lfp_store is not None: + request.lfp_store = lfp_store + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.insert_lfp_store] + + # Certain 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_lfp_store(self, + request: Optional[Union[lfpstore.DeleteLfpStoreRequest, dict]] = None, + *, + name: Optional[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 store for a target 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_lfp_v1beta + + async def sample_delete_lfp_store(): + # Create a client + client = merchant_lfp_v1beta.LfpStoreServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_lfp_v1beta.DeleteLfpStoreRequest( + name="name_value", + ) + + # Make the request + await client.delete_lfp_store(request=request) + + Args: + request (Optional[Union[google.shopping.merchant_lfp_v1beta.types.DeleteLfpStoreRequest, dict]]): + The request object. Request message for the + DeleteLfpStore method. + name (:class:`str`): + Required. The name of the store to delete for the target + merchant account. Format: + ``accounts/{account}/lfpStores/{target_merchant}~{store_code}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lfpstore.DeleteLfpStoreRequest): + request = lfpstore.DeleteLfpStoreRequest(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_lfp_store] + + # Certain 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_lfp_stores(self, + request: Optional[Union[lfpstore.ListLfpStoresRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLfpStoresAsyncPager: + r"""Lists the stores of the target merchant, specified by the filter + in ``ListLfpStoresRequest``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_lfp_v1beta + + async def sample_list_lfp_stores(): + # Create a client + client = merchant_lfp_v1beta.LfpStoreServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_lfp_v1beta.ListLfpStoresRequest( + parent="parent_value", + target_account=1491, + ) + + # Make the request + page_result = client.list_lfp_stores(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_lfp_v1beta.types.ListLfpStoresRequest, dict]]): + The request object. Request message for the ListLfpStores + method. + parent (:class:`str`): + Required. The LFP partner. 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_lfp_v1beta.services.lfp_store_service.pagers.ListLfpStoresAsyncPager: + Response message for the + ListLfpStores 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lfpstore.ListLfpStoresRequest): + request = lfpstore.ListLfpStoresRequest(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_lfp_stores] + + # Certain 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.ListLfpStoresAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "LfpStoreServiceAsyncClient": + 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__) + + +__all__ = ( + "LfpStoreServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/client.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/client.py new file mode 100644 index 000000000000..c436d694f956 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/client.py @@ -0,0 +1,1046 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +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_lfp_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 + +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_lfp_v1beta.services.lfp_store_service import pagers +from google.shopping.merchant_lfp_v1beta.types import lfpstore +from .transports.base import LfpStoreServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import LfpStoreServiceGrpcTransport +from .transports.grpc_asyncio import LfpStoreServiceGrpcAsyncIOTransport +from .transports.rest import LfpStoreServiceRestTransport + + +class LfpStoreServiceClientMeta(type): + """Metaclass for the LfpStoreService 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[LfpStoreServiceTransport]] + _transport_registry["grpc"] = LfpStoreServiceGrpcTransport + _transport_registry["grpc_asyncio"] = LfpStoreServiceGrpcAsyncIOTransport + _transport_registry["rest"] = LfpStoreServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[LfpStoreServiceTransport]: + """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 LfpStoreServiceClient(metaclass=LfpStoreServiceClientMeta): + """Service for a `LFP + partner `__ to + submit local stores for a merchant. + """ + + @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: + LfpStoreServiceClient: 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: + LfpStoreServiceClient: 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) -> LfpStoreServiceTransport: + """Returns the transport used by the client instance. + + Returns: + LfpStoreServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def lfp_store_path(account: str,target_merchant: str,store_code: str,) -> str: + """Returns a fully-qualified lfp_store string.""" + return "accounts/{account}/lfpStores/{target_merchant}~{store_code}".format(account=account, target_merchant=target_merchant, store_code=store_code, ) + + @staticmethod + def parse_lfp_store_path(path: str) -> Dict[str,str]: + """Parses a lfp_store path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/lfpStores/(?P.+?)~(?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 = LfpStoreServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = LfpStoreServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = LfpStoreServiceClient._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 = LfpStoreServiceClient._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 + + @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, LfpStoreServiceTransport, Callable[..., LfpStoreServiceTransport]]] = 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 store 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,LfpStoreServiceTransport,Callable[..., LfpStoreServiceTransport]]]): + 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 LfpStoreServiceTransport 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 = LfpStoreServiceClient._read_environment_variables() + self._client_cert_source = LfpStoreServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = LfpStoreServiceClient._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, LfpStoreServiceTransport) + if transport_provided: + # transport is a LfpStoreServiceTransport 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(LfpStoreServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + LfpStoreServiceClient._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[LfpStoreServiceTransport], Callable[..., LfpStoreServiceTransport]] = ( + LfpStoreServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., LfpStoreServiceTransport], 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.lfp_v1beta.LfpStoreServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.lfp.v1beta.LfpStoreService", + "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.lfp.v1beta.LfpStoreService", + "credentialsType": None, + } + ) + + def get_lfp_store(self, + request: Optional[Union[lfpstore.GetLfpStoreRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> lfpstore.LfpStore: + r"""Retrieves information about a store. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_lfp_v1beta + + def sample_get_lfp_store(): + # Create a client + client = merchant_lfp_v1beta.LfpStoreServiceClient() + + # Initialize request argument(s) + request = merchant_lfp_v1beta.GetLfpStoreRequest( + name="name_value", + ) + + # Make the request + response = client.get_lfp_store(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_lfp_v1beta.types.GetLfpStoreRequest, dict]): + The request object. Request message for the ``GetLfpStore`` method. + name (str): + Required. The name of the store to retrieve. Format: + ``accounts/{account}/lfpStores/{target_merchant}~{store_code}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.shopping.merchant_lfp_v1beta.types.LfpStore: + A store for the merchant. This will + be used to match to a store under the + Google Business Profile of the target + merchant. If a matching store can't be + found, the inventories or sales + submitted with the store code will not + be used. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lfpstore.GetLfpStoreRequest): + request = lfpstore.GetLfpStoreRequest(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_lfp_store] + + # Certain 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_lfp_store(self, + request: Optional[Union[lfpstore.InsertLfpStoreRequest, dict]] = None, + *, + parent: Optional[str] = None, + lfp_store: Optional[lfpstore.LfpStore] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> lfpstore.LfpStore: + r"""Inserts a store for the target merchant. If the store + with the same store code already exists, it will be + replaced. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_lfp_v1beta + + def sample_insert_lfp_store(): + # Create a client + client = merchant_lfp_v1beta.LfpStoreServiceClient() + + # Initialize request argument(s) + lfp_store = merchant_lfp_v1beta.LfpStore() + lfp_store.target_account = 1491 + lfp_store.store_code = "store_code_value" + lfp_store.store_address = "store_address_value" + + request = merchant_lfp_v1beta.InsertLfpStoreRequest( + parent="parent_value", + lfp_store=lfp_store, + ) + + # Make the request + response = client.insert_lfp_store(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_lfp_v1beta.types.InsertLfpStoreRequest, dict]): + The request object. Request message for the + InsertLfpStore method. + parent (str): + Required. The LFP provider account Format: + ``accounts/{account}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + lfp_store (google.shopping.merchant_lfp_v1beta.types.LfpStore): + Required. The store to insert. + This corresponds to the ``lfp_store`` 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_lfp_v1beta.types.LfpStore: + A store for the merchant. This will + be used to match to a store under the + Google Business Profile of the target + merchant. If a matching store can't be + found, the inventories or sales + submitted with the store code will not + be used. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, lfp_store]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lfpstore.InsertLfpStoreRequest): + request = lfpstore.InsertLfpStoreRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if lfp_store is not None: + request.lfp_store = lfp_store + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.insert_lfp_store] + + # Certain 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_lfp_store(self, + request: Optional[Union[lfpstore.DeleteLfpStoreRequest, dict]] = None, + *, + name: Optional[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 store for a target 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_lfp_v1beta + + def sample_delete_lfp_store(): + # Create a client + client = merchant_lfp_v1beta.LfpStoreServiceClient() + + # Initialize request argument(s) + request = merchant_lfp_v1beta.DeleteLfpStoreRequest( + name="name_value", + ) + + # Make the request + client.delete_lfp_store(request=request) + + Args: + request (Union[google.shopping.merchant_lfp_v1beta.types.DeleteLfpStoreRequest, dict]): + The request object. Request message for the + DeleteLfpStore method. + name (str): + Required. The name of the store to delete for the target + merchant account. Format: + ``accounts/{account}/lfpStores/{target_merchant}~{store_code}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lfpstore.DeleteLfpStoreRequest): + request = lfpstore.DeleteLfpStoreRequest(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_lfp_store] + + # Certain 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_lfp_stores(self, + request: Optional[Union[lfpstore.ListLfpStoresRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLfpStoresPager: + r"""Lists the stores of the target merchant, specified by the filter + in ``ListLfpStoresRequest``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_lfp_v1beta + + def sample_list_lfp_stores(): + # Create a client + client = merchant_lfp_v1beta.LfpStoreServiceClient() + + # Initialize request argument(s) + request = merchant_lfp_v1beta.ListLfpStoresRequest( + parent="parent_value", + target_account=1491, + ) + + # Make the request + page_result = client.list_lfp_stores(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.shopping.merchant_lfp_v1beta.types.ListLfpStoresRequest, dict]): + The request object. Request message for the ListLfpStores + method. + parent (str): + Required. The LFP partner. 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_lfp_v1beta.services.lfp_store_service.pagers.ListLfpStoresPager: + Response message for the + ListLfpStores 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lfpstore.ListLfpStoresRequest): + request = lfpstore.ListLfpStoresRequest(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_lfp_stores] + + # Certain 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.ListLfpStoresPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "LfpStoreServiceClient": + 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__) + + +__all__ = ( + "LfpStoreServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/pagers.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/pagers.py new file mode 100644 index 000000000000..a7745d10afde --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/pagers.py @@ -0,0 +1,166 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_lfp_v1beta.types import lfpstore + + +class ListLfpStoresPager: + """A pager for iterating through ``list_lfp_stores`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_lfp_v1beta.types.ListLfpStoresResponse` object, and + provides an ``__iter__`` method to iterate through its + ``lfp_stores`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListLfpStores`` requests and continue to iterate + through the ``lfp_stores`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_lfp_v1beta.types.ListLfpStoresResponse` + 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[..., lfpstore.ListLfpStoresResponse], + request: lfpstore.ListLfpStoresRequest, + response: lfpstore.ListLfpStoresResponse, + *, + 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_lfp_v1beta.types.ListLfpStoresRequest): + The initial request object. + response (google.shopping.merchant_lfp_v1beta.types.ListLfpStoresResponse): + 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 = lfpstore.ListLfpStoresRequest(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[lfpstore.ListLfpStoresResponse]: + 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[lfpstore.LfpStore]: + for page in self.pages: + yield from page.lfp_stores + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListLfpStoresAsyncPager: + """A pager for iterating through ``list_lfp_stores`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_lfp_v1beta.types.ListLfpStoresResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``lfp_stores`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListLfpStores`` requests and continue to iterate + through the ``lfp_stores`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_lfp_v1beta.types.ListLfpStoresResponse` + 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[lfpstore.ListLfpStoresResponse]], + request: lfpstore.ListLfpStoresRequest, + response: lfpstore.ListLfpStoresResponse, + *, + 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_lfp_v1beta.types.ListLfpStoresRequest): + The initial request object. + response (google.shopping.merchant_lfp_v1beta.types.ListLfpStoresResponse): + 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 = lfpstore.ListLfpStoresRequest(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[lfpstore.ListLfpStoresResponse]: + 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[lfpstore.LfpStore]: + async def async_generator(): + async for page in self.pages: + for response in page.lfp_stores: + 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-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/README.rst new file mode 100644 index 000000000000..ed35abffa51e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`LfpStoreServiceTransport` is the ABC for all transports. +- public child `LfpStoreServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `LfpStoreServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseLfpStoreServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `LfpStoreServiceRestTransport` 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-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/__init__.py new file mode 100644 index 000000000000..7f93047869ee --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 LfpStoreServiceTransport +from .grpc import LfpStoreServiceGrpcTransport +from .grpc_asyncio import LfpStoreServiceGrpcAsyncIOTransport +from .rest import LfpStoreServiceRestTransport +from .rest import LfpStoreServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[LfpStoreServiceTransport]] +_transport_registry['grpc'] = LfpStoreServiceGrpcTransport +_transport_registry['grpc_asyncio'] = LfpStoreServiceGrpcAsyncIOTransport +_transport_registry['rest'] = LfpStoreServiceRestTransport + +__all__ = ( + 'LfpStoreServiceTransport', + 'LfpStoreServiceGrpcTransport', + 'LfpStoreServiceGrpcAsyncIOTransport', + 'LfpStoreServiceRestTransport', + 'LfpStoreServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/base.py new file mode 100644 index 000000000000..8aaec461f03f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/base.py @@ -0,0 +1,197 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_lfp_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 + +from google.protobuf import empty_pb2 # type: ignore +from google.shopping.merchant_lfp_v1beta.types import lfpstore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class LfpStoreServiceTransport(abc.ABC): + """Abstract transport class for LfpStoreService.""" + + 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_lfp_store: gapic_v1.method.wrap_method( + self.get_lfp_store, + default_timeout=None, + client_info=client_info, + ), + self.insert_lfp_store: gapic_v1.method.wrap_method( + self.insert_lfp_store, + default_timeout=None, + client_info=client_info, + ), + self.delete_lfp_store: gapic_v1.method.wrap_method( + self.delete_lfp_store, + default_timeout=None, + client_info=client_info, + ), + self.list_lfp_stores: gapic_v1.method.wrap_method( + self.list_lfp_stores, + 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_lfp_store(self) -> Callable[ + [lfpstore.GetLfpStoreRequest], + Union[ + lfpstore.LfpStore, + Awaitable[lfpstore.LfpStore] + ]]: + raise NotImplementedError() + + @property + def insert_lfp_store(self) -> Callable[ + [lfpstore.InsertLfpStoreRequest], + Union[ + lfpstore.LfpStore, + Awaitable[lfpstore.LfpStore] + ]]: + raise NotImplementedError() + + @property + def delete_lfp_store(self) -> Callable[ + [lfpstore.DeleteLfpStoreRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def list_lfp_stores(self) -> Callable[ + [lfpstore.ListLfpStoresRequest], + Union[ + lfpstore.ListLfpStoresResponse, + Awaitable[lfpstore.ListLfpStoresResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'LfpStoreServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/grpc.py new file mode 100644 index 000000000000..e312dd60f248 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/grpc.py @@ -0,0 +1,431 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_lfp_v1beta.types import lfpstore +from .base import LfpStoreServiceTransport, 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.lfp.v1beta.LfpStoreService", + "rpcName": 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.lfp.v1beta.LfpStoreService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class LfpStoreServiceGrpcTransport(LfpStoreServiceTransport): + """gRPC backend transport for LfpStoreService. + + Service for a `LFP + partner `__ to + submit local stores for a merchant. + + This 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_lfp_store(self) -> Callable[ + [lfpstore.GetLfpStoreRequest], + lfpstore.LfpStore]: + r"""Return a callable for the get lfp store method over gRPC. + + Retrieves information about a store. + + Returns: + Callable[[~.GetLfpStoreRequest], + ~.LfpStore]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_lfp_store' not in self._stubs: + self._stubs['get_lfp_store'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.lfp.v1beta.LfpStoreService/GetLfpStore', + request_serializer=lfpstore.GetLfpStoreRequest.serialize, + response_deserializer=lfpstore.LfpStore.deserialize, + ) + return self._stubs['get_lfp_store'] + + @property + def insert_lfp_store(self) -> Callable[ + [lfpstore.InsertLfpStoreRequest], + lfpstore.LfpStore]: + r"""Return a callable for the insert lfp store method over gRPC. + + Inserts a store for the target merchant. If the store + with the same store code already exists, it will be + replaced. + + Returns: + Callable[[~.InsertLfpStoreRequest], + ~.LfpStore]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_lfp_store' not in self._stubs: + self._stubs['insert_lfp_store'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.lfp.v1beta.LfpStoreService/InsertLfpStore', + request_serializer=lfpstore.InsertLfpStoreRequest.serialize, + response_deserializer=lfpstore.LfpStore.deserialize, + ) + return self._stubs['insert_lfp_store'] + + @property + def delete_lfp_store(self) -> Callable[ + [lfpstore.DeleteLfpStoreRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete lfp store method over gRPC. + + Deletes a store for a target merchant. + + Returns: + Callable[[~.DeleteLfpStoreRequest], + ~.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_lfp_store' not in self._stubs: + self._stubs['delete_lfp_store'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.lfp.v1beta.LfpStoreService/DeleteLfpStore', + request_serializer=lfpstore.DeleteLfpStoreRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_lfp_store'] + + @property + def list_lfp_stores(self) -> Callable[ + [lfpstore.ListLfpStoresRequest], + lfpstore.ListLfpStoresResponse]: + r"""Return a callable for the list lfp stores method over gRPC. + + Lists the stores of the target merchant, specified by the filter + in ``ListLfpStoresRequest``. + + Returns: + Callable[[~.ListLfpStoresRequest], + ~.ListLfpStoresResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_lfp_stores' not in self._stubs: + self._stubs['list_lfp_stores'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.lfp.v1beta.LfpStoreService/ListLfpStores', + request_serializer=lfpstore.ListLfpStoresRequest.serialize, + response_deserializer=lfpstore.ListLfpStoresResponse.deserialize, + ) + return self._stubs['list_lfp_stores'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'LfpStoreServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..51b43f32f4a4 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/grpc_asyncio.py @@ -0,0 +1,466 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_lfp_v1beta.types import lfpstore +from .base import LfpStoreServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import LfpStoreServiceGrpcTransport + +try: + from google.api_core import client_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.lfp.v1beta.LfpStoreService", + "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.lfp.v1beta.LfpStoreService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class LfpStoreServiceGrpcAsyncIOTransport(LfpStoreServiceTransport): + """gRPC AsyncIO backend transport for LfpStoreService. + + Service for a `LFP + partner `__ to + submit local stores for a merchant. + + This 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_lfp_store(self) -> Callable[ + [lfpstore.GetLfpStoreRequest], + Awaitable[lfpstore.LfpStore]]: + r"""Return a callable for the get lfp store method over gRPC. + + Retrieves information about a store. + + Returns: + Callable[[~.GetLfpStoreRequest], + Awaitable[~.LfpStore]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_lfp_store' not in self._stubs: + self._stubs['get_lfp_store'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.lfp.v1beta.LfpStoreService/GetLfpStore', + request_serializer=lfpstore.GetLfpStoreRequest.serialize, + response_deserializer=lfpstore.LfpStore.deserialize, + ) + return self._stubs['get_lfp_store'] + + @property + def insert_lfp_store(self) -> Callable[ + [lfpstore.InsertLfpStoreRequest], + Awaitable[lfpstore.LfpStore]]: + r"""Return a callable for the insert lfp store method over gRPC. + + Inserts a store for the target merchant. If the store + with the same store code already exists, it will be + replaced. + + Returns: + Callable[[~.InsertLfpStoreRequest], + Awaitable[~.LfpStore]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_lfp_store' not in self._stubs: + self._stubs['insert_lfp_store'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.lfp.v1beta.LfpStoreService/InsertLfpStore', + request_serializer=lfpstore.InsertLfpStoreRequest.serialize, + response_deserializer=lfpstore.LfpStore.deserialize, + ) + return self._stubs['insert_lfp_store'] + + @property + def delete_lfp_store(self) -> Callable[ + [lfpstore.DeleteLfpStoreRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete lfp store method over gRPC. + + Deletes a store for a target merchant. + + Returns: + Callable[[~.DeleteLfpStoreRequest], + 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_lfp_store' not in self._stubs: + self._stubs['delete_lfp_store'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.lfp.v1beta.LfpStoreService/DeleteLfpStore', + request_serializer=lfpstore.DeleteLfpStoreRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_lfp_store'] + + @property + def list_lfp_stores(self) -> Callable[ + [lfpstore.ListLfpStoresRequest], + Awaitable[lfpstore.ListLfpStoresResponse]]: + r"""Return a callable for the list lfp stores method over gRPC. + + Lists the stores of the target merchant, specified by the filter + in ``ListLfpStoresRequest``. + + Returns: + Callable[[~.ListLfpStoresRequest], + Awaitable[~.ListLfpStoresResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_lfp_stores' not in self._stubs: + self._stubs['list_lfp_stores'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.lfp.v1beta.LfpStoreService/ListLfpStores', + request_serializer=lfpstore.ListLfpStoresRequest.serialize, + response_deserializer=lfpstore.ListLfpStoresResponse.deserialize, + ) + return self._stubs['list_lfp_stores'] + + 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_lfp_store: self._wrap_method( + self.get_lfp_store, + default_timeout=None, + client_info=client_info, + ), + self.insert_lfp_store: self._wrap_method( + self.insert_lfp_store, + default_timeout=None, + client_info=client_info, + ), + self.delete_lfp_store: self._wrap_method( + self.delete_lfp_store, + default_timeout=None, + client_info=client_info, + ), + self.list_lfp_stores: self._wrap_method( + self.list_lfp_stores, + 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__ = ( + 'LfpStoreServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/rest.py new file mode 100644 index 000000000000..44939c1d91a7 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/rest.py @@ -0,0 +1,756 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +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_lfp_v1beta.types import lfpstore + + +from .rest_base import _BaseLfpStoreServiceRestTransport +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}", +) + + +class LfpStoreServiceRestInterceptor: + """Interceptor for LfpStoreService. + + 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 LfpStoreServiceRestTransport. + + .. code-block:: python + class MyCustomLfpStoreServiceInterceptor(LfpStoreServiceRestInterceptor): + def pre_delete_lfp_store(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_lfp_store(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_lfp_store(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_insert_lfp_store(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_insert_lfp_store(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_lfp_stores(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_lfp_stores(self, response): + logging.log(f"Received response: {response}") + return response + + transport = LfpStoreServiceRestTransport(interceptor=MyCustomLfpStoreServiceInterceptor()) + client = LfpStoreServiceClient(transport=transport) + + + """ + def pre_delete_lfp_store(self, request: lfpstore.DeleteLfpStoreRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[lfpstore.DeleteLfpStoreRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_lfp_store + + Override in a subclass to manipulate the request or metadata + before they are sent to the LfpStoreService server. + """ + return request, metadata + + def pre_get_lfp_store(self, request: lfpstore.GetLfpStoreRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[lfpstore.GetLfpStoreRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_lfp_store + + Override in a subclass to manipulate the request or metadata + before they are sent to the LfpStoreService server. + """ + return request, metadata + + def post_get_lfp_store(self, response: lfpstore.LfpStore) -> lfpstore.LfpStore: + """Post-rpc interceptor for get_lfp_store + + Override in a subclass to manipulate the response + after it is returned by the LfpStoreService server but before + it is returned to user code. + """ + return response + + def pre_insert_lfp_store(self, request: lfpstore.InsertLfpStoreRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[lfpstore.InsertLfpStoreRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for insert_lfp_store + + Override in a subclass to manipulate the request or metadata + before they are sent to the LfpStoreService server. + """ + return request, metadata + + def post_insert_lfp_store(self, response: lfpstore.LfpStore) -> lfpstore.LfpStore: + """Post-rpc interceptor for insert_lfp_store + + Override in a subclass to manipulate the response + after it is returned by the LfpStoreService server but before + it is returned to user code. + """ + return response + + def pre_list_lfp_stores(self, request: lfpstore.ListLfpStoresRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[lfpstore.ListLfpStoresRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_lfp_stores + + Override in a subclass to manipulate the request or metadata + before they are sent to the LfpStoreService server. + """ + return request, metadata + + def post_list_lfp_stores(self, response: lfpstore.ListLfpStoresResponse) -> lfpstore.ListLfpStoresResponse: + """Post-rpc interceptor for list_lfp_stores + + Override in a subclass to manipulate the response + after it is returned by the LfpStoreService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class LfpStoreServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: LfpStoreServiceRestInterceptor + + +class LfpStoreServiceRestTransport(_BaseLfpStoreServiceRestTransport): + """REST backend synchronous transport for LfpStoreService. + + Service for a `LFP + partner `__ to + submit local stores for a merchant. + + This 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[LfpStoreServiceRestInterceptor] = 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 LfpStoreServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _DeleteLfpStore(_BaseLfpStoreServiceRestTransport._BaseDeleteLfpStore, LfpStoreServiceRestStub): + def __hash__(self): + return hash("LfpStoreServiceRestTransport.DeleteLfpStore") + + @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: lfpstore.DeleteLfpStoreRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): + r"""Call the delete lfp store method over HTTP. + + Args: + request (~.lfpstore.DeleteLfpStoreRequest): + The request object. Request message for the + DeleteLfpStore method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 = _BaseLfpStoreServiceRestTransport._BaseDeleteLfpStore._get_http_options() + + request, metadata = self._interceptor.pre_delete_lfp_store(request, metadata) + transcoded_request = _BaseLfpStoreServiceRestTransport._BaseDeleteLfpStore._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseLfpStoreServiceRestTransport._BaseDeleteLfpStore._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(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.lfp_v1beta.LfpStoreServiceClient.DeleteLfpStore", + extra = { + "serviceName": "google.shopping.merchant.lfp.v1beta.LfpStoreService", + "rpcName": "DeleteLfpStore", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = LfpStoreServiceRestTransport._DeleteLfpStore._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 _GetLfpStore(_BaseLfpStoreServiceRestTransport._BaseGetLfpStore, LfpStoreServiceRestStub): + def __hash__(self): + return hash("LfpStoreServiceRestTransport.GetLfpStore") + + @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: lfpstore.GetLfpStoreRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> lfpstore.LfpStore: + r"""Call the get lfp store method over HTTP. + + Args: + request (~.lfpstore.GetLfpStoreRequest): + The request object. Request message for the ``GetLfpStore`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.lfpstore.LfpStore: + A store for the merchant. This will + be used to match to a store under the + Google Business Profile of the target + merchant. If a matching store can't be + found, the inventories or sales + submitted with the store code will not + be used. + + """ + + http_options = _BaseLfpStoreServiceRestTransport._BaseGetLfpStore._get_http_options() + + request, metadata = self._interceptor.pre_get_lfp_store(request, metadata) + transcoded_request = _BaseLfpStoreServiceRestTransport._BaseGetLfpStore._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseLfpStoreServiceRestTransport._BaseGetLfpStore._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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.lfp_v1beta.LfpStoreServiceClient.GetLfpStore", + extra = { + "serviceName": "google.shopping.merchant.lfp.v1beta.LfpStoreService", + "rpcName": "GetLfpStore", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = LfpStoreServiceRestTransport._GetLfpStore._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 = lfpstore.LfpStore() + pb_resp = lfpstore.LfpStore.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_lfp_store(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = lfpstore.LfpStore.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.lfp_v1beta.LfpStoreServiceClient.get_lfp_store", + extra = { + "serviceName": "google.shopping.merchant.lfp.v1beta.LfpStoreService", + "rpcName": "GetLfpStore", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _InsertLfpStore(_BaseLfpStoreServiceRestTransport._BaseInsertLfpStore, LfpStoreServiceRestStub): + def __hash__(self): + return hash("LfpStoreServiceRestTransport.InsertLfpStore") + + @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: lfpstore.InsertLfpStoreRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> lfpstore.LfpStore: + r"""Call the insert lfp store method over HTTP. + + Args: + request (~.lfpstore.InsertLfpStoreRequest): + The request object. Request message for the + InsertLfpStore method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.lfpstore.LfpStore: + A store for the merchant. This will + be used to match to a store under the + Google Business Profile of the target + merchant. If a matching store can't be + found, the inventories or sales + submitted with the store code will not + be used. + + """ + + http_options = _BaseLfpStoreServiceRestTransport._BaseInsertLfpStore._get_http_options() + + request, metadata = self._interceptor.pre_insert_lfp_store(request, metadata) + transcoded_request = _BaseLfpStoreServiceRestTransport._BaseInsertLfpStore._get_transcoded_request(http_options, request) + + body = _BaseLfpStoreServiceRestTransport._BaseInsertLfpStore._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseLfpStoreServiceRestTransport._BaseInsertLfpStore._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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.lfp_v1beta.LfpStoreServiceClient.InsertLfpStore", + extra = { + "serviceName": "google.shopping.merchant.lfp.v1beta.LfpStoreService", + "rpcName": "InsertLfpStore", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = LfpStoreServiceRestTransport._InsertLfpStore._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 = lfpstore.LfpStore() + pb_resp = lfpstore.LfpStore.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_insert_lfp_store(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = lfpstore.LfpStore.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.lfp_v1beta.LfpStoreServiceClient.insert_lfp_store", + extra = { + "serviceName": "google.shopping.merchant.lfp.v1beta.LfpStoreService", + "rpcName": "InsertLfpStore", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListLfpStores(_BaseLfpStoreServiceRestTransport._BaseListLfpStores, LfpStoreServiceRestStub): + def __hash__(self): + return hash("LfpStoreServiceRestTransport.ListLfpStores") + + @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: lfpstore.ListLfpStoresRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> lfpstore.ListLfpStoresResponse: + r"""Call the list lfp stores method over HTTP. + + Args: + request (~.lfpstore.ListLfpStoresRequest): + The request object. Request message for the ListLfpStores + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.lfpstore.ListLfpStoresResponse: + Response message for the + ListLfpStores method. + + """ + + http_options = _BaseLfpStoreServiceRestTransport._BaseListLfpStores._get_http_options() + + request, metadata = self._interceptor.pre_list_lfp_stores(request, metadata) + transcoded_request = _BaseLfpStoreServiceRestTransport._BaseListLfpStores._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseLfpStoreServiceRestTransport._BaseListLfpStores._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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.lfp_v1beta.LfpStoreServiceClient.ListLfpStores", + extra = { + "serviceName": "google.shopping.merchant.lfp.v1beta.LfpStoreService", + "rpcName": "ListLfpStores", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = LfpStoreServiceRestTransport._ListLfpStores._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 = lfpstore.ListLfpStoresResponse() + pb_resp = lfpstore.ListLfpStoresResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_lfp_stores(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = lfpstore.ListLfpStoresResponse.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.lfp_v1beta.LfpStoreServiceClient.list_lfp_stores", + extra = { + "serviceName": "google.shopping.merchant.lfp.v1beta.LfpStoreService", + "rpcName": "ListLfpStores", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def delete_lfp_store(self) -> Callable[ + [lfpstore.DeleteLfpStoreRequest], + 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._DeleteLfpStore(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_lfp_store(self) -> Callable[ + [lfpstore.GetLfpStoreRequest], + lfpstore.LfpStore]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetLfpStore(self._session, self._host, self._interceptor) # type: ignore + + @property + def insert_lfp_store(self) -> Callable[ + [lfpstore.InsertLfpStoreRequest], + lfpstore.LfpStore]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._InsertLfpStore(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_lfp_stores(self) -> Callable[ + [lfpstore.ListLfpStoresRequest], + lfpstore.ListLfpStoresResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListLfpStores(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'LfpStoreServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/rest_base.py new file mode 100644 index 000000000000..b685711f10d7 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/rest_base.py @@ -0,0 +1,250 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 LfpStoreServiceTransport, 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_lfp_v1beta.types import lfpstore + + +class _BaseLfpStoreServiceRestTransport(LfpStoreServiceTransport): + """Base REST backend transport for LfpStoreService. + + 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 _BaseDeleteLfpStore: + 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': '/lfp/v1beta/{name=accounts/*/lfpStores/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = lfpstore.DeleteLfpStoreRequest.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(_BaseLfpStoreServiceRestTransport._BaseDeleteLfpStore._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetLfpStore: + 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': '/lfp/v1beta/{name=accounts/*/lfpStores/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = lfpstore.GetLfpStoreRequest.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(_BaseLfpStoreServiceRestTransport._BaseGetLfpStore._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseInsertLfpStore: + 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': '/lfp/v1beta/{parent=accounts/*}/lfpStores:insert', + 'body': 'lfp_store', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = lfpstore.InsertLfpStoreRequest.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(_BaseLfpStoreServiceRestTransport._BaseInsertLfpStore._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListLfpStores: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "targetAccount" : 0, } + + @classmethod + def _get_unset_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': '/lfp/v1beta/{parent=accounts/*}/lfpStores', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = lfpstore.ListLfpStoresRequest.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(_BaseLfpStoreServiceRestTransport._BaseListLfpStores._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseLfpStoreServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/types/__init__.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/types/__init__.py new file mode 100644 index 000000000000..cf8ecc8b896a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/types/__init__.py @@ -0,0 +1,44 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .lfpinventory import ( + InsertLfpInventoryRequest, + LfpInventory, +) +from .lfpsale import ( + InsertLfpSaleRequest, + LfpSale, +) +from .lfpstore import ( + DeleteLfpStoreRequest, + GetLfpStoreRequest, + InsertLfpStoreRequest, + LfpStore, + ListLfpStoresRequest, + ListLfpStoresResponse, +) + +__all__ = ( + 'InsertLfpInventoryRequest', + 'LfpInventory', + 'InsertLfpSaleRequest', + 'LfpSale', + 'DeleteLfpStoreRequest', + 'GetLfpStoreRequest', + 'InsertLfpStoreRequest', + 'LfpStore', + 'ListLfpStoresRequest', + 'ListLfpStoresResponse', +) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/types/lfpinventory.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/types/lfpinventory.py new file mode 100644 index 000000000000..c87612bc3840 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/types/lfpinventory.py @@ -0,0 +1,200 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 timestamp_pb2 # type: ignore +from google.shopping.type.types import types + + +__protobuf__ = proto.module( + package='google.shopping.merchant.lfp.v1beta', + manifest={ + 'LfpInventory', + 'InsertLfpInventoryRequest', + }, +) + + +class LfpInventory(proto.Message): + r"""Local Inventory for the merchant. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Output only. Identifier. The name for the ``LfpInventory`` + resource. Format: + ``accounts/{account}/lfpInventories/{target_merchant}~{store_code}~{offer}`` + target_account (int): + Required. The Merchant Center ID of the + merchant to submit the inventory for. + store_code (str): + Required. The identifier of the merchant's store. Either the + store code inserted through ``InsertLfpStore`` or the store + code in the Business Profile. + offer_id (str): + Required. Immutable. A unique identifier for the product. If + both inventories and sales are submitted for a merchant, + this id should match for the same product. + + **Note**: if the merchant sells the same product new and + used, they should have different IDs. + region_code (str): + Required. The `CLDR territory + code `__ + for the country where the product is sold. + content_language (str): + Required. The two-letter ISO 639-1 language + code for the item. + gtin (str): + Optional. The Global Trade Item Number of the + product. + + This field is a member of `oneof`_ ``_gtin``. + price (google.shopping.type.types.Price): + Optional. The current price of the product. + availability (str): + Required. Availability of the product at this store. For + accepted attribute values, see the `local product inventory + data + specification `__ + quantity (int): + Optional. Quantity of the product available + at this store. Must be greater than or equal to + zero. + + This field is a member of `oneof`_ ``_quantity``. + collection_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. The time when the inventory is + collected. If not set, it will be set to the + time when the inventory is submitted. + pickup_method (str): + Optional. Supported pickup method for this offer. Unless the + value is "not supported", this field must be submitted + together with ``pickupSla``. For accepted attribute values, + see the `local product inventory data + specification `__. + + This field is a member of `oneof`_ ``_pickup_method``. + pickup_sla (str): + Optional. Expected date that an order will be ready for + pickup relative to the order date. Must be submitted + together with ``pickupMethod``. For accepted attribute + values, see the `local product inventory data + specification `__. + + This field is a member of `oneof`_ ``_pickup_sla``. + feed_label (str): + Optional. The `feed + label `__ + for the product. If this is not set, it will default to + ``regionCode``. + + This field is a member of `oneof`_ ``_feed_label``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + target_account: int = proto.Field( + proto.INT64, + number=2, + ) + store_code: str = proto.Field( + proto.STRING, + number=3, + ) + offer_id: str = proto.Field( + proto.STRING, + number=4, + ) + region_code: str = proto.Field( + proto.STRING, + number=5, + ) + content_language: str = proto.Field( + proto.STRING, + number=6, + ) + gtin: str = proto.Field( + proto.STRING, + number=7, + optional=True, + ) + price: types.Price = proto.Field( + proto.MESSAGE, + number=8, + message=types.Price, + ) + availability: str = proto.Field( + proto.STRING, + number=9, + ) + quantity: int = proto.Field( + proto.INT64, + number=10, + optional=True, + ) + collection_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=11, + message=timestamp_pb2.Timestamp, + ) + pickup_method: str = proto.Field( + proto.STRING, + number=12, + optional=True, + ) + pickup_sla: str = proto.Field( + proto.STRING, + number=13, + optional=True, + ) + feed_label: str = proto.Field( + proto.STRING, + number=14, + optional=True, + ) + + +class InsertLfpInventoryRequest(proto.Message): + r"""Request message for the ``InsertLfpInventory`` method. + + Attributes: + parent (str): + Required. The LFP provider account. Format: + ``accounts/{account}`` + lfp_inventory (google.shopping.merchant_lfp_v1beta.types.LfpInventory): + Required. The inventory to insert. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + lfp_inventory: 'LfpInventory' = proto.Field( + proto.MESSAGE, + number=2, + message='LfpInventory', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/types/lfpsale.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/types/lfpsale.py new file mode 100644 index 000000000000..765ac207bfa8 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/types/lfpsale.py @@ -0,0 +1,165 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 timestamp_pb2 # type: ignore +from google.shopping.type.types import types + + +__protobuf__ = proto.module( + package='google.shopping.merchant.lfp.v1beta', + manifest={ + 'LfpSale', + 'InsertLfpSaleRequest', + }, +) + + +class LfpSale(proto.Message): + r"""A sale for the merchant. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Output only. Identifier. The name of the ``LfpSale`` + resource. Format: ``accounts/{account}/lfpSales/{sale}`` + target_account (int): + Required. The Merchant Center ID of the + merchant to submit the sale for. + store_code (str): + Required. The identifier of the merchant's store. Either a + ``storeCode`` inserted through the API or the code of the + store in the Business Profile. + offer_id (str): + Required. A unique identifier for the product. If both + inventories and sales are submitted for a merchant, this id + should match for the same product. + + **Note**: if the merchant sells the same product new and + used, they should have different IDs. + region_code (str): + Required. The `CLDR territory + code `__ + for the country where the product is sold. + content_language (str): + Required. The two-letter ISO 639-1 language + code for the item. + gtin (str): + Required. The Global Trade Item Number of the + sold product. + price (google.shopping.type.types.Price): + Required. The unit price of the product. + quantity (int): + Required. The relative change of the + available quantity. Negative for items returned. + sale_time (google.protobuf.timestamp_pb2.Timestamp): + Required. The timestamp for the sale. + uid (str): + Output only. System generated globally unique ID for the + ``LfpSale``. + + This field is a member of `oneof`_ ``_uid``. + feed_label (str): + Optional. The `feed + label `__ + for the product. If this is not set, it will default to + ``regionCode``. + + This field is a member of `oneof`_ ``_feed_label``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + target_account: int = proto.Field( + proto.INT64, + number=2, + ) + store_code: str = proto.Field( + proto.STRING, + number=3, + ) + offer_id: str = proto.Field( + proto.STRING, + number=4, + ) + region_code: str = proto.Field( + proto.STRING, + number=5, + ) + content_language: str = proto.Field( + proto.STRING, + number=6, + ) + gtin: str = proto.Field( + proto.STRING, + number=7, + ) + price: types.Price = proto.Field( + proto.MESSAGE, + number=8, + message=types.Price, + ) + quantity: int = proto.Field( + proto.INT64, + number=9, + ) + sale_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + uid: str = proto.Field( + proto.STRING, + number=11, + optional=True, + ) + feed_label: str = proto.Field( + proto.STRING, + number=12, + optional=True, + ) + + +class InsertLfpSaleRequest(proto.Message): + r"""Request message for the InsertLfpSale method. + + Attributes: + parent (str): + Required. The LFP provider account. Format: + ``accounts/{lfp_partner}`` + lfp_sale (google.shopping.merchant_lfp_v1beta.types.LfpSale): + Required. The sale to insert. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + lfp_sale: 'LfpSale' = proto.Field( + proto.MESSAGE, + number=2, + message='LfpSale', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/types/lfpstore.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/types/lfpstore.py new file mode 100644 index 000000000000..51c5d7c21439 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/types/lfpstore.py @@ -0,0 +1,308 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.lfp.v1beta', + manifest={ + 'LfpStore', + 'GetLfpStoreRequest', + 'InsertLfpStoreRequest', + 'DeleteLfpStoreRequest', + 'ListLfpStoresRequest', + 'ListLfpStoresResponse', + }, +) + + +class LfpStore(proto.Message): + r"""A store for the merchant. This will be used to match to a + store under the Google Business Profile of the target merchant. + If a matching store can't be found, the inventories or sales + submitted with the store code will not be used. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Output only. Identifier. The name of the ``LfpStore`` + resource. Format: + ``accounts/{account}/lfpStores/{target_merchant}~{store_code}`` + target_account (int): + Required. The Merchant Center id of the + merchant to submit the store for. + store_code (str): + Required. Immutable. A store identifier that + is unique for the target merchant. + store_address (str): + Required. The street address of the store. + Example: 1600 Amphitheatre Pkwy, Mountain View, + CA 94043, USA. + store_name (str): + Optional. The merchant or store name. + + This field is a member of `oneof`_ ``_store_name``. + phone_number (str): + Optional. The store phone number in + `E.164 `__ format. + Example: ``+15556767888`` + + This field is a member of `oneof`_ ``_phone_number``. + website_uri (str): + Optional. The website URL for the store or + merchant. + + This field is a member of `oneof`_ ``_website_uri``. + gcid_category (MutableSequence[str]): + Optional. `Google My Business category + id `__. + place_id (str): + Optional. The `Google Place + Id `__ + of the store location. + + This field is a member of `oneof`_ ``_place_id``. + matching_state (google.shopping.merchant_lfp_v1beta.types.LfpStore.StoreMatchingState): + Optional. Output only. The state of matching to a Google + Business Profile. See + [matchingStateHint][google.shopping.merchant.lfp.v1beta.LfpStore.matching_state_hint] + for further details if no match is found. + matching_state_hint (str): + Optional. Output only. The hint of why the matching has + failed. This is only set when + [matchingState][google.shopping.merchant.lfp.v1beta.LfpStore.matching_state]=``STORE_MATCHING_STATE_FAILED``. + + Possible values are: + + - "``linked-store-not-found``": There aren't any Google + Business Profile stores available for matching. + - "``store-match-not-found``": The provided ``LfpStore`` + couldn't be matched to any of the connected Google + Business Profile stores. Merchant Center account is + connected correctly and stores are available on Google + Business Profile, but the ``LfpStore`` location address + does not match with Google Business Profile stores' + addresses. Update the ``LfpStore`` address or Google + Business Profile store address to match correctly. + - "``store-match-unverified``": The provided ``LfpStore`` + couldn't be matched to any of the connected Google + Business Profile stores, as the matched Google Business + Profile store is unverified. Go through the Google + Business Profile verification process to match correctly. + + This field is a member of `oneof`_ ``_matching_state_hint``. + """ + class StoreMatchingState(proto.Enum): + r"""The state of matching ``LfpStore`` to a Google Business Profile. + + Values: + STORE_MATCHING_STATE_UNSPECIFIED (0): + Store matching state unspecified. + STORE_MATCHING_STATE_MATCHED (1): + The ``LfpStore`` is successfully matched with a Google + Business Profile store. + STORE_MATCHING_STATE_FAILED (2): + The ``LfpStore`` is not matched with a Google Business + Profile store. + """ + STORE_MATCHING_STATE_UNSPECIFIED = 0 + STORE_MATCHING_STATE_MATCHED = 1 + STORE_MATCHING_STATE_FAILED = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + target_account: int = proto.Field( + proto.INT64, + number=2, + ) + store_code: str = proto.Field( + proto.STRING, + number=3, + ) + store_address: str = proto.Field( + proto.STRING, + number=4, + ) + store_name: str = proto.Field( + proto.STRING, + number=5, + optional=True, + ) + phone_number: str = proto.Field( + proto.STRING, + number=6, + optional=True, + ) + website_uri: str = proto.Field( + proto.STRING, + number=7, + optional=True, + ) + gcid_category: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=8, + ) + place_id: str = proto.Field( + proto.STRING, + number=9, + optional=True, + ) + matching_state: StoreMatchingState = proto.Field( + proto.ENUM, + number=10, + enum=StoreMatchingState, + ) + matching_state_hint: str = proto.Field( + proto.STRING, + number=11, + optional=True, + ) + + +class GetLfpStoreRequest(proto.Message): + r"""Request message for the ``GetLfpStore`` method. + + Attributes: + name (str): + Required. The name of the store to retrieve. Format: + ``accounts/{account}/lfpStores/{target_merchant}~{store_code}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class InsertLfpStoreRequest(proto.Message): + r"""Request message for the InsertLfpStore method. + + Attributes: + parent (str): + Required. The LFP provider account Format: + ``accounts/{account}`` + lfp_store (google.shopping.merchant_lfp_v1beta.types.LfpStore): + Required. The store to insert. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + lfp_store: 'LfpStore' = proto.Field( + proto.MESSAGE, + number=2, + message='LfpStore', + ) + + +class DeleteLfpStoreRequest(proto.Message): + r"""Request message for the DeleteLfpStore method. + + Attributes: + name (str): + Required. The name of the store to delete for the target + merchant account. Format: + ``accounts/{account}/lfpStores/{target_merchant}~{store_code}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListLfpStoresRequest(proto.Message): + r"""Request message for the ListLfpStores method. + + Attributes: + parent (str): + Required. The LFP partner. Format: ``accounts/{account}`` + target_account (int): + Required. The Merchant Center id of the + merchant to list stores for. + page_size (int): + Optional. The maximum number of ``LfpStore`` resources for + the given account to return. The service returns fewer than + this value if the number of stores for the given account is + less than the ``pageSize``. The default value is 250. 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 + ``ListLfpStoresRequest`` call. Provide the page token to + retrieve the subsequent page. When paginating, all other + parameters provided to ``ListLfpStoresRequest`` must match + the call that provided the page token. The token returned as + [nextPageToken][google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse.next_page_token] + in the response to the previous request. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + target_account: int = proto.Field( + proto.INT64, + number=2, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + page_token: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListLfpStoresResponse(proto.Message): + r"""Response message for the ListLfpStores method. + + Attributes: + lfp_stores (MutableSequence[google.shopping.merchant_lfp_v1beta.types.LfpStore]): + The stores from the specified merchant. + 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 + + lfp_stores: MutableSequence['LfpStore'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='LfpStore', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/mypy.ini b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/noxfile.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/noxfile.py new file mode 100644 index 000000000000..00ac360425a6 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/noxfile.py @@ -0,0 +1,280 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = 'google-shopping-merchant-lfp' + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.13" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "prerelease_deps", +] + +@nox.session(python=ALL_PYTHON) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def unit(session, protobuf_implementation): + """Run the unit test suite.""" + + 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+") + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") + + # 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") + + session.run( + 'py.test', + '--quiet', + '--cov=google/shopping/merchant_lfp_v1beta/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)), + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + +@nox.session(python=ALL_PYTHON[-1]) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def prerelease_deps(session, protobuf_implementation): + """Run the unit test suite against pre-release versions of dependencies.""" + + 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 test environment dependencies + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + + # Install the package without dependencies + session.install('-e', '.', '--no-deps') + + # We test the minimum dependency versions using the minimum Python + # version so the lowest python runtime that we test has a corresponding constraints + # file, located at `testing/constraints--.txt`, which contains all of the + # 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 + ) + ] + + session.install(*constraints_deps) + + prerel_deps = [ + "googleapis-common-protos", + "google-api-core", + "google-auth", + # Exclude grpcio!=1.67.0rc1 which does not support python 3.13 + "grpcio!=1.67.0rc1", + "grpcio-status", + "protobuf", + "proto-plus", + ] + + for dep in prerel_deps: + session.install("--pre", "--no-deps", "--upgrade", dep) + + # Remaining dependencies + other_deps = [ + "requests", + ] + session.install(*other_deps) + + # Print out prerelease package versions + + session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") + session.run("python", "-c", "import google.auth; print(google.auth.__version__)") + session.run("python", "-c", "import grpc; print(grpc.__version__)") + session.run( + "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" + ) + session.run( + "python", "-c", "import proto; print(proto.__version__)" + ) + + session.run( + 'py.test', + '--quiet', + '--cov=google/shopping/merchant_lfp_v1beta/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)), + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + + +@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=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 docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==7.0.1", "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=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", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_inventory_service_insert_lfp_inventory_async.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_inventory_service_insert_lfp_inventory_async.py new file mode 100644 index 000000000000..3deb231592ee --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_inventory_service_insert_lfp_inventory_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for InsertLfpInventory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-lfp + + +# [START merchantapi_v1beta_generated_LfpInventoryService_InsertLfpInventory_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_lfp_v1beta + + +async def sample_insert_lfp_inventory(): + # Create a client + client = merchant_lfp_v1beta.LfpInventoryServiceAsyncClient() + + # Initialize request argument(s) + lfp_inventory = merchant_lfp_v1beta.LfpInventory() + lfp_inventory.target_account = 1491 + lfp_inventory.store_code = "store_code_value" + lfp_inventory.offer_id = "offer_id_value" + lfp_inventory.region_code = "region_code_value" + lfp_inventory.content_language = "content_language_value" + lfp_inventory.availability = "availability_value" + + request = merchant_lfp_v1beta.InsertLfpInventoryRequest( + parent="parent_value", + lfp_inventory=lfp_inventory, + ) + + # Make the request + response = await client.insert_lfp_inventory(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_LfpInventoryService_InsertLfpInventory_async] diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_inventory_service_insert_lfp_inventory_sync.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_inventory_service_insert_lfp_inventory_sync.py new file mode 100644 index 000000000000..45c4a36fe2d4 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_inventory_service_insert_lfp_inventory_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for InsertLfpInventory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-lfp + + +# [START merchantapi_v1beta_generated_LfpInventoryService_InsertLfpInventory_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_lfp_v1beta + + +def sample_insert_lfp_inventory(): + # Create a client + client = merchant_lfp_v1beta.LfpInventoryServiceClient() + + # Initialize request argument(s) + lfp_inventory = merchant_lfp_v1beta.LfpInventory() + lfp_inventory.target_account = 1491 + lfp_inventory.store_code = "store_code_value" + lfp_inventory.offer_id = "offer_id_value" + lfp_inventory.region_code = "region_code_value" + lfp_inventory.content_language = "content_language_value" + lfp_inventory.availability = "availability_value" + + request = merchant_lfp_v1beta.InsertLfpInventoryRequest( + parent="parent_value", + lfp_inventory=lfp_inventory, + ) + + # Make the request + response = client.insert_lfp_inventory(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_LfpInventoryService_InsertLfpInventory_sync] diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_sale_service_insert_lfp_sale_async.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_sale_service_insert_lfp_sale_async.py new file mode 100644 index 000000000000..1837b8532da8 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_sale_service_insert_lfp_sale_async.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for InsertLfpSale +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-lfp + + +# [START merchantapi_v1beta_generated_LfpSaleService_InsertLfpSale_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_lfp_v1beta + + +async def sample_insert_lfp_sale(): + # Create a client + client = merchant_lfp_v1beta.LfpSaleServiceAsyncClient() + + # Initialize request argument(s) + lfp_sale = merchant_lfp_v1beta.LfpSale() + lfp_sale.target_account = 1491 + lfp_sale.store_code = "store_code_value" + lfp_sale.offer_id = "offer_id_value" + lfp_sale.region_code = "region_code_value" + lfp_sale.content_language = "content_language_value" + lfp_sale.gtin = "gtin_value" + lfp_sale.quantity = 895 + + request = merchant_lfp_v1beta.InsertLfpSaleRequest( + parent="parent_value", + lfp_sale=lfp_sale, + ) + + # Make the request + response = await client.insert_lfp_sale(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_LfpSaleService_InsertLfpSale_async] diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_sale_service_insert_lfp_sale_sync.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_sale_service_insert_lfp_sale_sync.py new file mode 100644 index 000000000000..663261c61a6d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_sale_service_insert_lfp_sale_sync.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for InsertLfpSale +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-lfp + + +# [START merchantapi_v1beta_generated_LfpSaleService_InsertLfpSale_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_lfp_v1beta + + +def sample_insert_lfp_sale(): + # Create a client + client = merchant_lfp_v1beta.LfpSaleServiceClient() + + # Initialize request argument(s) + lfp_sale = merchant_lfp_v1beta.LfpSale() + lfp_sale.target_account = 1491 + lfp_sale.store_code = "store_code_value" + lfp_sale.offer_id = "offer_id_value" + lfp_sale.region_code = "region_code_value" + lfp_sale.content_language = "content_language_value" + lfp_sale.gtin = "gtin_value" + lfp_sale.quantity = 895 + + request = merchant_lfp_v1beta.InsertLfpSaleRequest( + parent="parent_value", + lfp_sale=lfp_sale, + ) + + # Make the request + response = client.insert_lfp_sale(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_LfpSaleService_InsertLfpSale_sync] diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_delete_lfp_store_async.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_delete_lfp_store_async.py new file mode 100644 index 000000000000..049ac1c46d70 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_delete_lfp_store_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteLfpStore +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-lfp + + +# [START merchantapi_v1beta_generated_LfpStoreService_DeleteLfpStore_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_lfp_v1beta + + +async def sample_delete_lfp_store(): + # Create a client + client = merchant_lfp_v1beta.LfpStoreServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_lfp_v1beta.DeleteLfpStoreRequest( + name="name_value", + ) + + # Make the request + await client.delete_lfp_store(request=request) + + +# [END merchantapi_v1beta_generated_LfpStoreService_DeleteLfpStore_async] diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_delete_lfp_store_sync.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_delete_lfp_store_sync.py new file mode 100644 index 000000000000..5340c182dc2f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_delete_lfp_store_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteLfpStore +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-lfp + + +# [START merchantapi_v1beta_generated_LfpStoreService_DeleteLfpStore_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_lfp_v1beta + + +def sample_delete_lfp_store(): + # Create a client + client = merchant_lfp_v1beta.LfpStoreServiceClient() + + # Initialize request argument(s) + request = merchant_lfp_v1beta.DeleteLfpStoreRequest( + name="name_value", + ) + + # Make the request + client.delete_lfp_store(request=request) + + +# [END merchantapi_v1beta_generated_LfpStoreService_DeleteLfpStore_sync] diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_get_lfp_store_async.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_get_lfp_store_async.py new file mode 100644 index 000000000000..2ca93b570e26 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_get_lfp_store_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetLfpStore +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-lfp + + +# [START merchantapi_v1beta_generated_LfpStoreService_GetLfpStore_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_lfp_v1beta + + +async def sample_get_lfp_store(): + # Create a client + client = merchant_lfp_v1beta.LfpStoreServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_lfp_v1beta.GetLfpStoreRequest( + name="name_value", + ) + + # Make the request + response = await client.get_lfp_store(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_LfpStoreService_GetLfpStore_async] diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_get_lfp_store_sync.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_get_lfp_store_sync.py new file mode 100644 index 000000000000..6a40361b8fd6 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_get_lfp_store_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetLfpStore +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-lfp + + +# [START merchantapi_v1beta_generated_LfpStoreService_GetLfpStore_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_lfp_v1beta + + +def sample_get_lfp_store(): + # Create a client + client = merchant_lfp_v1beta.LfpStoreServiceClient() + + # Initialize request argument(s) + request = merchant_lfp_v1beta.GetLfpStoreRequest( + name="name_value", + ) + + # Make the request + response = client.get_lfp_store(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_LfpStoreService_GetLfpStore_sync] diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_insert_lfp_store_async.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_insert_lfp_store_async.py new file mode 100644 index 000000000000..2a248dcdd969 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_insert_lfp_store_async.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for InsertLfpStore +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-lfp + + +# [START merchantapi_v1beta_generated_LfpStoreService_InsertLfpStore_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_lfp_v1beta + + +async def sample_insert_lfp_store(): + # Create a client + client = merchant_lfp_v1beta.LfpStoreServiceAsyncClient() + + # Initialize request argument(s) + lfp_store = merchant_lfp_v1beta.LfpStore() + lfp_store.target_account = 1491 + lfp_store.store_code = "store_code_value" + lfp_store.store_address = "store_address_value" + + request = merchant_lfp_v1beta.InsertLfpStoreRequest( + parent="parent_value", + lfp_store=lfp_store, + ) + + # Make the request + response = await client.insert_lfp_store(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_LfpStoreService_InsertLfpStore_async] diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_insert_lfp_store_sync.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_insert_lfp_store_sync.py new file mode 100644 index 000000000000..27fed1065b46 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_insert_lfp_store_sync.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for InsertLfpStore +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-lfp + + +# [START merchantapi_v1beta_generated_LfpStoreService_InsertLfpStore_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_lfp_v1beta + + +def sample_insert_lfp_store(): + # Create a client + client = merchant_lfp_v1beta.LfpStoreServiceClient() + + # Initialize request argument(s) + lfp_store = merchant_lfp_v1beta.LfpStore() + lfp_store.target_account = 1491 + lfp_store.store_code = "store_code_value" + lfp_store.store_address = "store_address_value" + + request = merchant_lfp_v1beta.InsertLfpStoreRequest( + parent="parent_value", + lfp_store=lfp_store, + ) + + # Make the request + response = client.insert_lfp_store(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_LfpStoreService_InsertLfpStore_sync] diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_list_lfp_stores_async.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_list_lfp_stores_async.py new file mode 100644 index 000000000000..8cee2dee7524 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_list_lfp_stores_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListLfpStores +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-lfp + + +# [START merchantapi_v1beta_generated_LfpStoreService_ListLfpStores_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_lfp_v1beta + + +async def sample_list_lfp_stores(): + # Create a client + client = merchant_lfp_v1beta.LfpStoreServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_lfp_v1beta.ListLfpStoresRequest( + parent="parent_value", + target_account=1491, + ) + + # Make the request + page_result = client.list_lfp_stores(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_LfpStoreService_ListLfpStores_async] diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_list_lfp_stores_sync.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_list_lfp_stores_sync.py new file mode 100644 index 000000000000..61c063017649 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_list_lfp_stores_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListLfpStores +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-lfp + + +# [START merchantapi_v1beta_generated_LfpStoreService_ListLfpStores_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_lfp_v1beta + + +def sample_list_lfp_stores(): + # Create a client + client = merchant_lfp_v1beta.LfpStoreServiceClient() + + # Initialize request argument(s) + request = merchant_lfp_v1beta.ListLfpStoresRequest( + parent="parent_value", + target_account=1491, + ) + + # Make the request + page_result = client.list_lfp_stores(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_LfpStoreService_ListLfpStores_sync] diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.lfp.v1beta.json b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.lfp.v1beta.json new file mode 100644 index 000000000000..c88051dded42 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.lfp.v1beta.json @@ -0,0 +1,967 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.shopping.merchant.lfp.v1beta", + "version": "v1beta" + } + ], + "language": "PYTHON", + "name": "google-shopping-merchant-lfp", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_lfp_v1beta.LfpInventoryServiceAsyncClient", + "shortName": "LfpInventoryServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_lfp_v1beta.LfpInventoryServiceAsyncClient.insert_lfp_inventory", + "method": { + "fullName": "google.shopping.merchant.lfp.v1beta.LfpInventoryService.InsertLfpInventory", + "service": { + "fullName": "google.shopping.merchant.lfp.v1beta.LfpInventoryService", + "shortName": "LfpInventoryService" + }, + "shortName": "InsertLfpInventory" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_lfp_v1beta.types.InsertLfpInventoryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.shopping.merchant_lfp_v1beta.types.LfpInventory", + "shortName": "insert_lfp_inventory" + }, + "description": "Sample for InsertLfpInventory", + "file": "merchantapi_v1beta_generated_lfp_inventory_service_insert_lfp_inventory_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_LfpInventoryService_InsertLfpInventory_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 54, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 55, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_lfp_inventory_service_insert_lfp_inventory_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_lfp_v1beta.LfpInventoryServiceClient", + "shortName": "LfpInventoryServiceClient" + }, + "fullName": "google.shopping.merchant_lfp_v1beta.LfpInventoryServiceClient.insert_lfp_inventory", + "method": { + "fullName": "google.shopping.merchant.lfp.v1beta.LfpInventoryService.InsertLfpInventory", + "service": { + "fullName": "google.shopping.merchant.lfp.v1beta.LfpInventoryService", + "shortName": "LfpInventoryService" + }, + "shortName": "InsertLfpInventory" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_lfp_v1beta.types.InsertLfpInventoryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.shopping.merchant_lfp_v1beta.types.LfpInventory", + "shortName": "insert_lfp_inventory" + }, + "description": "Sample for InsertLfpInventory", + "file": "merchantapi_v1beta_generated_lfp_inventory_service_insert_lfp_inventory_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_LfpInventoryService_InsertLfpInventory_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 54, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 55, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_lfp_inventory_service_insert_lfp_inventory_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_lfp_v1beta.LfpSaleServiceAsyncClient", + "shortName": "LfpSaleServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_lfp_v1beta.LfpSaleServiceAsyncClient.insert_lfp_sale", + "method": { + "fullName": "google.shopping.merchant.lfp.v1beta.LfpSaleService.InsertLfpSale", + "service": { + "fullName": "google.shopping.merchant.lfp.v1beta.LfpSaleService", + "shortName": "LfpSaleService" + }, + "shortName": "InsertLfpSale" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_lfp_v1beta.types.InsertLfpSaleRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.shopping.merchant_lfp_v1beta.types.LfpSale", + "shortName": "insert_lfp_sale" + }, + "description": "Sample for InsertLfpSale", + "file": "merchantapi_v1beta_generated_lfp_sale_service_insert_lfp_sale_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_LfpSaleService_InsertLfpSale_async", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 55, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 56, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_lfp_sale_service_insert_lfp_sale_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_lfp_v1beta.LfpSaleServiceClient", + "shortName": "LfpSaleServiceClient" + }, + "fullName": "google.shopping.merchant_lfp_v1beta.LfpSaleServiceClient.insert_lfp_sale", + "method": { + "fullName": "google.shopping.merchant.lfp.v1beta.LfpSaleService.InsertLfpSale", + "service": { + "fullName": "google.shopping.merchant.lfp.v1beta.LfpSaleService", + "shortName": "LfpSaleService" + }, + "shortName": "InsertLfpSale" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_lfp_v1beta.types.InsertLfpSaleRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.shopping.merchant_lfp_v1beta.types.LfpSale", + "shortName": "insert_lfp_sale" + }, + "description": "Sample for InsertLfpSale", + "file": "merchantapi_v1beta_generated_lfp_sale_service_insert_lfp_sale_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_LfpSaleService_InsertLfpSale_sync", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 55, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 56, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_lfp_sale_service_insert_lfp_sale_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_lfp_v1beta.LfpStoreServiceAsyncClient", + "shortName": "LfpStoreServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_lfp_v1beta.LfpStoreServiceAsyncClient.delete_lfp_store", + "method": { + "fullName": "google.shopping.merchant.lfp.v1beta.LfpStoreService.DeleteLfpStore", + "service": { + "fullName": "google.shopping.merchant.lfp.v1beta.LfpStoreService", + "shortName": "LfpStoreService" + }, + "shortName": "DeleteLfpStore" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_lfp_v1beta.types.DeleteLfpStoreRequest" + }, + { + "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_lfp_store" + }, + "description": "Sample for DeleteLfpStore", + "file": "merchantapi_v1beta_generated_lfp_store_service_delete_lfp_store_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_LfpStoreService_DeleteLfpStore_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_lfp_store_service_delete_lfp_store_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_lfp_v1beta.LfpStoreServiceClient", + "shortName": "LfpStoreServiceClient" + }, + "fullName": "google.shopping.merchant_lfp_v1beta.LfpStoreServiceClient.delete_lfp_store", + "method": { + "fullName": "google.shopping.merchant.lfp.v1beta.LfpStoreService.DeleteLfpStore", + "service": { + "fullName": "google.shopping.merchant.lfp.v1beta.LfpStoreService", + "shortName": "LfpStoreService" + }, + "shortName": "DeleteLfpStore" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_lfp_v1beta.types.DeleteLfpStoreRequest" + }, + { + "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_lfp_store" + }, + "description": "Sample for DeleteLfpStore", + "file": "merchantapi_v1beta_generated_lfp_store_service_delete_lfp_store_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_LfpStoreService_DeleteLfpStore_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_lfp_store_service_delete_lfp_store_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_lfp_v1beta.LfpStoreServiceAsyncClient", + "shortName": "LfpStoreServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_lfp_v1beta.LfpStoreServiceAsyncClient.get_lfp_store", + "method": { + "fullName": "google.shopping.merchant.lfp.v1beta.LfpStoreService.GetLfpStore", + "service": { + "fullName": "google.shopping.merchant.lfp.v1beta.LfpStoreService", + "shortName": "LfpStoreService" + }, + "shortName": "GetLfpStore" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_lfp_v1beta.types.GetLfpStoreRequest" + }, + { + "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_lfp_v1beta.types.LfpStore", + "shortName": "get_lfp_store" + }, + "description": "Sample for GetLfpStore", + "file": "merchantapi_v1beta_generated_lfp_store_service_get_lfp_store_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_LfpStoreService_GetLfpStore_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_lfp_store_service_get_lfp_store_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_lfp_v1beta.LfpStoreServiceClient", + "shortName": "LfpStoreServiceClient" + }, + "fullName": "google.shopping.merchant_lfp_v1beta.LfpStoreServiceClient.get_lfp_store", + "method": { + "fullName": "google.shopping.merchant.lfp.v1beta.LfpStoreService.GetLfpStore", + "service": { + "fullName": "google.shopping.merchant.lfp.v1beta.LfpStoreService", + "shortName": "LfpStoreService" + }, + "shortName": "GetLfpStore" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_lfp_v1beta.types.GetLfpStoreRequest" + }, + { + "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_lfp_v1beta.types.LfpStore", + "shortName": "get_lfp_store" + }, + "description": "Sample for GetLfpStore", + "file": "merchantapi_v1beta_generated_lfp_store_service_get_lfp_store_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_LfpStoreService_GetLfpStore_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_lfp_store_service_get_lfp_store_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_lfp_v1beta.LfpStoreServiceAsyncClient", + "shortName": "LfpStoreServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_lfp_v1beta.LfpStoreServiceAsyncClient.insert_lfp_store", + "method": { + "fullName": "google.shopping.merchant.lfp.v1beta.LfpStoreService.InsertLfpStore", + "service": { + "fullName": "google.shopping.merchant.lfp.v1beta.LfpStoreService", + "shortName": "LfpStoreService" + }, + "shortName": "InsertLfpStore" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_lfp_v1beta.types.InsertLfpStoreRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "lfp_store", + "type": "google.shopping.merchant_lfp_v1beta.types.LfpStore" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.shopping.merchant_lfp_v1beta.types.LfpStore", + "shortName": "insert_lfp_store" + }, + "description": "Sample for InsertLfpStore", + "file": "merchantapi_v1beta_generated_lfp_store_service_insert_lfp_store_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_LfpStoreService_InsertLfpStore_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_lfp_store_service_insert_lfp_store_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_lfp_v1beta.LfpStoreServiceClient", + "shortName": "LfpStoreServiceClient" + }, + "fullName": "google.shopping.merchant_lfp_v1beta.LfpStoreServiceClient.insert_lfp_store", + "method": { + "fullName": "google.shopping.merchant.lfp.v1beta.LfpStoreService.InsertLfpStore", + "service": { + "fullName": "google.shopping.merchant.lfp.v1beta.LfpStoreService", + "shortName": "LfpStoreService" + }, + "shortName": "InsertLfpStore" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_lfp_v1beta.types.InsertLfpStoreRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "lfp_store", + "type": "google.shopping.merchant_lfp_v1beta.types.LfpStore" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.shopping.merchant_lfp_v1beta.types.LfpStore", + "shortName": "insert_lfp_store" + }, + "description": "Sample for InsertLfpStore", + "file": "merchantapi_v1beta_generated_lfp_store_service_insert_lfp_store_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_LfpStoreService_InsertLfpStore_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_lfp_store_service_insert_lfp_store_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_lfp_v1beta.LfpStoreServiceAsyncClient", + "shortName": "LfpStoreServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_lfp_v1beta.LfpStoreServiceAsyncClient.list_lfp_stores", + "method": { + "fullName": "google.shopping.merchant.lfp.v1beta.LfpStoreService.ListLfpStores", + "service": { + "fullName": "google.shopping.merchant.lfp.v1beta.LfpStoreService", + "shortName": "LfpStoreService" + }, + "shortName": "ListLfpStores" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_lfp_v1beta.types.ListLfpStoresRequest" + }, + { + "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_lfp_v1beta.services.lfp_store_service.pagers.ListLfpStoresAsyncPager", + "shortName": "list_lfp_stores" + }, + "description": "Sample for ListLfpStores", + "file": "merchantapi_v1beta_generated_lfp_store_service_list_lfp_stores_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_LfpStoreService_ListLfpStores_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "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": 54, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_lfp_store_service_list_lfp_stores_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_lfp_v1beta.LfpStoreServiceClient", + "shortName": "LfpStoreServiceClient" + }, + "fullName": "google.shopping.merchant_lfp_v1beta.LfpStoreServiceClient.list_lfp_stores", + "method": { + "fullName": "google.shopping.merchant.lfp.v1beta.LfpStoreService.ListLfpStores", + "service": { + "fullName": "google.shopping.merchant.lfp.v1beta.LfpStoreService", + "shortName": "LfpStoreService" + }, + "shortName": "ListLfpStores" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_lfp_v1beta.types.ListLfpStoresRequest" + }, + { + "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_lfp_v1beta.services.lfp_store_service.pagers.ListLfpStoresPager", + "shortName": "list_lfp_stores" + }, + "description": "Sample for ListLfpStores", + "file": "merchantapi_v1beta_generated_lfp_store_service_list_lfp_stores_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_LfpStoreService_ListLfpStores_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "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": 54, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_lfp_store_service_list_lfp_stores_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/scripts/fixup_merchant_lfp_v1beta_keywords.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/scripts/fixup_merchant_lfp_v1beta_keywords.py new file mode 100644 index 000000000000..f94ed4a889c2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/scripts/fixup_merchant_lfp_v1beta_keywords.py @@ -0,0 +1,181 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_lfpCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'delete_lfp_store': ('name', ), + 'get_lfp_store': ('name', ), + 'insert_lfp_inventory': ('parent', 'lfp_inventory', ), + 'insert_lfp_sale': ('parent', 'lfp_sale', ), + 'insert_lfp_store': ('parent', 'lfp_store', ), + 'list_lfp_stores': ('parent', 'target_account', 'page_size', 'page_token', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=merchant_lfpCallTransformer(), +): + """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_lfp 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-lfp/v1beta/setup.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/setup.py new file mode 100644 index 000000000000..c80b6726642d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/setup.py @@ -0,0 +1,99 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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-lfp' + + +description = "Google Shopping Merchant Lfp API client library" + +version = None + +with open(os.path.join(package_root, 'google/shopping/merchant_lfp/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.0dev,!=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.0dev,!=2.24.0,!=2.25.0", + "proto-plus >= 1.22.3, <2.0.0dev", + "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'", + "protobuf>=3.20.2,<6.0.0dev,!=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.0dev", +] +extras = { +} +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-lfp" + +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-lfp/v1beta/testing/constraints-3.10.txt b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/testing/constraints-3.10.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/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-lfp/v1beta/testing/constraints-3.11.txt b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/testing/constraints-3.11.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/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-lfp/v1beta/testing/constraints-3.12.txt b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/testing/constraints-3.12.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/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-lfp/v1beta/testing/constraints-3.13.txt b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/testing/constraints-3.13.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/testing/constraints-3.13.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-lfp/v1beta/testing/constraints-3.7.txt b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/testing/constraints-3.7.txt new file mode 100644 index 000000000000..130a0c0f80ab --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/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.0dev", +# 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-lfp/v1beta/testing/constraints-3.8.txt b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/testing/constraints-3.8.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/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-lfp/v1beta/testing/constraints-3.9.txt b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/testing/constraints-3.9.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/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-lfp/v1beta/tests/__init__.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-lfp/v1beta/tests/unit/__init__.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-lfp/v1beta/tests/unit/gapic/__init__.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-lfp/v1beta/tests/unit/gapic/merchant_lfp_v1beta/__init__.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/tests/unit/gapic/merchant_lfp_v1beta/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/tests/unit/gapic/merchant_lfp_v1beta/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-lfp/v1beta/tests/unit/gapic/merchant_lfp_v1beta/test_lfp_inventory_service.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/tests/unit/gapic/merchant_lfp_v1beta/test_lfp_inventory_service.py new file mode 100644 index 000000000000..277752435069 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/tests/unit/gapic/merchant_lfp_v1beta/test_lfp_inventory_service.py @@ -0,0 +1,2095 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable, AsyncIterable +from google.protobuf import json_format +import json +import math +import pytest +from google.api_core import api_core_version +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +try: + from google.auth.aio import credentials as ga_credentials_async + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account +from google.protobuf import timestamp_pb2 # type: ignore +from google.shopping.merchant_lfp_v1beta.services.lfp_inventory_service import LfpInventoryServiceAsyncClient +from google.shopping.merchant_lfp_v1beta.services.lfp_inventory_service import LfpInventoryServiceClient +from google.shopping.merchant_lfp_v1beta.services.lfp_inventory_service import transports +from google.shopping.merchant_lfp_v1beta.types import lfpinventory +from google.shopping.type.types import types +import google.auth + + +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 LfpInventoryServiceClient._get_default_mtls_endpoint(None) is None + assert LfpInventoryServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert LfpInventoryServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert LfpInventoryServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert LfpInventoryServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert LfpInventoryServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert LfpInventoryServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert LfpInventoryServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert LfpInventoryServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + LfpInventoryServiceClient._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 LfpInventoryServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert LfpInventoryServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert LfpInventoryServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + LfpInventoryServiceClient._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 LfpInventoryServiceClient._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 LfpInventoryServiceClient._get_client_cert_source(None, False) is None + assert LfpInventoryServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert LfpInventoryServiceClient._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 LfpInventoryServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert LfpInventoryServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(LfpInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpInventoryServiceClient)) +@mock.patch.object(LfpInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpInventoryServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = LfpInventoryServiceClient._DEFAULT_UNIVERSE + default_endpoint = LfpInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = LfpInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert LfpInventoryServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert LfpInventoryServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == LfpInventoryServiceClient.DEFAULT_MTLS_ENDPOINT + assert LfpInventoryServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert LfpInventoryServiceClient._get_api_endpoint(None, None, default_universe, "always") == LfpInventoryServiceClient.DEFAULT_MTLS_ENDPOINT + assert LfpInventoryServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == LfpInventoryServiceClient.DEFAULT_MTLS_ENDPOINT + assert LfpInventoryServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert LfpInventoryServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + LfpInventoryServiceClient._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 LfpInventoryServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert LfpInventoryServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert LfpInventoryServiceClient._get_universe_domain(None, None) == LfpInventoryServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + LfpInventoryServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize("client_class,transport_name", [ + (LfpInventoryServiceClient, "grpc"), + (LfpInventoryServiceAsyncClient, "grpc_asyncio"), + (LfpInventoryServiceClient, "rest"), +]) +def test_lfp_inventory_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'merchantapi.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://merchantapi.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.LfpInventoryServiceGrpcTransport, "grpc"), + (transports.LfpInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.LfpInventoryServiceRestTransport, "rest"), +]) +def test_lfp_inventory_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (LfpInventoryServiceClient, "grpc"), + (LfpInventoryServiceAsyncClient, "grpc_asyncio"), + (LfpInventoryServiceClient, "rest"), +]) +def test_lfp_inventory_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'merchantapi.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://merchantapi.googleapis.com' + ) + + +def test_lfp_inventory_service_client_get_transport_class(): + transport = LfpInventoryServiceClient.get_transport_class() + available_transports = [ + transports.LfpInventoryServiceGrpcTransport, + transports.LfpInventoryServiceRestTransport, + ] + assert transport in available_transports + + transport = LfpInventoryServiceClient.get_transport_class("grpc") + assert transport == transports.LfpInventoryServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (LfpInventoryServiceClient, transports.LfpInventoryServiceGrpcTransport, "grpc"), + (LfpInventoryServiceAsyncClient, transports.LfpInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (LfpInventoryServiceClient, transports.LfpInventoryServiceRestTransport, "rest"), +]) +@mock.patch.object(LfpInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpInventoryServiceClient)) +@mock.patch.object(LfpInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpInventoryServiceAsyncClient)) +def test_lfp_inventory_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(LfpInventoryServiceClient, '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(LfpInventoryServiceClient, '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", [ + (LfpInventoryServiceClient, transports.LfpInventoryServiceGrpcTransport, "grpc", "true"), + (LfpInventoryServiceAsyncClient, transports.LfpInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (LfpInventoryServiceClient, transports.LfpInventoryServiceGrpcTransport, "grpc", "false"), + (LfpInventoryServiceAsyncClient, transports.LfpInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (LfpInventoryServiceClient, transports.LfpInventoryServiceRestTransport, "rest", "true"), + (LfpInventoryServiceClient, transports.LfpInventoryServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(LfpInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpInventoryServiceClient)) +@mock.patch.object(LfpInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpInventoryServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_lfp_inventory_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + LfpInventoryServiceClient, LfpInventoryServiceAsyncClient +]) +@mock.patch.object(LfpInventoryServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LfpInventoryServiceClient)) +@mock.patch.object(LfpInventoryServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LfpInventoryServiceAsyncClient)) +def test_lfp_inventory_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + +@pytest.mark.parametrize("client_class", [ + LfpInventoryServiceClient, LfpInventoryServiceAsyncClient +]) +@mock.patch.object(LfpInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpInventoryServiceClient)) +@mock.patch.object(LfpInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpInventoryServiceAsyncClient)) +def test_lfp_inventory_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = LfpInventoryServiceClient._DEFAULT_UNIVERSE + default_endpoint = LfpInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = LfpInventoryServiceClient._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", [ + (LfpInventoryServiceClient, transports.LfpInventoryServiceGrpcTransport, "grpc"), + (LfpInventoryServiceAsyncClient, transports.LfpInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (LfpInventoryServiceClient, transports.LfpInventoryServiceRestTransport, "rest"), +]) +def test_lfp_inventory_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (LfpInventoryServiceClient, transports.LfpInventoryServiceGrpcTransport, "grpc", grpc_helpers), + (LfpInventoryServiceAsyncClient, transports.LfpInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (LfpInventoryServiceClient, transports.LfpInventoryServiceRestTransport, "rest", None), +]) +def test_lfp_inventory_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_lfp_inventory_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_lfp_v1beta.services.lfp_inventory_service.transports.LfpInventoryServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = LfpInventoryServiceClient( + 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", [ + (LfpInventoryServiceClient, transports.LfpInventoryServiceGrpcTransport, "grpc", grpc_helpers), + (LfpInventoryServiceAsyncClient, transports.LfpInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_lfp_inventory_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "merchantapi.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/content', +), + scopes=None, + default_host="merchantapi.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + lfpinventory.InsertLfpInventoryRequest, + dict, +]) +def test_insert_lfp_inventory(request_type, transport: str = 'grpc'): + client = LfpInventoryServiceClient( + 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_lfp_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lfpinventory.LfpInventory( + name='name_value', + target_account=1491, + store_code='store_code_value', + offer_id='offer_id_value', + region_code='region_code_value', + content_language='content_language_value', + gtin='gtin_value', + availability='availability_value', + quantity=895, + pickup_method='pickup_method_value', + pickup_sla='pickup_sla_value', + feed_label='feed_label_value', + ) + response = client.insert_lfp_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = lfpinventory.InsertLfpInventoryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, lfpinventory.LfpInventory) + assert response.name == 'name_value' + assert response.target_account == 1491 + assert response.store_code == 'store_code_value' + assert response.offer_id == 'offer_id_value' + assert response.region_code == 'region_code_value' + assert response.content_language == 'content_language_value' + assert response.gtin == 'gtin_value' + assert response.availability == 'availability_value' + assert response.quantity == 895 + assert response.pickup_method == 'pickup_method_value' + assert response.pickup_sla == 'pickup_sla_value' + assert response.feed_label == 'feed_label_value' + + +def test_insert_lfp_inventory_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = LfpInventoryServiceClient( + 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 = lfpinventory.InsertLfpInventoryRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_lfp_inventory), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.insert_lfp_inventory(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lfpinventory.InsertLfpInventoryRequest( + parent='parent_value', + ) + +def test_insert_lfp_inventory_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LfpInventoryServiceClient( + 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_lfp_inventory in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.insert_lfp_inventory] = mock_rpc + request = {} + client.insert_lfp_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.insert_lfp_inventory(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_insert_lfp_inventory_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = LfpInventoryServiceAsyncClient( + 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_lfp_inventory in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.insert_lfp_inventory] = mock_rpc + + request = {} + await client.insert_lfp_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.insert_lfp_inventory(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_insert_lfp_inventory_async(transport: str = 'grpc_asyncio', request_type=lfpinventory.InsertLfpInventoryRequest): + client = LfpInventoryServiceAsyncClient( + 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_lfp_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(lfpinventory.LfpInventory( + name='name_value', + target_account=1491, + store_code='store_code_value', + offer_id='offer_id_value', + region_code='region_code_value', + content_language='content_language_value', + gtin='gtin_value', + availability='availability_value', + quantity=895, + pickup_method='pickup_method_value', + pickup_sla='pickup_sla_value', + feed_label='feed_label_value', + )) + response = await client.insert_lfp_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = lfpinventory.InsertLfpInventoryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, lfpinventory.LfpInventory) + assert response.name == 'name_value' + assert response.target_account == 1491 + assert response.store_code == 'store_code_value' + assert response.offer_id == 'offer_id_value' + assert response.region_code == 'region_code_value' + assert response.content_language == 'content_language_value' + assert response.gtin == 'gtin_value' + assert response.availability == 'availability_value' + assert response.quantity == 895 + assert response.pickup_method == 'pickup_method_value' + assert response.pickup_sla == 'pickup_sla_value' + assert response.feed_label == 'feed_label_value' + + +@pytest.mark.asyncio +async def test_insert_lfp_inventory_async_from_dict(): + await test_insert_lfp_inventory_async(request_type=dict) + +def test_insert_lfp_inventory_field_headers(): + client = LfpInventoryServiceClient( + 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 = lfpinventory.InsertLfpInventoryRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_lfp_inventory), + '__call__') as call: + call.return_value = lfpinventory.LfpInventory() + client.insert_lfp_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_insert_lfp_inventory_field_headers_async(): + client = LfpInventoryServiceAsyncClient( + 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 = lfpinventory.InsertLfpInventoryRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_lfp_inventory), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpinventory.LfpInventory()) + await client.insert_lfp_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_insert_lfp_inventory_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LfpInventoryServiceClient( + 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_lfp_inventory in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.insert_lfp_inventory] = mock_rpc + + request = {} + client.insert_lfp_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.insert_lfp_inventory(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_insert_lfp_inventory_rest_required_fields(request_type=lfpinventory.InsertLfpInventoryRequest): + transport_class = transports.LfpInventoryServiceRestTransport + + 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_lfp_inventory._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).insert_lfp_inventory._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = LfpInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = lfpinventory.LfpInventory() + # 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 = lfpinventory.LfpInventory.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_lfp_inventory(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_insert_lfp_inventory_rest_unset_required_fields(): + transport = transports.LfpInventoryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.insert_lfp_inventory._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "lfpInventory", ))) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.LfpInventoryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LfpInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.LfpInventoryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LfpInventoryServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.LfpInventoryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = LfpInventoryServiceClient( + 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 = LfpInventoryServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.LfpInventoryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LfpInventoryServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.LfpInventoryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = LfpInventoryServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.LfpInventoryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.LfpInventoryServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.LfpInventoryServiceGrpcTransport, + transports.LfpInventoryServiceGrpcAsyncIOTransport, + transports.LfpInventoryServiceRestTransport, +]) +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 = LfpInventoryServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = LfpInventoryServiceClient( + 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_insert_lfp_inventory_empty_call_grpc(): + client = LfpInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.insert_lfp_inventory), + '__call__') as call: + call.return_value = lfpinventory.LfpInventory() + client.insert_lfp_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = lfpinventory.InsertLfpInventoryRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = LfpInventoryServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = LfpInventoryServiceAsyncClient( + 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_insert_lfp_inventory_empty_call_grpc_asyncio(): + client = LfpInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.insert_lfp_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpinventory.LfpInventory( + name='name_value', + target_account=1491, + store_code='store_code_value', + offer_id='offer_id_value', + region_code='region_code_value', + content_language='content_language_value', + gtin='gtin_value', + availability='availability_value', + quantity=895, + pickup_method='pickup_method_value', + pickup_sla='pickup_sla_value', + feed_label='feed_label_value', + )) + await client.insert_lfp_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = lfpinventory.InsertLfpInventoryRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = LfpInventoryServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_insert_lfp_inventory_rest_bad_request(request_type=lfpinventory.InsertLfpInventoryRequest): + client = LfpInventoryServiceClient( + 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_lfp_inventory(request) + + +@pytest.mark.parametrize("request_type", [ + lfpinventory.InsertLfpInventoryRequest, + dict, +]) +def test_insert_lfp_inventory_rest_call_success(request_type): + client = LfpInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + request_init["lfp_inventory"] = {'name': 'name_value', 'target_account': 1491, 'store_code': 'store_code_value', 'offer_id': 'offer_id_value', 'region_code': 'region_code_value', 'content_language': 'content_language_value', 'gtin': 'gtin_value', 'price': {'amount_micros': 1408, 'currency_code': 'currency_code_value'}, 'availability': 'availability_value', 'quantity': 895, 'collection_time': {'seconds': 751, 'nanos': 543}, 'pickup_method': 'pickup_method_value', 'pickup_sla': 'pickup_sla_value', 'feed_label': 'feed_label_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 = lfpinventory.InsertLfpInventoryRequest.meta.fields["lfp_inventory"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["lfp_inventory"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["lfp_inventory"][field])): + del request_init["lfp_inventory"][field][i][subfield] + else: + del request_init["lfp_inventory"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = lfpinventory.LfpInventory( + name='name_value', + target_account=1491, + store_code='store_code_value', + offer_id='offer_id_value', + region_code='region_code_value', + content_language='content_language_value', + gtin='gtin_value', + availability='availability_value', + quantity=895, + pickup_method='pickup_method_value', + pickup_sla='pickup_sla_value', + feed_label='feed_label_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 = lfpinventory.LfpInventory.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_lfp_inventory(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, lfpinventory.LfpInventory) + assert response.name == 'name_value' + assert response.target_account == 1491 + assert response.store_code == 'store_code_value' + assert response.offer_id == 'offer_id_value' + assert response.region_code == 'region_code_value' + assert response.content_language == 'content_language_value' + assert response.gtin == 'gtin_value' + assert response.availability == 'availability_value' + assert response.quantity == 895 + assert response.pickup_method == 'pickup_method_value' + assert response.pickup_sla == 'pickup_sla_value' + assert response.feed_label == 'feed_label_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_insert_lfp_inventory_rest_interceptors(null_interceptor): + transport = transports.LfpInventoryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LfpInventoryServiceRestInterceptor(), + ) + client = LfpInventoryServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.LfpInventoryServiceRestInterceptor, "post_insert_lfp_inventory") as post, \ + mock.patch.object(transports.LfpInventoryServiceRestInterceptor, "pre_insert_lfp_inventory") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = lfpinventory.InsertLfpInventoryRequest.pb(lfpinventory.InsertLfpInventoryRequest()) + 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 = lfpinventory.LfpInventory.to_json(lfpinventory.LfpInventory()) + req.return_value.content = return_value + + request = lfpinventory.InsertLfpInventoryRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = lfpinventory.LfpInventory() + + client.insert_lfp_inventory(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + +def test_initialize_client_w_rest(): + client = LfpInventoryServiceClient( + 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_insert_lfp_inventory_empty_call_rest(): + client = LfpInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.insert_lfp_inventory), + '__call__') as call: + client.insert_lfp_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = lfpinventory.InsertLfpInventoryRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = LfpInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.LfpInventoryServiceGrpcTransport, + ) + +def test_lfp_inventory_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.LfpInventoryServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_lfp_inventory_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_lfp_v1beta.services.lfp_inventory_service.transports.LfpInventoryServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.LfpInventoryServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'insert_lfp_inventory', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_lfp_inventory_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.shopping.merchant_lfp_v1beta.services.lfp_inventory_service.transports.LfpInventoryServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.LfpInventoryServiceTransport( + 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_inventory_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.shopping.merchant_lfp_v1beta.services.lfp_inventory_service.transports.LfpInventoryServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.LfpInventoryServiceTransport() + adc.assert_called_once() + + +def test_lfp_inventory_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + LfpInventoryServiceClient() + 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.LfpInventoryServiceGrpcTransport, + transports.LfpInventoryServiceGrpcAsyncIOTransport, + ], +) +def test_lfp_inventory_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/content',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.LfpInventoryServiceGrpcTransport, + transports.LfpInventoryServiceGrpcAsyncIOTransport, + transports.LfpInventoryServiceRestTransport, + ], +) +def test_lfp_inventory_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.LfpInventoryServiceGrpcTransport, grpc_helpers), + (transports.LfpInventoryServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_lfp_inventory_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "merchantapi.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/content', +), + scopes=["1", "2"], + default_host="merchantapi.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.LfpInventoryServiceGrpcTransport, transports.LfpInventoryServiceGrpcAsyncIOTransport]) +def test_lfp_inventory_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + +def test_lfp_inventory_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.LfpInventoryServiceRestTransport ( + 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_inventory_service_host_no_port(transport_name): + client = LfpInventoryServiceClient( + 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_inventory_service_host_with_port(transport_name): + client = LfpInventoryServiceClient( + 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_inventory_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = LfpInventoryServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = LfpInventoryServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.insert_lfp_inventory._session + session2 = client2.transport.insert_lfp_inventory._session + assert session1 != session2 +def test_lfp_inventory_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.LfpInventoryServiceGrpcTransport( + 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_inventory_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.LfpInventoryServiceGrpcAsyncIOTransport( + 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.LfpInventoryServiceGrpcTransport, transports.LfpInventoryServiceGrpcAsyncIOTransport]) +def test_lfp_inventory_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.LfpInventoryServiceGrpcTransport, transports.LfpInventoryServiceGrpcAsyncIOTransport]) +def test_lfp_inventory_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_lfp_inventory_path(): + account = "squid" + target_merchant = "clam" + store_code = "whelk" + offer = "octopus" + expected = "accounts/{account}/lfpInventories/{target_merchant}~{store_code}~{offer}".format(account=account, target_merchant=target_merchant, store_code=store_code, offer=offer, ) + actual = LfpInventoryServiceClient.lfp_inventory_path(account, target_merchant, store_code, offer) + assert expected == actual + + +def test_parse_lfp_inventory_path(): + expected = { + "account": "oyster", + "target_merchant": "nudibranch", + "store_code": "cuttlefish", + "offer": "mussel", + } + path = LfpInventoryServiceClient.lfp_inventory_path(**expected) + + # Check that the path construction is reversible. + actual = LfpInventoryServiceClient.parse_lfp_inventory_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "winkle" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = LfpInventoryServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = LfpInventoryServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = LfpInventoryServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format(folder=folder, ) + actual = LfpInventoryServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = LfpInventoryServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = LfpInventoryServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format(organization=organization, ) + actual = LfpInventoryServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = LfpInventoryServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = LfpInventoryServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format(project=project, ) + actual = LfpInventoryServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = LfpInventoryServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = LfpInventoryServiceClient.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 = LfpInventoryServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = LfpInventoryServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = LfpInventoryServiceClient.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.LfpInventoryServiceTransport, '_prep_wrapped_messages') as prep: + client = LfpInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.LfpInventoryServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = LfpInventoryServiceClient.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 = LfpInventoryServiceClient( + 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 = LfpInventoryServiceAsyncClient( + 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 = LfpInventoryServiceClient( + 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 = LfpInventoryServiceClient( + 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", [ + (LfpInventoryServiceClient, transports.LfpInventoryServiceGrpcTransport), + (LfpInventoryServiceAsyncClient, transports.LfpInventoryServiceGrpcAsyncIOTransport), +]) +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-lfp/v1beta/tests/unit/gapic/merchant_lfp_v1beta/test_lfp_sale_service.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/tests/unit/gapic/merchant_lfp_v1beta/test_lfp_sale_service.py new file mode 100644 index 000000000000..974dfbcc725f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/tests/unit/gapic/merchant_lfp_v1beta/test_lfp_sale_service.py @@ -0,0 +1,2077 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable, AsyncIterable +from google.protobuf import json_format +import json +import math +import pytest +from google.api_core import api_core_version +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +try: + from google.auth.aio import credentials as ga_credentials_async + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account +from google.protobuf import timestamp_pb2 # type: ignore +from google.shopping.merchant_lfp_v1beta.services.lfp_sale_service import LfpSaleServiceAsyncClient +from google.shopping.merchant_lfp_v1beta.services.lfp_sale_service import LfpSaleServiceClient +from google.shopping.merchant_lfp_v1beta.services.lfp_sale_service import transports +from google.shopping.merchant_lfp_v1beta.types import lfpsale +from google.shopping.type.types import types +import google.auth + + +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 LfpSaleServiceClient._get_default_mtls_endpoint(None) is None + assert LfpSaleServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert LfpSaleServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert LfpSaleServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert LfpSaleServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert LfpSaleServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert LfpSaleServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert LfpSaleServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert LfpSaleServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + LfpSaleServiceClient._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 LfpSaleServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert LfpSaleServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert LfpSaleServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + LfpSaleServiceClient._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 LfpSaleServiceClient._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 LfpSaleServiceClient._get_client_cert_source(None, False) is None + assert LfpSaleServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert LfpSaleServiceClient._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 LfpSaleServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert LfpSaleServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(LfpSaleServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpSaleServiceClient)) +@mock.patch.object(LfpSaleServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpSaleServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = LfpSaleServiceClient._DEFAULT_UNIVERSE + default_endpoint = LfpSaleServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = LfpSaleServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert LfpSaleServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert LfpSaleServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == LfpSaleServiceClient.DEFAULT_MTLS_ENDPOINT + assert LfpSaleServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert LfpSaleServiceClient._get_api_endpoint(None, None, default_universe, "always") == LfpSaleServiceClient.DEFAULT_MTLS_ENDPOINT + assert LfpSaleServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == LfpSaleServiceClient.DEFAULT_MTLS_ENDPOINT + assert LfpSaleServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert LfpSaleServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + LfpSaleServiceClient._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 LfpSaleServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert LfpSaleServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert LfpSaleServiceClient._get_universe_domain(None, None) == LfpSaleServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + LfpSaleServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize("client_class,transport_name", [ + (LfpSaleServiceClient, "grpc"), + (LfpSaleServiceAsyncClient, "grpc_asyncio"), + (LfpSaleServiceClient, "rest"), +]) +def test_lfp_sale_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.LfpSaleServiceGrpcTransport, "grpc"), + (transports.LfpSaleServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.LfpSaleServiceRestTransport, "rest"), +]) +def test_lfp_sale_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", [ + (LfpSaleServiceClient, "grpc"), + (LfpSaleServiceAsyncClient, "grpc_asyncio"), + (LfpSaleServiceClient, "rest"), +]) +def test_lfp_sale_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_sale_service_client_get_transport_class(): + transport = LfpSaleServiceClient.get_transport_class() + available_transports = [ + transports.LfpSaleServiceGrpcTransport, + transports.LfpSaleServiceRestTransport, + ] + assert transport in available_transports + + transport = LfpSaleServiceClient.get_transport_class("grpc") + assert transport == transports.LfpSaleServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (LfpSaleServiceClient, transports.LfpSaleServiceGrpcTransport, "grpc"), + (LfpSaleServiceAsyncClient, transports.LfpSaleServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (LfpSaleServiceClient, transports.LfpSaleServiceRestTransport, "rest"), +]) +@mock.patch.object(LfpSaleServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpSaleServiceClient)) +@mock.patch.object(LfpSaleServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpSaleServiceAsyncClient)) +def test_lfp_sale_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(LfpSaleServiceClient, '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(LfpSaleServiceClient, '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", [ + (LfpSaleServiceClient, transports.LfpSaleServiceGrpcTransport, "grpc", "true"), + (LfpSaleServiceAsyncClient, transports.LfpSaleServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (LfpSaleServiceClient, transports.LfpSaleServiceGrpcTransport, "grpc", "false"), + (LfpSaleServiceAsyncClient, transports.LfpSaleServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (LfpSaleServiceClient, transports.LfpSaleServiceRestTransport, "rest", "true"), + (LfpSaleServiceClient, transports.LfpSaleServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(LfpSaleServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpSaleServiceClient)) +@mock.patch.object(LfpSaleServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpSaleServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_lfp_sale_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", [ + LfpSaleServiceClient, LfpSaleServiceAsyncClient +]) +@mock.patch.object(LfpSaleServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LfpSaleServiceClient)) +@mock.patch.object(LfpSaleServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LfpSaleServiceAsyncClient)) +def test_lfp_sale_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", [ + LfpSaleServiceClient, LfpSaleServiceAsyncClient +]) +@mock.patch.object(LfpSaleServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpSaleServiceClient)) +@mock.patch.object(LfpSaleServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpSaleServiceAsyncClient)) +def test_lfp_sale_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = LfpSaleServiceClient._DEFAULT_UNIVERSE + default_endpoint = LfpSaleServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = LfpSaleServiceClient._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", [ + (LfpSaleServiceClient, transports.LfpSaleServiceGrpcTransport, "grpc"), + (LfpSaleServiceAsyncClient, transports.LfpSaleServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (LfpSaleServiceClient, transports.LfpSaleServiceRestTransport, "rest"), +]) +def test_lfp_sale_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", [ + (LfpSaleServiceClient, transports.LfpSaleServiceGrpcTransport, "grpc", grpc_helpers), + (LfpSaleServiceAsyncClient, transports.LfpSaleServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (LfpSaleServiceClient, transports.LfpSaleServiceRestTransport, "rest", None), +]) +def test_lfp_sale_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_sale_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_lfp_v1beta.services.lfp_sale_service.transports.LfpSaleServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = LfpSaleServiceClient( + 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", [ + (LfpSaleServiceClient, transports.LfpSaleServiceGrpcTransport, "grpc", grpc_helpers), + (LfpSaleServiceAsyncClient, transports.LfpSaleServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_lfp_sale_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", [ + lfpsale.InsertLfpSaleRequest, + dict, +]) +def test_insert_lfp_sale(request_type, transport: str = 'grpc'): + client = LfpSaleServiceClient( + 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_lfp_sale), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lfpsale.LfpSale( + name='name_value', + target_account=1491, + store_code='store_code_value', + offer_id='offer_id_value', + region_code='region_code_value', + content_language='content_language_value', + gtin='gtin_value', + quantity=895, + uid='uid_value', + feed_label='feed_label_value', + ) + response = client.insert_lfp_sale(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = lfpsale.InsertLfpSaleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, lfpsale.LfpSale) + assert response.name == 'name_value' + assert response.target_account == 1491 + assert response.store_code == 'store_code_value' + assert response.offer_id == 'offer_id_value' + assert response.region_code == 'region_code_value' + assert response.content_language == 'content_language_value' + assert response.gtin == 'gtin_value' + assert response.quantity == 895 + assert response.uid == 'uid_value' + assert response.feed_label == 'feed_label_value' + + +def test_insert_lfp_sale_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 = LfpSaleServiceClient( + 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 = lfpsale.InsertLfpSaleRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_lfp_sale), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.insert_lfp_sale(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lfpsale.InsertLfpSaleRequest( + parent='parent_value', + ) + +def test_insert_lfp_sale_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LfpSaleServiceClient( + 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_lfp_sale in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_lfp_sale] = mock_rpc + request = {} + client.insert_lfp_sale(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.insert_lfp_sale(request) + + # Establish that a new wrapper 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_lfp_sale_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = LfpSaleServiceAsyncClient( + 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_lfp_sale in client._client._transport._wrapped_methods + + # 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_lfp_sale] = mock_rpc + + request = {} + await client.insert_lfp_sale(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.insert_lfp_sale(request) + + # Establish that a new wrapper 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_lfp_sale_async(transport: str = 'grpc_asyncio', request_type=lfpsale.InsertLfpSaleRequest): + client = LfpSaleServiceAsyncClient( + 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_lfp_sale), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(lfpsale.LfpSale( + name='name_value', + target_account=1491, + store_code='store_code_value', + offer_id='offer_id_value', + region_code='region_code_value', + content_language='content_language_value', + gtin='gtin_value', + quantity=895, + uid='uid_value', + feed_label='feed_label_value', + )) + response = await client.insert_lfp_sale(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = lfpsale.InsertLfpSaleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, lfpsale.LfpSale) + assert response.name == 'name_value' + assert response.target_account == 1491 + assert response.store_code == 'store_code_value' + assert response.offer_id == 'offer_id_value' + assert response.region_code == 'region_code_value' + assert response.content_language == 'content_language_value' + assert response.gtin == 'gtin_value' + assert response.quantity == 895 + assert response.uid == 'uid_value' + assert response.feed_label == 'feed_label_value' + + +@pytest.mark.asyncio +async def test_insert_lfp_sale_async_from_dict(): + await test_insert_lfp_sale_async(request_type=dict) + +def test_insert_lfp_sale_field_headers(): + client = LfpSaleServiceClient( + 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 = lfpsale.InsertLfpSaleRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_lfp_sale), + '__call__') as call: + call.return_value = lfpsale.LfpSale() + client.insert_lfp_sale(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_lfp_sale_field_headers_async(): + client = LfpSaleServiceAsyncClient( + 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 = lfpsale.InsertLfpSaleRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_lfp_sale), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpsale.LfpSale()) + await client.insert_lfp_sale(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_insert_lfp_sale_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 = LfpSaleServiceClient( + 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_lfp_sale in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_lfp_sale] = mock_rpc + + request = {} + client.insert_lfp_sale(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.insert_lfp_sale(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_lfp_sale_rest_required_fields(request_type=lfpsale.InsertLfpSaleRequest): + transport_class = transports.LfpSaleServiceRestTransport + + 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_lfp_sale._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_lfp_sale._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 = LfpSaleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = lfpsale.LfpSale() + # 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 = lfpsale.LfpSale.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_lfp_sale(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_insert_lfp_sale_rest_unset_required_fields(): + transport = transports.LfpSaleServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.insert_lfp_sale._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "lfpSale", ))) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.LfpSaleServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LfpSaleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.LfpSaleServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LfpSaleServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.LfpSaleServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = LfpSaleServiceClient( + 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 = LfpSaleServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.LfpSaleServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LfpSaleServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.LfpSaleServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = LfpSaleServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.LfpSaleServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.LfpSaleServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.LfpSaleServiceGrpcTransport, + transports.LfpSaleServiceGrpcAsyncIOTransport, + transports.LfpSaleServiceRestTransport, +]) +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 = LfpSaleServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = LfpSaleServiceClient( + 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_insert_lfp_sale_empty_call_grpc(): + client = LfpSaleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.insert_lfp_sale), + '__call__') as call: + call.return_value = lfpsale.LfpSale() + client.insert_lfp_sale(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = lfpsale.InsertLfpSaleRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = LfpSaleServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = LfpSaleServiceAsyncClient( + 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_insert_lfp_sale_empty_call_grpc_asyncio(): + client = LfpSaleServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.insert_lfp_sale), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpsale.LfpSale( + name='name_value', + target_account=1491, + store_code='store_code_value', + offer_id='offer_id_value', + region_code='region_code_value', + content_language='content_language_value', + gtin='gtin_value', + quantity=895, + uid='uid_value', + feed_label='feed_label_value', + )) + await client.insert_lfp_sale(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = lfpsale.InsertLfpSaleRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = LfpSaleServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_insert_lfp_sale_rest_bad_request(request_type=lfpsale.InsertLfpSaleRequest): + client = LfpSaleServiceClient( + 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_lfp_sale(request) + + +@pytest.mark.parametrize("request_type", [ + lfpsale.InsertLfpSaleRequest, + dict, +]) +def test_insert_lfp_sale_rest_call_success(request_type): + client = LfpSaleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + request_init["lfp_sale"] = {'name': 'name_value', 'target_account': 1491, 'store_code': 'store_code_value', 'offer_id': 'offer_id_value', 'region_code': 'region_code_value', 'content_language': 'content_language_value', 'gtin': 'gtin_value', 'price': {'amount_micros': 1408, 'currency_code': 'currency_code_value'}, 'quantity': 895, 'sale_time': {'seconds': 751, 'nanos': 543}, 'uid': 'uid_value', 'feed_label': 'feed_label_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 = lfpsale.InsertLfpSaleRequest.meta.fields["lfp_sale"] + + 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["lfp_sale"].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["lfp_sale"][field])): + del request_init["lfp_sale"][field][i][subfield] + else: + del request_init["lfp_sale"][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 = lfpsale.LfpSale( + name='name_value', + target_account=1491, + store_code='store_code_value', + offer_id='offer_id_value', + region_code='region_code_value', + content_language='content_language_value', + gtin='gtin_value', + quantity=895, + uid='uid_value', + feed_label='feed_label_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 = lfpsale.LfpSale.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_lfp_sale(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, lfpsale.LfpSale) + assert response.name == 'name_value' + assert response.target_account == 1491 + assert response.store_code == 'store_code_value' + assert response.offer_id == 'offer_id_value' + assert response.region_code == 'region_code_value' + assert response.content_language == 'content_language_value' + assert response.gtin == 'gtin_value' + assert response.quantity == 895 + assert response.uid == 'uid_value' + assert response.feed_label == 'feed_label_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_insert_lfp_sale_rest_interceptors(null_interceptor): + transport = transports.LfpSaleServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LfpSaleServiceRestInterceptor(), + ) + client = LfpSaleServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.LfpSaleServiceRestInterceptor, "post_insert_lfp_sale") as post, \ + mock.patch.object(transports.LfpSaleServiceRestInterceptor, "pre_insert_lfp_sale") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = lfpsale.InsertLfpSaleRequest.pb(lfpsale.InsertLfpSaleRequest()) + 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 = lfpsale.LfpSale.to_json(lfpsale.LfpSale()) + req.return_value.content = return_value + + request = lfpsale.InsertLfpSaleRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = lfpsale.LfpSale() + + client.insert_lfp_sale(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + +def test_initialize_client_w_rest(): + client = LfpSaleServiceClient( + 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_insert_lfp_sale_empty_call_rest(): + client = LfpSaleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.insert_lfp_sale), + '__call__') as call: + client.insert_lfp_sale(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = lfpsale.InsertLfpSaleRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = LfpSaleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.LfpSaleServiceGrpcTransport, + ) + +def test_lfp_sale_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.LfpSaleServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_lfp_sale_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_lfp_v1beta.services.lfp_sale_service.transports.LfpSaleServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.LfpSaleServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'insert_lfp_sale', + ) + 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_sale_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_lfp_v1beta.services.lfp_sale_service.transports.LfpSaleServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.LfpSaleServiceTransport( + 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_sale_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_lfp_v1beta.services.lfp_sale_service.transports.LfpSaleServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.LfpSaleServiceTransport() + adc.assert_called_once() + + +def test_lfp_sale_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) + LfpSaleServiceClient() + 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.LfpSaleServiceGrpcTransport, + transports.LfpSaleServiceGrpcAsyncIOTransport, + ], +) +def test_lfp_sale_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.LfpSaleServiceGrpcTransport, + transports.LfpSaleServiceGrpcAsyncIOTransport, + transports.LfpSaleServiceRestTransport, + ], +) +def test_lfp_sale_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.LfpSaleServiceGrpcTransport, grpc_helpers), + (transports.LfpSaleServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_lfp_sale_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.LfpSaleServiceGrpcTransport, transports.LfpSaleServiceGrpcAsyncIOTransport]) +def test_lfp_sale_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_sale_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.LfpSaleServiceRestTransport ( + 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_sale_service_host_no_port(transport_name): + client = LfpSaleServiceClient( + 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_sale_service_host_with_port(transport_name): + client = LfpSaleServiceClient( + 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_sale_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = LfpSaleServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = LfpSaleServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.insert_lfp_sale._session + session2 = client2.transport.insert_lfp_sale._session + assert session1 != session2 +def test_lfp_sale_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.LfpSaleServiceGrpcTransport( + 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_sale_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.LfpSaleServiceGrpcAsyncIOTransport( + 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.LfpSaleServiceGrpcTransport, transports.LfpSaleServiceGrpcAsyncIOTransport]) +def test_lfp_sale_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.LfpSaleServiceGrpcTransport, transports.LfpSaleServiceGrpcAsyncIOTransport]) +def test_lfp_sale_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_sale_path(): + account = "squid" + sale = "clam" + expected = "accounts/{account}/lfpSales/{sale}".format(account=account, sale=sale, ) + actual = LfpSaleServiceClient.lfp_sale_path(account, sale) + assert expected == actual + + +def test_parse_lfp_sale_path(): + expected = { + "account": "whelk", + "sale": "octopus", + } + path = LfpSaleServiceClient.lfp_sale_path(**expected) + + # Check that the path construction is reversible. + actual = LfpSaleServiceClient.parse_lfp_sale_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = LfpSaleServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = LfpSaleServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = LfpSaleServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = LfpSaleServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = LfpSaleServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = LfpSaleServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = LfpSaleServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = LfpSaleServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = LfpSaleServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = LfpSaleServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = LfpSaleServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = LfpSaleServiceClient.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 = LfpSaleServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = LfpSaleServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = LfpSaleServiceClient.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.LfpSaleServiceTransport, '_prep_wrapped_messages') as prep: + client = LfpSaleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.LfpSaleServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = LfpSaleServiceClient.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 = LfpSaleServiceClient( + 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 = LfpSaleServiceAsyncClient( + 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 = LfpSaleServiceClient( + 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 = LfpSaleServiceClient( + 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", [ + (LfpSaleServiceClient, transports.LfpSaleServiceGrpcTransport), + (LfpSaleServiceAsyncClient, transports.LfpSaleServiceGrpcAsyncIOTransport), +]) +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-lfp/v1beta/tests/unit/gapic/merchant_lfp_v1beta/test_lfp_store_service.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/tests/unit/gapic/merchant_lfp_v1beta/test_lfp_store_service.py new file mode 100644 index 000000000000..d5f55ed2da1e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/tests/unit/gapic/merchant_lfp_v1beta/test_lfp_store_service.py @@ -0,0 +1,4514 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_lfp_v1beta.services.lfp_store_service import LfpStoreServiceAsyncClient +from google.shopping.merchant_lfp_v1beta.services.lfp_store_service import LfpStoreServiceClient +from google.shopping.merchant_lfp_v1beta.services.lfp_store_service import pagers +from google.shopping.merchant_lfp_v1beta.services.lfp_store_service import transports +from google.shopping.merchant_lfp_v1beta.types import lfpstore +import google.auth + + +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 LfpStoreServiceClient._get_default_mtls_endpoint(None) is None + assert LfpStoreServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert LfpStoreServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert LfpStoreServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert LfpStoreServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert LfpStoreServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert LfpStoreServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert LfpStoreServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert LfpStoreServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + LfpStoreServiceClient._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 LfpStoreServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert LfpStoreServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert LfpStoreServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + LfpStoreServiceClient._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 LfpStoreServiceClient._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 LfpStoreServiceClient._get_client_cert_source(None, False) is None + assert LfpStoreServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert LfpStoreServiceClient._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 LfpStoreServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert LfpStoreServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(LfpStoreServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpStoreServiceClient)) +@mock.patch.object(LfpStoreServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpStoreServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = LfpStoreServiceClient._DEFAULT_UNIVERSE + default_endpoint = LfpStoreServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = LfpStoreServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert LfpStoreServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert LfpStoreServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == LfpStoreServiceClient.DEFAULT_MTLS_ENDPOINT + assert LfpStoreServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert LfpStoreServiceClient._get_api_endpoint(None, None, default_universe, "always") == LfpStoreServiceClient.DEFAULT_MTLS_ENDPOINT + assert LfpStoreServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == LfpStoreServiceClient.DEFAULT_MTLS_ENDPOINT + assert LfpStoreServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert LfpStoreServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + LfpStoreServiceClient._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 LfpStoreServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert LfpStoreServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert LfpStoreServiceClient._get_universe_domain(None, None) == LfpStoreServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + LfpStoreServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize("client_class,transport_name", [ + (LfpStoreServiceClient, "grpc"), + (LfpStoreServiceAsyncClient, "grpc_asyncio"), + (LfpStoreServiceClient, "rest"), +]) +def test_lfp_store_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.LfpStoreServiceGrpcTransport, "grpc"), + (transports.LfpStoreServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.LfpStoreServiceRestTransport, "rest"), +]) +def test_lfp_store_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", [ + (LfpStoreServiceClient, "grpc"), + (LfpStoreServiceAsyncClient, "grpc_asyncio"), + (LfpStoreServiceClient, "rest"), +]) +def test_lfp_store_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_store_service_client_get_transport_class(): + transport = LfpStoreServiceClient.get_transport_class() + available_transports = [ + transports.LfpStoreServiceGrpcTransport, + transports.LfpStoreServiceRestTransport, + ] + assert transport in available_transports + + transport = LfpStoreServiceClient.get_transport_class("grpc") + assert transport == transports.LfpStoreServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (LfpStoreServiceClient, transports.LfpStoreServiceGrpcTransport, "grpc"), + (LfpStoreServiceAsyncClient, transports.LfpStoreServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (LfpStoreServiceClient, transports.LfpStoreServiceRestTransport, "rest"), +]) +@mock.patch.object(LfpStoreServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpStoreServiceClient)) +@mock.patch.object(LfpStoreServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpStoreServiceAsyncClient)) +def test_lfp_store_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(LfpStoreServiceClient, '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(LfpStoreServiceClient, '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", [ + (LfpStoreServiceClient, transports.LfpStoreServiceGrpcTransport, "grpc", "true"), + (LfpStoreServiceAsyncClient, transports.LfpStoreServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (LfpStoreServiceClient, transports.LfpStoreServiceGrpcTransport, "grpc", "false"), + (LfpStoreServiceAsyncClient, transports.LfpStoreServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (LfpStoreServiceClient, transports.LfpStoreServiceRestTransport, "rest", "true"), + (LfpStoreServiceClient, transports.LfpStoreServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(LfpStoreServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpStoreServiceClient)) +@mock.patch.object(LfpStoreServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpStoreServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_lfp_store_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", [ + LfpStoreServiceClient, LfpStoreServiceAsyncClient +]) +@mock.patch.object(LfpStoreServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LfpStoreServiceClient)) +@mock.patch.object(LfpStoreServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LfpStoreServiceAsyncClient)) +def test_lfp_store_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", [ + LfpStoreServiceClient, LfpStoreServiceAsyncClient +]) +@mock.patch.object(LfpStoreServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpStoreServiceClient)) +@mock.patch.object(LfpStoreServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpStoreServiceAsyncClient)) +def test_lfp_store_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = LfpStoreServiceClient._DEFAULT_UNIVERSE + default_endpoint = LfpStoreServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = LfpStoreServiceClient._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", [ + (LfpStoreServiceClient, transports.LfpStoreServiceGrpcTransport, "grpc"), + (LfpStoreServiceAsyncClient, transports.LfpStoreServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (LfpStoreServiceClient, transports.LfpStoreServiceRestTransport, "rest"), +]) +def test_lfp_store_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", [ + (LfpStoreServiceClient, transports.LfpStoreServiceGrpcTransport, "grpc", grpc_helpers), + (LfpStoreServiceAsyncClient, transports.LfpStoreServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (LfpStoreServiceClient, transports.LfpStoreServiceRestTransport, "rest", None), +]) +def test_lfp_store_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_store_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_lfp_v1beta.services.lfp_store_service.transports.LfpStoreServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = LfpStoreServiceClient( + 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", [ + (LfpStoreServiceClient, transports.LfpStoreServiceGrpcTransport, "grpc", grpc_helpers), + (LfpStoreServiceAsyncClient, transports.LfpStoreServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_lfp_store_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", [ + lfpstore.GetLfpStoreRequest, + dict, +]) +def test_get_lfp_store(request_type, transport: str = 'grpc'): + client = LfpStoreServiceClient( + 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_lfp_store), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lfpstore.LfpStore( + name='name_value', + target_account=1491, + store_code='store_code_value', + store_address='store_address_value', + store_name='store_name_value', + phone_number='phone_number_value', + website_uri='website_uri_value', + gcid_category=['gcid_category_value'], + place_id='place_id_value', + matching_state=lfpstore.LfpStore.StoreMatchingState.STORE_MATCHING_STATE_MATCHED, + matching_state_hint='matching_state_hint_value', + ) + response = client.get_lfp_store(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = lfpstore.GetLfpStoreRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, lfpstore.LfpStore) + assert response.name == 'name_value' + assert response.target_account == 1491 + assert response.store_code == 'store_code_value' + assert response.store_address == 'store_address_value' + assert response.store_name == 'store_name_value' + assert response.phone_number == 'phone_number_value' + assert response.website_uri == 'website_uri_value' + assert response.gcid_category == ['gcid_category_value'] + assert response.place_id == 'place_id_value' + assert response.matching_state == lfpstore.LfpStore.StoreMatchingState.STORE_MATCHING_STATE_MATCHED + assert response.matching_state_hint == 'matching_state_hint_value' + + +def test_get_lfp_store_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 = LfpStoreServiceClient( + 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 = lfpstore.GetLfpStoreRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_lfp_store), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_lfp_store(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lfpstore.GetLfpStoreRequest( + name='name_value', + ) + +def test_get_lfp_store_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LfpStoreServiceClient( + 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_lfp_store in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_lfp_store] = mock_rpc + request = {} + client.get_lfp_store(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_lfp_store(request) + + # Establish that a new wrapper 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_lfp_store_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = LfpStoreServiceAsyncClient( + 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_lfp_store in client._client._transport._wrapped_methods + + # 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_lfp_store] = mock_rpc + + request = {} + await client.get_lfp_store(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_lfp_store(request) + + # Establish that a new wrapper 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_lfp_store_async(transport: str = 'grpc_asyncio', request_type=lfpstore.GetLfpStoreRequest): + client = LfpStoreServiceAsyncClient( + 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_lfp_store), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(lfpstore.LfpStore( + name='name_value', + target_account=1491, + store_code='store_code_value', + store_address='store_address_value', + store_name='store_name_value', + phone_number='phone_number_value', + website_uri='website_uri_value', + gcid_category=['gcid_category_value'], + place_id='place_id_value', + matching_state=lfpstore.LfpStore.StoreMatchingState.STORE_MATCHING_STATE_MATCHED, + matching_state_hint='matching_state_hint_value', + )) + response = await client.get_lfp_store(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = lfpstore.GetLfpStoreRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, lfpstore.LfpStore) + assert response.name == 'name_value' + assert response.target_account == 1491 + assert response.store_code == 'store_code_value' + assert response.store_address == 'store_address_value' + assert response.store_name == 'store_name_value' + assert response.phone_number == 'phone_number_value' + assert response.website_uri == 'website_uri_value' + assert response.gcid_category == ['gcid_category_value'] + assert response.place_id == 'place_id_value' + assert response.matching_state == lfpstore.LfpStore.StoreMatchingState.STORE_MATCHING_STATE_MATCHED + assert response.matching_state_hint == 'matching_state_hint_value' + + +@pytest.mark.asyncio +async def test_get_lfp_store_async_from_dict(): + await test_get_lfp_store_async(request_type=dict) + +def test_get_lfp_store_field_headers(): + client = LfpStoreServiceClient( + 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 = lfpstore.GetLfpStoreRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_lfp_store), + '__call__') as call: + call.return_value = lfpstore.LfpStore() + client.get_lfp_store(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_lfp_store_field_headers_async(): + client = LfpStoreServiceAsyncClient( + 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 = lfpstore.GetLfpStoreRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_lfp_store), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpstore.LfpStore()) + await client.get_lfp_store(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_lfp_store_flattened(): + client = LfpStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_lfp_store), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lfpstore.LfpStore() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_lfp_store( + 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_lfp_store_flattened_error(): + client = LfpStoreServiceClient( + 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_lfp_store( + lfpstore.GetLfpStoreRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_lfp_store_flattened_async(): + client = LfpStoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_lfp_store), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lfpstore.LfpStore() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpstore.LfpStore()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_lfp_store( + 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_lfp_store_flattened_error_async(): + client = LfpStoreServiceAsyncClient( + 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_lfp_store( + lfpstore.GetLfpStoreRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + lfpstore.InsertLfpStoreRequest, + dict, +]) +def test_insert_lfp_store(request_type, transport: str = 'grpc'): + client = LfpStoreServiceClient( + 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_lfp_store), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lfpstore.LfpStore( + name='name_value', + target_account=1491, + store_code='store_code_value', + store_address='store_address_value', + store_name='store_name_value', + phone_number='phone_number_value', + website_uri='website_uri_value', + gcid_category=['gcid_category_value'], + place_id='place_id_value', + matching_state=lfpstore.LfpStore.StoreMatchingState.STORE_MATCHING_STATE_MATCHED, + matching_state_hint='matching_state_hint_value', + ) + response = client.insert_lfp_store(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = lfpstore.InsertLfpStoreRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, lfpstore.LfpStore) + assert response.name == 'name_value' + assert response.target_account == 1491 + assert response.store_code == 'store_code_value' + assert response.store_address == 'store_address_value' + assert response.store_name == 'store_name_value' + assert response.phone_number == 'phone_number_value' + assert response.website_uri == 'website_uri_value' + assert response.gcid_category == ['gcid_category_value'] + assert response.place_id == 'place_id_value' + assert response.matching_state == lfpstore.LfpStore.StoreMatchingState.STORE_MATCHING_STATE_MATCHED + assert response.matching_state_hint == 'matching_state_hint_value' + + +def test_insert_lfp_store_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 = LfpStoreServiceClient( + 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 = lfpstore.InsertLfpStoreRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_lfp_store), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.insert_lfp_store(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lfpstore.InsertLfpStoreRequest( + parent='parent_value', + ) + +def test_insert_lfp_store_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LfpStoreServiceClient( + 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_lfp_store in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_lfp_store] = mock_rpc + request = {} + client.insert_lfp_store(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.insert_lfp_store(request) + + # Establish that a new wrapper 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_lfp_store_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = LfpStoreServiceAsyncClient( + 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_lfp_store in client._client._transport._wrapped_methods + + # 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_lfp_store] = mock_rpc + + request = {} + await client.insert_lfp_store(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.insert_lfp_store(request) + + # Establish that a new wrapper 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_lfp_store_async(transport: str = 'grpc_asyncio', request_type=lfpstore.InsertLfpStoreRequest): + client = LfpStoreServiceAsyncClient( + 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_lfp_store), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(lfpstore.LfpStore( + name='name_value', + target_account=1491, + store_code='store_code_value', + store_address='store_address_value', + store_name='store_name_value', + phone_number='phone_number_value', + website_uri='website_uri_value', + gcid_category=['gcid_category_value'], + place_id='place_id_value', + matching_state=lfpstore.LfpStore.StoreMatchingState.STORE_MATCHING_STATE_MATCHED, + matching_state_hint='matching_state_hint_value', + )) + response = await client.insert_lfp_store(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = lfpstore.InsertLfpStoreRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, lfpstore.LfpStore) + assert response.name == 'name_value' + assert response.target_account == 1491 + assert response.store_code == 'store_code_value' + assert response.store_address == 'store_address_value' + assert response.store_name == 'store_name_value' + assert response.phone_number == 'phone_number_value' + assert response.website_uri == 'website_uri_value' + assert response.gcid_category == ['gcid_category_value'] + assert response.place_id == 'place_id_value' + assert response.matching_state == lfpstore.LfpStore.StoreMatchingState.STORE_MATCHING_STATE_MATCHED + assert response.matching_state_hint == 'matching_state_hint_value' + + +@pytest.mark.asyncio +async def test_insert_lfp_store_async_from_dict(): + await test_insert_lfp_store_async(request_type=dict) + +def test_insert_lfp_store_field_headers(): + client = LfpStoreServiceClient( + 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 = lfpstore.InsertLfpStoreRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_lfp_store), + '__call__') as call: + call.return_value = lfpstore.LfpStore() + client.insert_lfp_store(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_lfp_store_field_headers_async(): + client = LfpStoreServiceAsyncClient( + 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 = lfpstore.InsertLfpStoreRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_lfp_store), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpstore.LfpStore()) + await client.insert_lfp_store(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_insert_lfp_store_flattened(): + client = LfpStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_lfp_store), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lfpstore.LfpStore() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.insert_lfp_store( + parent='parent_value', + lfp_store=lfpstore.LfpStore(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].lfp_store + mock_val = lfpstore.LfpStore(name='name_value') + assert arg == mock_val + + +def test_insert_lfp_store_flattened_error(): + client = LfpStoreServiceClient( + 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.insert_lfp_store( + lfpstore.InsertLfpStoreRequest(), + parent='parent_value', + lfp_store=lfpstore.LfpStore(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_insert_lfp_store_flattened_async(): + client = LfpStoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_lfp_store), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lfpstore.LfpStore() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpstore.LfpStore()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.insert_lfp_store( + parent='parent_value', + lfp_store=lfpstore.LfpStore(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].lfp_store + mock_val = lfpstore.LfpStore(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_insert_lfp_store_flattened_error_async(): + client = LfpStoreServiceAsyncClient( + 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.insert_lfp_store( + lfpstore.InsertLfpStoreRequest(), + parent='parent_value', + lfp_store=lfpstore.LfpStore(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + lfpstore.DeleteLfpStoreRequest, + dict, +]) +def test_delete_lfp_store(request_type, transport: str = 'grpc'): + client = LfpStoreServiceClient( + 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_lfp_store), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_lfp_store(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = lfpstore.DeleteLfpStoreRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_lfp_store_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 = LfpStoreServiceClient( + 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 = lfpstore.DeleteLfpStoreRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_lfp_store), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_lfp_store(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lfpstore.DeleteLfpStoreRequest( + name='name_value', + ) + +def test_delete_lfp_store_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LfpStoreServiceClient( + 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_lfp_store in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_lfp_store] = mock_rpc + request = {} + client.delete_lfp_store(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_lfp_store(request) + + # Establish that a new wrapper 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_lfp_store_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = LfpStoreServiceAsyncClient( + 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_lfp_store in client._client._transport._wrapped_methods + + # 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_lfp_store] = mock_rpc + + request = {} + await client.delete_lfp_store(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_lfp_store(request) + + # Establish that a new wrapper 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_lfp_store_async(transport: str = 'grpc_asyncio', request_type=lfpstore.DeleteLfpStoreRequest): + client = LfpStoreServiceAsyncClient( + 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_lfp_store), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_lfp_store(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = lfpstore.DeleteLfpStoreRequest() + 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_lfp_store_async_from_dict(): + await test_delete_lfp_store_async(request_type=dict) + +def test_delete_lfp_store_field_headers(): + client = LfpStoreServiceClient( + 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 = lfpstore.DeleteLfpStoreRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_lfp_store), + '__call__') as call: + call.return_value = None + client.delete_lfp_store(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_lfp_store_field_headers_async(): + client = LfpStoreServiceAsyncClient( + 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 = lfpstore.DeleteLfpStoreRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_lfp_store), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_lfp_store(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_lfp_store_flattened(): + client = LfpStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_lfp_store), + '__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_lfp_store( + 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_lfp_store_flattened_error(): + client = LfpStoreServiceClient( + 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_lfp_store( + lfpstore.DeleteLfpStoreRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_lfp_store_flattened_async(): + client = LfpStoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_lfp_store), + '__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_lfp_store( + 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_lfp_store_flattened_error_async(): + client = LfpStoreServiceAsyncClient( + 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_lfp_store( + lfpstore.DeleteLfpStoreRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + lfpstore.ListLfpStoresRequest, + dict, +]) +def test_list_lfp_stores(request_type, transport: str = 'grpc'): + client = LfpStoreServiceClient( + 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_lfp_stores), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lfpstore.ListLfpStoresResponse( + next_page_token='next_page_token_value', + ) + response = client.list_lfp_stores(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = lfpstore.ListLfpStoresRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListLfpStoresPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_lfp_stores_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 = LfpStoreServiceClient( + 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 = lfpstore.ListLfpStoresRequest( + 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_lfp_stores), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_lfp_stores(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lfpstore.ListLfpStoresRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_lfp_stores_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LfpStoreServiceClient( + 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_lfp_stores in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_lfp_stores] = mock_rpc + request = {} + client.list_lfp_stores(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_lfp_stores(request) + + # Establish that a new wrapper 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_lfp_stores_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = LfpStoreServiceAsyncClient( + 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_lfp_stores in client._client._transport._wrapped_methods + + # 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_lfp_stores] = mock_rpc + + request = {} + await client.list_lfp_stores(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_lfp_stores(request) + + # Establish that a new wrapper 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_lfp_stores_async(transport: str = 'grpc_asyncio', request_type=lfpstore.ListLfpStoresRequest): + client = LfpStoreServiceAsyncClient( + 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_lfp_stores), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(lfpstore.ListLfpStoresResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_lfp_stores(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = lfpstore.ListLfpStoresRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListLfpStoresAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_lfp_stores_async_from_dict(): + await test_list_lfp_stores_async(request_type=dict) + +def test_list_lfp_stores_field_headers(): + client = LfpStoreServiceClient( + 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 = lfpstore.ListLfpStoresRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lfp_stores), + '__call__') as call: + call.return_value = lfpstore.ListLfpStoresResponse() + client.list_lfp_stores(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_lfp_stores_field_headers_async(): + client = LfpStoreServiceAsyncClient( + 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 = lfpstore.ListLfpStoresRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lfp_stores), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpstore.ListLfpStoresResponse()) + await client.list_lfp_stores(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_lfp_stores_flattened(): + client = LfpStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lfp_stores), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lfpstore.ListLfpStoresResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_lfp_stores( + 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_lfp_stores_flattened_error(): + client = LfpStoreServiceClient( + 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_lfp_stores( + lfpstore.ListLfpStoresRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_lfp_stores_flattened_async(): + client = LfpStoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lfp_stores), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lfpstore.ListLfpStoresResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpstore.ListLfpStoresResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_lfp_stores( + 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_lfp_stores_flattened_error_async(): + client = LfpStoreServiceAsyncClient( + 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_lfp_stores( + lfpstore.ListLfpStoresRequest(), + parent='parent_value', + ) + + +def test_list_lfp_stores_pager(transport_name: str = "grpc"): + client = LfpStoreServiceClient( + 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_lfp_stores), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + lfpstore.ListLfpStoresResponse( + lfp_stores=[ + lfpstore.LfpStore(), + lfpstore.LfpStore(), + lfpstore.LfpStore(), + ], + next_page_token='abc', + ), + lfpstore.ListLfpStoresResponse( + lfp_stores=[], + next_page_token='def', + ), + lfpstore.ListLfpStoresResponse( + lfp_stores=[ + lfpstore.LfpStore(), + ], + next_page_token='ghi', + ), + lfpstore.ListLfpStoresResponse( + lfp_stores=[ + lfpstore.LfpStore(), + lfpstore.LfpStore(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_lfp_stores(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, lfpstore.LfpStore) + for i in results) +def test_list_lfp_stores_pages(transport_name: str = "grpc"): + client = LfpStoreServiceClient( + 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_lfp_stores), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + lfpstore.ListLfpStoresResponse( + lfp_stores=[ + lfpstore.LfpStore(), + lfpstore.LfpStore(), + lfpstore.LfpStore(), + ], + next_page_token='abc', + ), + lfpstore.ListLfpStoresResponse( + lfp_stores=[], + next_page_token='def', + ), + lfpstore.ListLfpStoresResponse( + lfp_stores=[ + lfpstore.LfpStore(), + ], + next_page_token='ghi', + ), + lfpstore.ListLfpStoresResponse( + lfp_stores=[ + lfpstore.LfpStore(), + lfpstore.LfpStore(), + ], + ), + RuntimeError, + ) + pages = list(client.list_lfp_stores(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_lfp_stores_async_pager(): + client = LfpStoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lfp_stores), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + lfpstore.ListLfpStoresResponse( + lfp_stores=[ + lfpstore.LfpStore(), + lfpstore.LfpStore(), + lfpstore.LfpStore(), + ], + next_page_token='abc', + ), + lfpstore.ListLfpStoresResponse( + lfp_stores=[], + next_page_token='def', + ), + lfpstore.ListLfpStoresResponse( + lfp_stores=[ + lfpstore.LfpStore(), + ], + next_page_token='ghi', + ), + lfpstore.ListLfpStoresResponse( + lfp_stores=[ + lfpstore.LfpStore(), + lfpstore.LfpStore(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_lfp_stores(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, lfpstore.LfpStore) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_lfp_stores_async_pages(): + client = LfpStoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lfp_stores), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + lfpstore.ListLfpStoresResponse( + lfp_stores=[ + lfpstore.LfpStore(), + lfpstore.LfpStore(), + lfpstore.LfpStore(), + ], + next_page_token='abc', + ), + lfpstore.ListLfpStoresResponse( + lfp_stores=[], + next_page_token='def', + ), + lfpstore.ListLfpStoresResponse( + lfp_stores=[ + lfpstore.LfpStore(), + ], + next_page_token='ghi', + ), + lfpstore.ListLfpStoresResponse( + lfp_stores=[ + lfpstore.LfpStore(), + lfpstore.LfpStore(), + ], + ), + 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_lfp_stores(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_lfp_store_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 = LfpStoreServiceClient( + 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_lfp_store in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_lfp_store] = mock_rpc + + request = {} + client.get_lfp_store(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_lfp_store(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_lfp_store_rest_required_fields(request_type=lfpstore.GetLfpStoreRequest): + transport_class = transports.LfpStoreServiceRestTransport + + 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_lfp_store._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_lfp_store._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 = LfpStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = lfpstore.LfpStore() + # 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 = lfpstore.LfpStore.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_lfp_store(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_lfp_store_rest_unset_required_fields(): + transport = transports.LfpStoreServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_lfp_store._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_lfp_store_rest_flattened(): + client = LfpStoreServiceClient( + 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 = lfpstore.LfpStore() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/lfpStores/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 = lfpstore.LfpStore.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_lfp_store(**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/lfp/v1beta/{name=accounts/*/lfpStores/*}" % client.transport._host, args[1]) + + +def test_get_lfp_store_rest_flattened_error(transport: str = 'rest'): + client = LfpStoreServiceClient( + 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_lfp_store( + lfpstore.GetLfpStoreRequest(), + name='name_value', + ) + + +def test_insert_lfp_store_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 = LfpStoreServiceClient( + 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_lfp_store in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_lfp_store] = mock_rpc + + request = {} + client.insert_lfp_store(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.insert_lfp_store(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_lfp_store_rest_required_fields(request_type=lfpstore.InsertLfpStoreRequest): + transport_class = transports.LfpStoreServiceRestTransport + + 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_lfp_store._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_lfp_store._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 = LfpStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = lfpstore.LfpStore() + # 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 = lfpstore.LfpStore.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_lfp_store(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_insert_lfp_store_rest_unset_required_fields(): + transport = transports.LfpStoreServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.insert_lfp_store._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "lfpStore", ))) + + +def test_insert_lfp_store_rest_flattened(): + client = LfpStoreServiceClient( + 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 = lfpstore.LfpStore() + + # 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', + lfp_store=lfpstore.LfpStore(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 = lfpstore.LfpStore.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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.insert_lfp_store(**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/lfp/v1beta/{parent=accounts/*}/lfpStores:insert" % client.transport._host, args[1]) + + +def test_insert_lfp_store_rest_flattened_error(transport: str = 'rest'): + client = LfpStoreServiceClient( + 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.insert_lfp_store( + lfpstore.InsertLfpStoreRequest(), + parent='parent_value', + lfp_store=lfpstore.LfpStore(name='name_value'), + ) + + +def test_delete_lfp_store_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 = LfpStoreServiceClient( + 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_lfp_store in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_lfp_store] = mock_rpc + + request = {} + client.delete_lfp_store(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_lfp_store(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_lfp_store_rest_required_fields(request_type=lfpstore.DeleteLfpStoreRequest): + transport_class = transports.LfpStoreServiceRestTransport + + 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_lfp_store._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_lfp_store._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 = LfpStoreServiceClient( + 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_lfp_store(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_lfp_store_rest_unset_required_fields(): + transport = transports.LfpStoreServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_lfp_store._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_delete_lfp_store_rest_flattened(): + client = LfpStoreServiceClient( + 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/lfpStores/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_lfp_store(**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/lfp/v1beta/{name=accounts/*/lfpStores/*}" % client.transport._host, args[1]) + + +def test_delete_lfp_store_rest_flattened_error(transport: str = 'rest'): + client = LfpStoreServiceClient( + 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_lfp_store( + lfpstore.DeleteLfpStoreRequest(), + name='name_value', + ) + + +def test_list_lfp_stores_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 = LfpStoreServiceClient( + 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_lfp_stores in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_lfp_stores] = mock_rpc + + request = {} + client.list_lfp_stores(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_lfp_stores(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_lfp_stores_rest_required_fields(request_type=lfpstore.ListLfpStoresRequest): + transport_class = transports.LfpStoreServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["target_account"] = 0 + request = 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 "targetAccount" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_lfp_stores._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "targetAccount" in jsonified_request + assert jsonified_request["targetAccount"] == request_init["target_account"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["targetAccount"] = 1491 + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_lfp_stores._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", "target_account", )) + 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 "targetAccount" in jsonified_request + assert jsonified_request["targetAccount"] == 1491 + + client = LfpStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = lfpstore.ListLfpStoresResponse() + # 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 = lfpstore.ListLfpStoresResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_lfp_stores(request) + + expected_params = [ + ( + "targetAccount", + str(0), + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_lfp_stores_rest_unset_required_fields(): + transport = transports.LfpStoreServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_lfp_stores._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", "targetAccount", )) & set(("parent", "targetAccount", ))) + + +def test_list_lfp_stores_rest_flattened(): + client = LfpStoreServiceClient( + 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 = lfpstore.ListLfpStoresResponse() + + # 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 = lfpstore.ListLfpStoresResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_lfp_stores(**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/lfp/v1beta/{parent=accounts/*}/lfpStores" % client.transport._host, args[1]) + + +def test_list_lfp_stores_rest_flattened_error(transport: str = 'rest'): + client = LfpStoreServiceClient( + 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_lfp_stores( + lfpstore.ListLfpStoresRequest(), + parent='parent_value', + ) + + +def test_list_lfp_stores_rest_pager(transport: str = 'rest'): + client = LfpStoreServiceClient( + 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 = ( + lfpstore.ListLfpStoresResponse( + lfp_stores=[ + lfpstore.LfpStore(), + lfpstore.LfpStore(), + lfpstore.LfpStore(), + ], + next_page_token='abc', + ), + lfpstore.ListLfpStoresResponse( + lfp_stores=[], + next_page_token='def', + ), + lfpstore.ListLfpStoresResponse( + lfp_stores=[ + lfpstore.LfpStore(), + ], + next_page_token='ghi', + ), + lfpstore.ListLfpStoresResponse( + lfp_stores=[ + lfpstore.LfpStore(), + lfpstore.LfpStore(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(lfpstore.ListLfpStoresResponse.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_lfp_stores(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, lfpstore.LfpStore) + for i in results) + + pages = list(client.list_lfp_stores(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.LfpStoreServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LfpStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.LfpStoreServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LfpStoreServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.LfpStoreServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = LfpStoreServiceClient( + 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 = LfpStoreServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.LfpStoreServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LfpStoreServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.LfpStoreServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = LfpStoreServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.LfpStoreServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.LfpStoreServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.LfpStoreServiceGrpcTransport, + transports.LfpStoreServiceGrpcAsyncIOTransport, + transports.LfpStoreServiceRestTransport, +]) +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 = LfpStoreServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = LfpStoreServiceClient( + 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_lfp_store_empty_call_grpc(): + client = LfpStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_lfp_store), + '__call__') as call: + call.return_value = lfpstore.LfpStore() + client.get_lfp_store(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = lfpstore.GetLfpStoreRequest() + + assert args[0] == request_msg + + +# This 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_lfp_store_empty_call_grpc(): + client = LfpStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.insert_lfp_store), + '__call__') as call: + call.return_value = lfpstore.LfpStore() + client.insert_lfp_store(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = lfpstore.InsertLfpStoreRequest() + + assert args[0] == request_msg + + +# This 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_lfp_store_empty_call_grpc(): + client = LfpStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_lfp_store), + '__call__') as call: + call.return_value = None + client.delete_lfp_store(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = lfpstore.DeleteLfpStoreRequest() + + assert args[0] == request_msg + + +# This 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_lfp_stores_empty_call_grpc(): + client = LfpStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_lfp_stores), + '__call__') as call: + call.return_value = lfpstore.ListLfpStoresResponse() + client.list_lfp_stores(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = lfpstore.ListLfpStoresRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = LfpStoreServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = LfpStoreServiceAsyncClient( + 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_lfp_store_empty_call_grpc_asyncio(): + client = LfpStoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_lfp_store), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpstore.LfpStore( + name='name_value', + target_account=1491, + store_code='store_code_value', + store_address='store_address_value', + store_name='store_name_value', + phone_number='phone_number_value', + website_uri='website_uri_value', + gcid_category=['gcid_category_value'], + place_id='place_id_value', + matching_state=lfpstore.LfpStore.StoreMatchingState.STORE_MATCHING_STATE_MATCHED, + matching_state_hint='matching_state_hint_value', + )) + await client.get_lfp_store(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = lfpstore.GetLfpStoreRequest() + + assert args[0] == request_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_lfp_store_empty_call_grpc_asyncio(): + client = LfpStoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.insert_lfp_store), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpstore.LfpStore( + name='name_value', + target_account=1491, + store_code='store_code_value', + store_address='store_address_value', + store_name='store_name_value', + phone_number='phone_number_value', + website_uri='website_uri_value', + gcid_category=['gcid_category_value'], + place_id='place_id_value', + matching_state=lfpstore.LfpStore.StoreMatchingState.STORE_MATCHING_STATE_MATCHED, + matching_state_hint='matching_state_hint_value', + )) + await client.insert_lfp_store(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = lfpstore.InsertLfpStoreRequest() + + assert args[0] == request_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_lfp_store_empty_call_grpc_asyncio(): + client = LfpStoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_lfp_store), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_lfp_store(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = lfpstore.DeleteLfpStoreRequest() + + assert args[0] == request_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_lfp_stores_empty_call_grpc_asyncio(): + client = LfpStoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_lfp_stores), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpstore.ListLfpStoresResponse( + next_page_token='next_page_token_value', + )) + await client.list_lfp_stores(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = lfpstore.ListLfpStoresRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = LfpStoreServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_lfp_store_rest_bad_request(request_type=lfpstore.GetLfpStoreRequest): + client = LfpStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/lfpStores/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_lfp_store(request) + + +@pytest.mark.parametrize("request_type", [ + lfpstore.GetLfpStoreRequest, + dict, +]) +def test_get_lfp_store_rest_call_success(request_type): + client = LfpStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/lfpStores/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 = lfpstore.LfpStore( + name='name_value', + target_account=1491, + store_code='store_code_value', + store_address='store_address_value', + store_name='store_name_value', + phone_number='phone_number_value', + website_uri='website_uri_value', + gcid_category=['gcid_category_value'], + place_id='place_id_value', + matching_state=lfpstore.LfpStore.StoreMatchingState.STORE_MATCHING_STATE_MATCHED, + matching_state_hint='matching_state_hint_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 = lfpstore.LfpStore.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_lfp_store(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, lfpstore.LfpStore) + assert response.name == 'name_value' + assert response.target_account == 1491 + assert response.store_code == 'store_code_value' + assert response.store_address == 'store_address_value' + assert response.store_name == 'store_name_value' + assert response.phone_number == 'phone_number_value' + assert response.website_uri == 'website_uri_value' + assert response.gcid_category == ['gcid_category_value'] + assert response.place_id == 'place_id_value' + assert response.matching_state == lfpstore.LfpStore.StoreMatchingState.STORE_MATCHING_STATE_MATCHED + assert response.matching_state_hint == 'matching_state_hint_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_lfp_store_rest_interceptors(null_interceptor): + transport = transports.LfpStoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LfpStoreServiceRestInterceptor(), + ) + client = LfpStoreServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.LfpStoreServiceRestInterceptor, "post_get_lfp_store") as post, \ + mock.patch.object(transports.LfpStoreServiceRestInterceptor, "pre_get_lfp_store") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = lfpstore.GetLfpStoreRequest.pb(lfpstore.GetLfpStoreRequest()) + 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 = lfpstore.LfpStore.to_json(lfpstore.LfpStore()) + req.return_value.content = return_value + + request = lfpstore.GetLfpStoreRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = lfpstore.LfpStore() + + client.get_lfp_store(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_insert_lfp_store_rest_bad_request(request_type=lfpstore.InsertLfpStoreRequest): + client = LfpStoreServiceClient( + 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_lfp_store(request) + + +@pytest.mark.parametrize("request_type", [ + lfpstore.InsertLfpStoreRequest, + dict, +]) +def test_insert_lfp_store_rest_call_success(request_type): + client = LfpStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + request_init["lfp_store"] = {'name': 'name_value', 'target_account': 1491, 'store_code': 'store_code_value', 'store_address': 'store_address_value', 'store_name': 'store_name_value', 'phone_number': 'phone_number_value', 'website_uri': 'website_uri_value', 'gcid_category': ['gcid_category_value1', 'gcid_category_value2'], 'place_id': 'place_id_value', 'matching_state': 1, 'matching_state_hint': 'matching_state_hint_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 = lfpstore.InsertLfpStoreRequest.meta.fields["lfp_store"] + + 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["lfp_store"].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["lfp_store"][field])): + del request_init["lfp_store"][field][i][subfield] + else: + del request_init["lfp_store"][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 = lfpstore.LfpStore( + name='name_value', + target_account=1491, + store_code='store_code_value', + store_address='store_address_value', + store_name='store_name_value', + phone_number='phone_number_value', + website_uri='website_uri_value', + gcid_category=['gcid_category_value'], + place_id='place_id_value', + matching_state=lfpstore.LfpStore.StoreMatchingState.STORE_MATCHING_STATE_MATCHED, + matching_state_hint='matching_state_hint_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 = lfpstore.LfpStore.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_lfp_store(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, lfpstore.LfpStore) + assert response.name == 'name_value' + assert response.target_account == 1491 + assert response.store_code == 'store_code_value' + assert response.store_address == 'store_address_value' + assert response.store_name == 'store_name_value' + assert response.phone_number == 'phone_number_value' + assert response.website_uri == 'website_uri_value' + assert response.gcid_category == ['gcid_category_value'] + assert response.place_id == 'place_id_value' + assert response.matching_state == lfpstore.LfpStore.StoreMatchingState.STORE_MATCHING_STATE_MATCHED + assert response.matching_state_hint == 'matching_state_hint_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_insert_lfp_store_rest_interceptors(null_interceptor): + transport = transports.LfpStoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LfpStoreServiceRestInterceptor(), + ) + client = LfpStoreServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.LfpStoreServiceRestInterceptor, "post_insert_lfp_store") as post, \ + mock.patch.object(transports.LfpStoreServiceRestInterceptor, "pre_insert_lfp_store") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = lfpstore.InsertLfpStoreRequest.pb(lfpstore.InsertLfpStoreRequest()) + 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 = lfpstore.LfpStore.to_json(lfpstore.LfpStore()) + req.return_value.content = return_value + + request = lfpstore.InsertLfpStoreRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = lfpstore.LfpStore() + + client.insert_lfp_store(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_lfp_store_rest_bad_request(request_type=lfpstore.DeleteLfpStoreRequest): + client = LfpStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/lfpStores/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_lfp_store(request) + + +@pytest.mark.parametrize("request_type", [ + lfpstore.DeleteLfpStoreRequest, + dict, +]) +def test_delete_lfp_store_rest_call_success(request_type): + client = LfpStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/lfpStores/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_lfp_store(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_lfp_store_rest_interceptors(null_interceptor): + transport = transports.LfpStoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LfpStoreServiceRestInterceptor(), + ) + client = LfpStoreServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.LfpStoreServiceRestInterceptor, "pre_delete_lfp_store") as pre: + pre.assert_not_called() + pb_message = lfpstore.DeleteLfpStoreRequest.pb(lfpstore.DeleteLfpStoreRequest()) + 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 = lfpstore.DeleteLfpStoreRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_lfp_store(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_list_lfp_stores_rest_bad_request(request_type=lfpstore.ListLfpStoresRequest): + client = LfpStoreServiceClient( + 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_lfp_stores(request) + + +@pytest.mark.parametrize("request_type", [ + lfpstore.ListLfpStoresRequest, + dict, +]) +def test_list_lfp_stores_rest_call_success(request_type): + client = LfpStoreServiceClient( + 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 = lfpstore.ListLfpStoresResponse( + 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 = lfpstore.ListLfpStoresResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_lfp_stores(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListLfpStoresPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_lfp_stores_rest_interceptors(null_interceptor): + transport = transports.LfpStoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LfpStoreServiceRestInterceptor(), + ) + client = LfpStoreServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.LfpStoreServiceRestInterceptor, "post_list_lfp_stores") as post, \ + mock.patch.object(transports.LfpStoreServiceRestInterceptor, "pre_list_lfp_stores") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = lfpstore.ListLfpStoresRequest.pb(lfpstore.ListLfpStoresRequest()) + 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 = lfpstore.ListLfpStoresResponse.to_json(lfpstore.ListLfpStoresResponse()) + req.return_value.content = return_value + + request = lfpstore.ListLfpStoresRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = lfpstore.ListLfpStoresResponse() + + client.list_lfp_stores(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + +def test_initialize_client_w_rest(): + client = LfpStoreServiceClient( + 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_lfp_store_empty_call_rest(): + client = LfpStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_lfp_store), + '__call__') as call: + client.get_lfp_store(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = lfpstore.GetLfpStoreRequest() + + assert args[0] == request_msg + + +# This 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_lfp_store_empty_call_rest(): + client = LfpStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.insert_lfp_store), + '__call__') as call: + client.insert_lfp_store(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = lfpstore.InsertLfpStoreRequest() + + assert args[0] == request_msg + + +# This 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_lfp_store_empty_call_rest(): + client = LfpStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_lfp_store), + '__call__') as call: + client.delete_lfp_store(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = lfpstore.DeleteLfpStoreRequest() + + assert args[0] == request_msg + + +# This 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_lfp_stores_empty_call_rest(): + client = LfpStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_lfp_stores), + '__call__') as call: + client.list_lfp_stores(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = lfpstore.ListLfpStoresRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = LfpStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.LfpStoreServiceGrpcTransport, + ) + +def test_lfp_store_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.LfpStoreServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_lfp_store_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_lfp_v1beta.services.lfp_store_service.transports.LfpStoreServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.LfpStoreServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_lfp_store', + 'insert_lfp_store', + 'delete_lfp_store', + 'list_lfp_stores', + ) + 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_store_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_lfp_v1beta.services.lfp_store_service.transports.LfpStoreServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.LfpStoreServiceTransport( + 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_store_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_lfp_v1beta.services.lfp_store_service.transports.LfpStoreServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.LfpStoreServiceTransport() + adc.assert_called_once() + + +def test_lfp_store_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) + LfpStoreServiceClient() + 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.LfpStoreServiceGrpcTransport, + transports.LfpStoreServiceGrpcAsyncIOTransport, + ], +) +def test_lfp_store_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.LfpStoreServiceGrpcTransport, + transports.LfpStoreServiceGrpcAsyncIOTransport, + transports.LfpStoreServiceRestTransport, + ], +) +def test_lfp_store_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.LfpStoreServiceGrpcTransport, grpc_helpers), + (transports.LfpStoreServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_lfp_store_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.LfpStoreServiceGrpcTransport, transports.LfpStoreServiceGrpcAsyncIOTransport]) +def test_lfp_store_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_store_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.LfpStoreServiceRestTransport ( + 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_store_service_host_no_port(transport_name): + client = LfpStoreServiceClient( + 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_store_service_host_with_port(transport_name): + client = LfpStoreServiceClient( + 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_store_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = LfpStoreServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = LfpStoreServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_lfp_store._session + session2 = client2.transport.get_lfp_store._session + assert session1 != session2 + session1 = client1.transport.insert_lfp_store._session + session2 = client2.transport.insert_lfp_store._session + assert session1 != session2 + session1 = client1.transport.delete_lfp_store._session + session2 = client2.transport.delete_lfp_store._session + assert session1 != session2 + session1 = client1.transport.list_lfp_stores._session + session2 = client2.transport.list_lfp_stores._session + assert session1 != session2 +def test_lfp_store_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.LfpStoreServiceGrpcTransport( + 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_store_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.LfpStoreServiceGrpcAsyncIOTransport( + 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.LfpStoreServiceGrpcTransport, transports.LfpStoreServiceGrpcAsyncIOTransport]) +def test_lfp_store_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.LfpStoreServiceGrpcTransport, transports.LfpStoreServiceGrpcAsyncIOTransport]) +def test_lfp_store_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_store_path(): + account = "squid" + target_merchant = "clam" + store_code = "whelk" + expected = "accounts/{account}/lfpStores/{target_merchant}~{store_code}".format(account=account, target_merchant=target_merchant, store_code=store_code, ) + actual = LfpStoreServiceClient.lfp_store_path(account, target_merchant, store_code) + assert expected == actual + + +def test_parse_lfp_store_path(): + expected = { + "account": "octopus", + "target_merchant": "oyster", + "store_code": "nudibranch", + } + path = LfpStoreServiceClient.lfp_store_path(**expected) + + # Check that the path construction is reversible. + actual = LfpStoreServiceClient.parse_lfp_store_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = LfpStoreServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = LfpStoreServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = LfpStoreServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = LfpStoreServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = LfpStoreServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = LfpStoreServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = LfpStoreServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = LfpStoreServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = LfpStoreServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = LfpStoreServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = LfpStoreServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = LfpStoreServiceClient.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 = LfpStoreServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = LfpStoreServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = LfpStoreServiceClient.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.LfpStoreServiceTransport, '_prep_wrapped_messages') as prep: + client = LfpStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.LfpStoreServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = LfpStoreServiceClient.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 = LfpStoreServiceClient( + 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 = LfpStoreServiceAsyncClient( + 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 = LfpStoreServiceClient( + 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 = LfpStoreServiceClient( + 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", [ + (LfpStoreServiceClient, transports.LfpStoreServiceGrpcTransport), + (LfpStoreServiceAsyncClient, transports.LfpStoreServiceGrpcAsyncIOTransport), +]) +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-notifications/v1beta/.coveragerc b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/.coveragerc new file mode 100644 index 000000000000..0f8bd476cddd --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/shopping/merchant_notifications/__init__.py + google/shopping/merchant_notifications/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-notifications/v1beta/.flake8 b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/MANIFEST.in b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/MANIFEST.in new file mode 100644 index 000000000000..9f4e45925603 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/shopping/merchant_notifications *.py +recursive-include google/shopping/merchant_notifications_v1beta *.py diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/README.rst b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/README.rst new file mode 100644 index 000000000000..614a3e6e1d20 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Shopping Merchant Notifications 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 Notifications 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 diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/_static/custom.css b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/conf.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/conf.py new file mode 100644 index 000000000000..f097792928e1 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-notifications 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("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# 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.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +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-notifications" +copyright = u"2023, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# 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 = 'en' + +# 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"] + +# 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 Python", + "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-notifications-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-notifications.tex", + u"google-shopping-merchant-notifications 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-notifications", + u"Google Shopping Merchant Notifications 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-notifications", + u"google-shopping-merchant-notifications Documentation", + author, + "google-shopping-merchant-notifications", + "GAPIC library for Google Shopping Merchant Notifications API", + "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": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", 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-notifications/v1beta/docs/index.rst b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/index.rst new file mode 100644 index 000000000000..19ecfb85828e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + merchant_notifications_v1beta/services_ + merchant_notifications_v1beta/types_ diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/merchant_notifications_v1beta/notifications_api_service.rst b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/merchant_notifications_v1beta/notifications_api_service.rst new file mode 100644 index 000000000000..ed3e6760500b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/merchant_notifications_v1beta/notifications_api_service.rst @@ -0,0 +1,10 @@ +NotificationsApiService +----------------------------------------- + +.. automodule:: google.shopping.merchant_notifications_v1beta.services.notifications_api_service + :members: + :inherited-members: + +.. automodule:: google.shopping.merchant_notifications_v1beta.services.notifications_api_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/merchant_notifications_v1beta/services_.rst b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/merchant_notifications_v1beta/services_.rst new file mode 100644 index 000000000000..92e0d93e8fbb --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/merchant_notifications_v1beta/services_.rst @@ -0,0 +1,6 @@ +Services for Google Shopping Merchant Notifications v1beta API +============================================================== +.. toctree:: + :maxdepth: 2 + + notifications_api_service diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/merchant_notifications_v1beta/types_.rst b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/merchant_notifications_v1beta/types_.rst new file mode 100644 index 000000000000..8fd3b768b617 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/merchant_notifications_v1beta/types_.rst @@ -0,0 +1,6 @@ +Types for Google Shopping Merchant Notifications v1beta API +=========================================================== + +.. automodule:: google.shopping.merchant_notifications_v1beta.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications/__init__.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications/__init__.py new file mode 100644 index 000000000000..a8de8d42680b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications/__init__.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_notifications import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.shopping.merchant_notifications_v1beta.services.notifications_api_service.client import NotificationsApiServiceClient +from google.shopping.merchant_notifications_v1beta.services.notifications_api_service.async_client import NotificationsApiServiceAsyncClient + +from google.shopping.merchant_notifications_v1beta.types.notificationsapi import CreateNotificationSubscriptionRequest +from google.shopping.merchant_notifications_v1beta.types.notificationsapi import DeleteNotificationSubscriptionRequest +from google.shopping.merchant_notifications_v1beta.types.notificationsapi import GetNotificationSubscriptionRequest +from google.shopping.merchant_notifications_v1beta.types.notificationsapi import ListNotificationSubscriptionsRequest +from google.shopping.merchant_notifications_v1beta.types.notificationsapi import ListNotificationSubscriptionsResponse +from google.shopping.merchant_notifications_v1beta.types.notificationsapi import NotificationSubscription +from google.shopping.merchant_notifications_v1beta.types.notificationsapi import ProductChange +from google.shopping.merchant_notifications_v1beta.types.notificationsapi import ProductStatusChangeMessage +from google.shopping.merchant_notifications_v1beta.types.notificationsapi import UpdateNotificationSubscriptionRequest +from google.shopping.merchant_notifications_v1beta.types.notificationsapi import Attribute +from google.shopping.merchant_notifications_v1beta.types.notificationsapi import Resource + +__all__ = ('NotificationsApiServiceClient', + 'NotificationsApiServiceAsyncClient', + 'CreateNotificationSubscriptionRequest', + 'DeleteNotificationSubscriptionRequest', + 'GetNotificationSubscriptionRequest', + 'ListNotificationSubscriptionsRequest', + 'ListNotificationSubscriptionsResponse', + 'NotificationSubscription', + 'ProductChange', + 'ProductStatusChangeMessage', + 'UpdateNotificationSubscriptionRequest', + 'Attribute', + 'Resource', +) diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications/gapic_version.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-notifications/v1beta/google/shopping/merchant_notifications/py.typed b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications/py.typed new file mode 100644 index 000000000000..1ce34936b424 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-shopping-merchant-notifications package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/__init__.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/__init__.py new file mode 100644 index 000000000000..4eed2bdb1813 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/__init__.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_notifications_v1beta import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.notifications_api_service import NotificationsApiServiceClient +from .services.notifications_api_service import NotificationsApiServiceAsyncClient + +from .types.notificationsapi import CreateNotificationSubscriptionRequest +from .types.notificationsapi import DeleteNotificationSubscriptionRequest +from .types.notificationsapi import GetNotificationSubscriptionRequest +from .types.notificationsapi import ListNotificationSubscriptionsRequest +from .types.notificationsapi import ListNotificationSubscriptionsResponse +from .types.notificationsapi import NotificationSubscription +from .types.notificationsapi import ProductChange +from .types.notificationsapi import ProductStatusChangeMessage +from .types.notificationsapi import UpdateNotificationSubscriptionRequest +from .types.notificationsapi import Attribute +from .types.notificationsapi import Resource + +__all__ = ( + 'NotificationsApiServiceAsyncClient', +'Attribute', +'CreateNotificationSubscriptionRequest', +'DeleteNotificationSubscriptionRequest', +'GetNotificationSubscriptionRequest', +'ListNotificationSubscriptionsRequest', +'ListNotificationSubscriptionsResponse', +'NotificationSubscription', +'NotificationsApiServiceClient', +'ProductChange', +'ProductStatusChangeMessage', +'Resource', +'UpdateNotificationSubscriptionRequest', +) diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/gapic_metadata.json b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/gapic_metadata.json new file mode 100644 index 000000000000..1c9f742e51f9 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/gapic_metadata.json @@ -0,0 +1,103 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.shopping.merchant_notifications_v1beta", + "protoPackage": "google.shopping.merchant.notifications.v1beta", + "schema": "1.0", + "services": { + "NotificationsApiService": { + "clients": { + "grpc": { + "libraryClient": "NotificationsApiServiceClient", + "rpcs": { + "CreateNotificationSubscription": { + "methods": [ + "create_notification_subscription" + ] + }, + "DeleteNotificationSubscription": { + "methods": [ + "delete_notification_subscription" + ] + }, + "GetNotificationSubscription": { + "methods": [ + "get_notification_subscription" + ] + }, + "ListNotificationSubscriptions": { + "methods": [ + "list_notification_subscriptions" + ] + }, + "UpdateNotificationSubscription": { + "methods": [ + "update_notification_subscription" + ] + } + } + }, + "grpc-async": { + "libraryClient": "NotificationsApiServiceAsyncClient", + "rpcs": { + "CreateNotificationSubscription": { + "methods": [ + "create_notification_subscription" + ] + }, + "DeleteNotificationSubscription": { + "methods": [ + "delete_notification_subscription" + ] + }, + "GetNotificationSubscription": { + "methods": [ + "get_notification_subscription" + ] + }, + "ListNotificationSubscriptions": { + "methods": [ + "list_notification_subscriptions" + ] + }, + "UpdateNotificationSubscription": { + "methods": [ + "update_notification_subscription" + ] + } + } + }, + "rest": { + "libraryClient": "NotificationsApiServiceClient", + "rpcs": { + "CreateNotificationSubscription": { + "methods": [ + "create_notification_subscription" + ] + }, + "DeleteNotificationSubscription": { + "methods": [ + "delete_notification_subscription" + ] + }, + "GetNotificationSubscription": { + "methods": [ + "get_notification_subscription" + ] + }, + "ListNotificationSubscriptions": { + "methods": [ + "list_notification_subscriptions" + ] + }, + "UpdateNotificationSubscription": { + "methods": [ + "update_notification_subscription" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/gapic_version.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-notifications/v1beta/google/shopping/merchant_notifications_v1beta/py.typed b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/py.typed new file mode 100644 index 000000000000..1ce34936b424 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-shopping-merchant-notifications package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/__init__.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/__init__.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/__init__.py new file mode 100644 index 000000000000..8698b4100c81 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 NotificationsApiServiceClient +from .async_client import NotificationsApiServiceAsyncClient + +__all__ = ( + 'NotificationsApiServiceClient', + 'NotificationsApiServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/async_client.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/async_client.py new file mode 100644 index 000000000000..6dd0a4e1ca9c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/async_client.py @@ -0,0 +1,836 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_notifications_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 + + +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_notifications_v1beta.services.notifications_api_service import pagers +from google.shopping.merchant_notifications_v1beta.types import notificationsapi +from .transports.base import NotificationsApiServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import NotificationsApiServiceGrpcAsyncIOTransport +from .client import NotificationsApiServiceClient + +try: + from google.api_core import client_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 NotificationsApiServiceAsyncClient: + """Service to manage notification subscriptions for merchants""" + + _client: NotificationsApiServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = NotificationsApiServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = NotificationsApiServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = NotificationsApiServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = NotificationsApiServiceClient._DEFAULT_UNIVERSE + + notification_subscription_path = staticmethod(NotificationsApiServiceClient.notification_subscription_path) + parse_notification_subscription_path = staticmethod(NotificationsApiServiceClient.parse_notification_subscription_path) + common_billing_account_path = staticmethod(NotificationsApiServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(NotificationsApiServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(NotificationsApiServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(NotificationsApiServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(NotificationsApiServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(NotificationsApiServiceClient.parse_common_organization_path) + common_project_path = staticmethod(NotificationsApiServiceClient.common_project_path) + parse_common_project_path = staticmethod(NotificationsApiServiceClient.parse_common_project_path) + common_location_path = staticmethod(NotificationsApiServiceClient.common_location_path) + parse_common_location_path = staticmethod(NotificationsApiServiceClient.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: + NotificationsApiServiceAsyncClient: The constructed client. + """ + return NotificationsApiServiceClient.from_service_account_info.__func__(NotificationsApiServiceAsyncClient, 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: + NotificationsApiServiceAsyncClient: The constructed client. + """ + return NotificationsApiServiceClient.from_service_account_file.__func__(NotificationsApiServiceAsyncClient, 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 NotificationsApiServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> NotificationsApiServiceTransport: + """Returns the transport used by the client instance. + + Returns: + NotificationsApiServiceTransport: 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 = NotificationsApiServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, NotificationsApiServiceTransport, Callable[..., NotificationsApiServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the notifications api 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,NotificationsApiServiceTransport,Callable[..., NotificationsApiServiceTransport]]]): + 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 NotificationsApiServiceTransport 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 = NotificationsApiServiceClient( + 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.notifications_v1beta.NotificationsApiServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", + "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.notifications.v1beta.NotificationsApiService", + "credentialsType": None, + } + ) + + async def get_notification_subscription(self, + request: Optional[Union[notificationsapi.GetNotificationSubscriptionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> notificationsapi.NotificationSubscription: + r"""Gets notification subscriptions for 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_notifications_v1beta + + async def sample_get_notification_subscription(): + # Create a client + client = merchant_notifications_v1beta.NotificationsApiServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_notifications_v1beta.GetNotificationSubscriptionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_notification_subscription(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_notifications_v1beta.types.GetNotificationSubscriptionRequest, dict]]): + The request object. Request message for the + GetNotificationSubscription method. + name (:class:`str`): + Required. The ``name`` of the notification subscription. + 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_notifications_v1beta.types.NotificationSubscription: + Represents a notification + subscription 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, notificationsapi.GetNotificationSubscriptionRequest): + request = notificationsapi.GetNotificationSubscriptionRequest(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_notification_subscription] + + # Certain 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_notification_subscription(self, + request: Optional[Union[notificationsapi.CreateNotificationSubscriptionRequest, dict]] = None, + *, + parent: Optional[str] = None, + notification_subscription: Optional[notificationsapi.NotificationSubscription] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> notificationsapi.NotificationSubscription: + r"""Creates a notification subscription for a merchant. + We will allow the following types of notification + subscriptions to exist together (per merchant as a + subscriber per event type): + + 1. Subscription for all managed accounts + subscription + for self + 2. Multiple "partial" subscriptions for managed accounts + + subscription for self + + we will not allow (per merchant as a subscriber per + event type): + + 1. multiple self subscriptions. + 2. multiple "all managed accounts" subscriptions. + 3. all and partial subscriptions at the same time. + 4. multiple partial subscriptions for the same target + 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_notifications_v1beta + + async def sample_create_notification_subscription(): + # Create a client + client = merchant_notifications_v1beta.NotificationsApiServiceAsyncClient() + + # Initialize request argument(s) + notification_subscription = merchant_notifications_v1beta.NotificationSubscription() + notification_subscription.all_managed_accounts = True + + request = merchant_notifications_v1beta.CreateNotificationSubscriptionRequest( + parent="parent_value", + notification_subscription=notification_subscription, + ) + + # Make the request + response = await client.create_notification_subscription(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_notifications_v1beta.types.CreateNotificationSubscriptionRequest, dict]]): + The request object. Request message for the + CreateNotificationSubscription method. + parent (:class:`str`): + Required. The merchant account that owns the new + notification subscription. Format: + ``accounts/{account}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + notification_subscription (:class:`google.shopping.merchant_notifications_v1beta.types.NotificationSubscription`): + Required. The notification + subscription to create. + + This corresponds to the ``notification_subscription`` 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_notifications_v1beta.types.NotificationSubscription: + Represents a notification + subscription 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. + has_flattened_params = any([parent, notification_subscription]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, notificationsapi.CreateNotificationSubscriptionRequest): + request = notificationsapi.CreateNotificationSubscriptionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if notification_subscription is not None: + request.notification_subscription = notification_subscription + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_notification_subscription] + + # Certain 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_notification_subscription(self, + request: Optional[Union[notificationsapi.UpdateNotificationSubscriptionRequest, dict]] = None, + *, + notification_subscription: Optional[notificationsapi.NotificationSubscription] = 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]]] = (), + ) -> notificationsapi.NotificationSubscription: + r"""Updates an existing notification subscription 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_notifications_v1beta + + async def sample_update_notification_subscription(): + # Create a client + client = merchant_notifications_v1beta.NotificationsApiServiceAsyncClient() + + # Initialize request argument(s) + notification_subscription = merchant_notifications_v1beta.NotificationSubscription() + notification_subscription.all_managed_accounts = True + + request = merchant_notifications_v1beta.UpdateNotificationSubscriptionRequest( + notification_subscription=notification_subscription, + ) + + # Make the request + response = await client.update_notification_subscription(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_notifications_v1beta.types.UpdateNotificationSubscriptionRequest, dict]]): + The request object. Request message for the + UpdateNotificationSubscription method. + notification_subscription (:class:`google.shopping.merchant_notifications_v1beta.types.NotificationSubscription`): + Required. The new version of the + notification subscription that should be + updated. + + This corresponds to the ``notification_subscription`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + 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_notifications_v1beta.types.NotificationSubscription: + Represents a notification + subscription 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. + has_flattened_params = any([notification_subscription, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, notificationsapi.UpdateNotificationSubscriptionRequest): + request = notificationsapi.UpdateNotificationSubscriptionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if notification_subscription is not None: + request.notification_subscription = notification_subscription + 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_notification_subscription] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("notification_subscription.name", request.notification_subscription.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_notification_subscription(self, + request: Optional[Union[notificationsapi.DeleteNotificationSubscriptionRequest, dict]] = None, + *, + name: Optional[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 notification subscription 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_notifications_v1beta + + async def sample_delete_notification_subscription(): + # Create a client + client = merchant_notifications_v1beta.NotificationsApiServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_notifications_v1beta.DeleteNotificationSubscriptionRequest( + name="name_value", + ) + + # Make the request + await client.delete_notification_subscription(request=request) + + Args: + request (Optional[Union[google.shopping.merchant_notifications_v1beta.types.DeleteNotificationSubscriptionRequest, dict]]): + The request object. Request message for the + DeleteNotificationSubscription method. + name (:class:`str`): + Required. The name of the + notification subscription to be deleted. + + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, notificationsapi.DeleteNotificationSubscriptionRequest): + request = notificationsapi.DeleteNotificationSubscriptionRequest(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_notification_subscription] + + # Certain 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_notification_subscriptions(self, + request: Optional[Union[notificationsapi.ListNotificationSubscriptionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListNotificationSubscriptionsAsyncPager: + r"""Gets all the notification subscriptions 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_notifications_v1beta + + async def sample_list_notification_subscriptions(): + # Create a client + client = merchant_notifications_v1beta.NotificationsApiServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_notifications_v1beta.ListNotificationSubscriptionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_notification_subscriptions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_notifications_v1beta.types.ListNotificationSubscriptionsRequest, dict]]): + The request object. Request message for the + ListNotificationSubscription method. + parent (:class:`str`): + Required. The merchant account who owns the notification + subscriptions. 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_notifications_v1beta.services.notifications_api_service.pagers.ListNotificationSubscriptionsAsyncPager: + Response message for the + ListNotificationSubscription 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, notificationsapi.ListNotificationSubscriptionsRequest): + request = notificationsapi.ListNotificationSubscriptionsRequest(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_notification_subscriptions] + + # Certain 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.ListNotificationSubscriptionsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "NotificationsApiServiceAsyncClient": + 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__) + + +__all__ = ( + "NotificationsApiServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/client.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/client.py new file mode 100644 index 000000000000..cd34d69acb8c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/client.py @@ -0,0 +1,1167 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +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_notifications_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 + +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_notifications_v1beta.services.notifications_api_service import pagers +from google.shopping.merchant_notifications_v1beta.types import notificationsapi +from .transports.base import NotificationsApiServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import NotificationsApiServiceGrpcTransport +from .transports.grpc_asyncio import NotificationsApiServiceGrpcAsyncIOTransport +from .transports.rest import NotificationsApiServiceRestTransport + + +class NotificationsApiServiceClientMeta(type): + """Metaclass for the NotificationsApiService 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[NotificationsApiServiceTransport]] + _transport_registry["grpc"] = NotificationsApiServiceGrpcTransport + _transport_registry["grpc_asyncio"] = NotificationsApiServiceGrpcAsyncIOTransport + _transport_registry["rest"] = NotificationsApiServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[NotificationsApiServiceTransport]: + """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 NotificationsApiServiceClient(metaclass=NotificationsApiServiceClientMeta): + """Service to manage notification subscriptions for merchants""" + + @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: + NotificationsApiServiceClient: 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: + NotificationsApiServiceClient: 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) -> NotificationsApiServiceTransport: + """Returns the transport used by the client instance. + + Returns: + NotificationsApiServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def notification_subscription_path(account: str,notification_subscription: str,) -> str: + """Returns a fully-qualified notification_subscription string.""" + return "accounts/{account}/notificationsubscriptions/{notification_subscription}".format(account=account, notification_subscription=notification_subscription, ) + + @staticmethod + def parse_notification_subscription_path(path: str) -> Dict[str,str]: + """Parses a notification_subscription path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/notificationsubscriptions/(?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 = NotificationsApiServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = NotificationsApiServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = NotificationsApiServiceClient._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 = NotificationsApiServiceClient._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 + + @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, NotificationsApiServiceTransport, Callable[..., NotificationsApiServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the notifications api 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,NotificationsApiServiceTransport,Callable[..., NotificationsApiServiceTransport]]]): + 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 NotificationsApiServiceTransport 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 = NotificationsApiServiceClient._read_environment_variables() + self._client_cert_source = NotificationsApiServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = NotificationsApiServiceClient._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, NotificationsApiServiceTransport) + if transport_provided: + # transport is a NotificationsApiServiceTransport 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(NotificationsApiServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + NotificationsApiServiceClient._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[NotificationsApiServiceTransport], Callable[..., NotificationsApiServiceTransport]] = ( + NotificationsApiServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., NotificationsApiServiceTransport], 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.notifications_v1beta.NotificationsApiServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", + "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.notifications.v1beta.NotificationsApiService", + "credentialsType": None, + } + ) + + def get_notification_subscription(self, + request: Optional[Union[notificationsapi.GetNotificationSubscriptionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> notificationsapi.NotificationSubscription: + r"""Gets notification subscriptions for 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_notifications_v1beta + + def sample_get_notification_subscription(): + # Create a client + client = merchant_notifications_v1beta.NotificationsApiServiceClient() + + # Initialize request argument(s) + request = merchant_notifications_v1beta.GetNotificationSubscriptionRequest( + name="name_value", + ) + + # Make the request + response = client.get_notification_subscription(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_notifications_v1beta.types.GetNotificationSubscriptionRequest, dict]): + The request object. Request message for the + GetNotificationSubscription method. + name (str): + Required. The ``name`` of the notification subscription. + 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_notifications_v1beta.types.NotificationSubscription: + Represents a notification + subscription 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, notificationsapi.GetNotificationSubscriptionRequest): + request = notificationsapi.GetNotificationSubscriptionRequest(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_notification_subscription] + + # Certain 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_notification_subscription(self, + request: Optional[Union[notificationsapi.CreateNotificationSubscriptionRequest, dict]] = None, + *, + parent: Optional[str] = None, + notification_subscription: Optional[notificationsapi.NotificationSubscription] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> notificationsapi.NotificationSubscription: + r"""Creates a notification subscription for a merchant. + We will allow the following types of notification + subscriptions to exist together (per merchant as a + subscriber per event type): + + 1. Subscription for all managed accounts + subscription + for self + 2. Multiple "partial" subscriptions for managed accounts + + subscription for self + + we will not allow (per merchant as a subscriber per + event type): + + 1. multiple self subscriptions. + 2. multiple "all managed accounts" subscriptions. + 3. all and partial subscriptions at the same time. + 4. multiple partial subscriptions for the same target + 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_notifications_v1beta + + def sample_create_notification_subscription(): + # Create a client + client = merchant_notifications_v1beta.NotificationsApiServiceClient() + + # Initialize request argument(s) + notification_subscription = merchant_notifications_v1beta.NotificationSubscription() + notification_subscription.all_managed_accounts = True + + request = merchant_notifications_v1beta.CreateNotificationSubscriptionRequest( + parent="parent_value", + notification_subscription=notification_subscription, + ) + + # Make the request + response = client.create_notification_subscription(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_notifications_v1beta.types.CreateNotificationSubscriptionRequest, dict]): + The request object. Request message for the + CreateNotificationSubscription method. + parent (str): + Required. The merchant account that owns the new + notification subscription. Format: + ``accounts/{account}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + notification_subscription (google.shopping.merchant_notifications_v1beta.types.NotificationSubscription): + Required. The notification + subscription to create. + + This corresponds to the ``notification_subscription`` 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_notifications_v1beta.types.NotificationSubscription: + Represents a notification + subscription 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. + has_flattened_params = any([parent, notification_subscription]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, notificationsapi.CreateNotificationSubscriptionRequest): + request = notificationsapi.CreateNotificationSubscriptionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if notification_subscription is not None: + request.notification_subscription = notification_subscription + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_notification_subscription] + + # Certain 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_notification_subscription(self, + request: Optional[Union[notificationsapi.UpdateNotificationSubscriptionRequest, dict]] = None, + *, + notification_subscription: Optional[notificationsapi.NotificationSubscription] = 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]]] = (), + ) -> notificationsapi.NotificationSubscription: + r"""Updates an existing notification subscription 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_notifications_v1beta + + def sample_update_notification_subscription(): + # Create a client + client = merchant_notifications_v1beta.NotificationsApiServiceClient() + + # Initialize request argument(s) + notification_subscription = merchant_notifications_v1beta.NotificationSubscription() + notification_subscription.all_managed_accounts = True + + request = merchant_notifications_v1beta.UpdateNotificationSubscriptionRequest( + notification_subscription=notification_subscription, + ) + + # Make the request + response = client.update_notification_subscription(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_notifications_v1beta.types.UpdateNotificationSubscriptionRequest, dict]): + The request object. Request message for the + UpdateNotificationSubscription method. + notification_subscription (google.shopping.merchant_notifications_v1beta.types.NotificationSubscription): + Required. The new version of the + notification subscription that should be + updated. + + This corresponds to the ``notification_subscription`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + 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_notifications_v1beta.types.NotificationSubscription: + Represents a notification + subscription 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. + has_flattened_params = any([notification_subscription, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, notificationsapi.UpdateNotificationSubscriptionRequest): + request = notificationsapi.UpdateNotificationSubscriptionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if notification_subscription is not None: + request.notification_subscription = notification_subscription + 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_notification_subscription] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("notification_subscription.name", request.notification_subscription.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_notification_subscription(self, + request: Optional[Union[notificationsapi.DeleteNotificationSubscriptionRequest, dict]] = None, + *, + name: Optional[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 notification subscription 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_notifications_v1beta + + def sample_delete_notification_subscription(): + # Create a client + client = merchant_notifications_v1beta.NotificationsApiServiceClient() + + # Initialize request argument(s) + request = merchant_notifications_v1beta.DeleteNotificationSubscriptionRequest( + name="name_value", + ) + + # Make the request + client.delete_notification_subscription(request=request) + + Args: + request (Union[google.shopping.merchant_notifications_v1beta.types.DeleteNotificationSubscriptionRequest, dict]): + The request object. Request message for the + DeleteNotificationSubscription method. + name (str): + Required. The name of the + notification subscription to be deleted. + + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, notificationsapi.DeleteNotificationSubscriptionRequest): + request = notificationsapi.DeleteNotificationSubscriptionRequest(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_notification_subscription] + + # Certain 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_notification_subscriptions(self, + request: Optional[Union[notificationsapi.ListNotificationSubscriptionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListNotificationSubscriptionsPager: + r"""Gets all the notification subscriptions 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_notifications_v1beta + + def sample_list_notification_subscriptions(): + # Create a client + client = merchant_notifications_v1beta.NotificationsApiServiceClient() + + # Initialize request argument(s) + request = merchant_notifications_v1beta.ListNotificationSubscriptionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_notification_subscriptions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.shopping.merchant_notifications_v1beta.types.ListNotificationSubscriptionsRequest, dict]): + The request object. Request message for the + ListNotificationSubscription method. + parent (str): + Required. The merchant account who owns the notification + subscriptions. 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_notifications_v1beta.services.notifications_api_service.pagers.ListNotificationSubscriptionsPager: + Response message for the + ListNotificationSubscription 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, notificationsapi.ListNotificationSubscriptionsRequest): + request = notificationsapi.ListNotificationSubscriptionsRequest(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_notification_subscriptions] + + # Certain 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.ListNotificationSubscriptionsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "NotificationsApiServiceClient": + 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__) + + +__all__ = ( + "NotificationsApiServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/pagers.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/pagers.py new file mode 100644 index 000000000000..9184edf322ec --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/pagers.py @@ -0,0 +1,166 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_notifications_v1beta.types import notificationsapi + + +class ListNotificationSubscriptionsPager: + """A pager for iterating through ``list_notification_subscriptions`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_notifications_v1beta.types.ListNotificationSubscriptionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``notification_subscriptions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListNotificationSubscriptions`` requests and continue to iterate + through the ``notification_subscriptions`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_notifications_v1beta.types.ListNotificationSubscriptionsResponse` + 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[..., notificationsapi.ListNotificationSubscriptionsResponse], + request: notificationsapi.ListNotificationSubscriptionsRequest, + response: notificationsapi.ListNotificationSubscriptionsResponse, + *, + 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_notifications_v1beta.types.ListNotificationSubscriptionsRequest): + The initial request object. + response (google.shopping.merchant_notifications_v1beta.types.ListNotificationSubscriptionsResponse): + 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 = notificationsapi.ListNotificationSubscriptionsRequest(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[notificationsapi.ListNotificationSubscriptionsResponse]: + 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[notificationsapi.NotificationSubscription]: + for page in self.pages: + yield from page.notification_subscriptions + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListNotificationSubscriptionsAsyncPager: + """A pager for iterating through ``list_notification_subscriptions`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_notifications_v1beta.types.ListNotificationSubscriptionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``notification_subscriptions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListNotificationSubscriptions`` requests and continue to iterate + through the ``notification_subscriptions`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_notifications_v1beta.types.ListNotificationSubscriptionsResponse` + 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[notificationsapi.ListNotificationSubscriptionsResponse]], + request: notificationsapi.ListNotificationSubscriptionsRequest, + response: notificationsapi.ListNotificationSubscriptionsResponse, + *, + 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_notifications_v1beta.types.ListNotificationSubscriptionsRequest): + The initial request object. + response (google.shopping.merchant_notifications_v1beta.types.ListNotificationSubscriptionsResponse): + 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 = notificationsapi.ListNotificationSubscriptionsRequest(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[notificationsapi.ListNotificationSubscriptionsResponse]: + 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[notificationsapi.NotificationSubscription]: + async def async_generator(): + async for page in self.pages: + for response in page.notification_subscriptions: + 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-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/README.rst new file mode 100644 index 000000000000..e82a831890a4 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`NotificationsApiServiceTransport` is the ABC for all transports. +- public child `NotificationsApiServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `NotificationsApiServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseNotificationsApiServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `NotificationsApiServiceRestTransport` 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-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/__init__.py new file mode 100644 index 000000000000..fbc95bf86509 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 NotificationsApiServiceTransport +from .grpc import NotificationsApiServiceGrpcTransport +from .grpc_asyncio import NotificationsApiServiceGrpcAsyncIOTransport +from .rest import NotificationsApiServiceRestTransport +from .rest import NotificationsApiServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[NotificationsApiServiceTransport]] +_transport_registry['grpc'] = NotificationsApiServiceGrpcTransport +_transport_registry['grpc_asyncio'] = NotificationsApiServiceGrpcAsyncIOTransport +_transport_registry['rest'] = NotificationsApiServiceRestTransport + +__all__ = ( + 'NotificationsApiServiceTransport', + 'NotificationsApiServiceGrpcTransport', + 'NotificationsApiServiceGrpcAsyncIOTransport', + 'NotificationsApiServiceRestTransport', + 'NotificationsApiServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/base.py new file mode 100644 index 000000000000..4b8680eaaea3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/base.py @@ -0,0 +1,211 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_notifications_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 + +from google.protobuf import empty_pb2 # type: ignore +from google.shopping.merchant_notifications_v1beta.types import notificationsapi + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class NotificationsApiServiceTransport(abc.ABC): + """Abstract transport class for NotificationsApiService.""" + + 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_notification_subscription: gapic_v1.method.wrap_method( + self.get_notification_subscription, + default_timeout=None, + client_info=client_info, + ), + self.create_notification_subscription: gapic_v1.method.wrap_method( + self.create_notification_subscription, + default_timeout=None, + client_info=client_info, + ), + self.update_notification_subscription: gapic_v1.method.wrap_method( + self.update_notification_subscription, + default_timeout=None, + client_info=client_info, + ), + self.delete_notification_subscription: gapic_v1.method.wrap_method( + self.delete_notification_subscription, + default_timeout=None, + client_info=client_info, + ), + self.list_notification_subscriptions: gapic_v1.method.wrap_method( + self.list_notification_subscriptions, + 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_notification_subscription(self) -> Callable[ + [notificationsapi.GetNotificationSubscriptionRequest], + Union[ + notificationsapi.NotificationSubscription, + Awaitable[notificationsapi.NotificationSubscription] + ]]: + raise NotImplementedError() + + @property + def create_notification_subscription(self) -> Callable[ + [notificationsapi.CreateNotificationSubscriptionRequest], + Union[ + notificationsapi.NotificationSubscription, + Awaitable[notificationsapi.NotificationSubscription] + ]]: + raise NotImplementedError() + + @property + def update_notification_subscription(self) -> Callable[ + [notificationsapi.UpdateNotificationSubscriptionRequest], + Union[ + notificationsapi.NotificationSubscription, + Awaitable[notificationsapi.NotificationSubscription] + ]]: + raise NotImplementedError() + + @property + def delete_notification_subscription(self) -> Callable[ + [notificationsapi.DeleteNotificationSubscriptionRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def list_notification_subscriptions(self) -> Callable[ + [notificationsapi.ListNotificationSubscriptionsRequest], + Union[ + notificationsapi.ListNotificationSubscriptionsResponse, + Awaitable[notificationsapi.ListNotificationSubscriptionsResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'NotificationsApiServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/grpc.py new file mode 100644 index 000000000000..46e0337f5471 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/grpc.py @@ -0,0 +1,475 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_notifications_v1beta.types import notificationsapi +from .base import NotificationsApiServiceTransport, 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.notifications.v1beta.NotificationsApiService", + "rpcName": 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.notifications.v1beta.NotificationsApiService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class NotificationsApiServiceGrpcTransport(NotificationsApiServiceTransport): + """gRPC backend transport for NotificationsApiService. + + Service to manage notification subscriptions for merchants + + This 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_notification_subscription(self) -> Callable[ + [notificationsapi.GetNotificationSubscriptionRequest], + notificationsapi.NotificationSubscription]: + r"""Return a callable for the get notification subscription method over gRPC. + + Gets notification subscriptions for an account. + + Returns: + Callable[[~.GetNotificationSubscriptionRequest], + ~.NotificationSubscription]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_notification_subscription' not in self._stubs: + self._stubs['get_notification_subscription'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.notifications.v1beta.NotificationsApiService/GetNotificationSubscription', + request_serializer=notificationsapi.GetNotificationSubscriptionRequest.serialize, + response_deserializer=notificationsapi.NotificationSubscription.deserialize, + ) + return self._stubs['get_notification_subscription'] + + @property + def create_notification_subscription(self) -> Callable[ + [notificationsapi.CreateNotificationSubscriptionRequest], + notificationsapi.NotificationSubscription]: + r"""Return a callable for the create notification + subscription method over gRPC. + + Creates a notification subscription for a merchant. + We will allow the following types of notification + subscriptions to exist together (per merchant as a + subscriber per event type): + + 1. Subscription for all managed accounts + subscription + for self + 2. Multiple "partial" subscriptions for managed accounts + + subscription for self + + we will not allow (per merchant as a subscriber per + event type): + + 1. multiple self subscriptions. + 2. multiple "all managed accounts" subscriptions. + 3. all and partial subscriptions at the same time. + 4. multiple partial subscriptions for the same target + account + + Returns: + Callable[[~.CreateNotificationSubscriptionRequest], + ~.NotificationSubscription]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_notification_subscription' not in self._stubs: + self._stubs['create_notification_subscription'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.notifications.v1beta.NotificationsApiService/CreateNotificationSubscription', + request_serializer=notificationsapi.CreateNotificationSubscriptionRequest.serialize, + response_deserializer=notificationsapi.NotificationSubscription.deserialize, + ) + return self._stubs['create_notification_subscription'] + + @property + def update_notification_subscription(self) -> Callable[ + [notificationsapi.UpdateNotificationSubscriptionRequest], + notificationsapi.NotificationSubscription]: + r"""Return a callable for the update notification + subscription method over gRPC. + + Updates an existing notification subscription for a + merchant. + + Returns: + Callable[[~.UpdateNotificationSubscriptionRequest], + ~.NotificationSubscription]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_notification_subscription' not in self._stubs: + self._stubs['update_notification_subscription'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.notifications.v1beta.NotificationsApiService/UpdateNotificationSubscription', + request_serializer=notificationsapi.UpdateNotificationSubscriptionRequest.serialize, + response_deserializer=notificationsapi.NotificationSubscription.deserialize, + ) + return self._stubs['update_notification_subscription'] + + @property + def delete_notification_subscription(self) -> Callable[ + [notificationsapi.DeleteNotificationSubscriptionRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete notification + subscription method over gRPC. + + Deletes a notification subscription for a merchant. + + Returns: + Callable[[~.DeleteNotificationSubscriptionRequest], + ~.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_notification_subscription' not in self._stubs: + self._stubs['delete_notification_subscription'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.notifications.v1beta.NotificationsApiService/DeleteNotificationSubscription', + request_serializer=notificationsapi.DeleteNotificationSubscriptionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_notification_subscription'] + + @property + def list_notification_subscriptions(self) -> Callable[ + [notificationsapi.ListNotificationSubscriptionsRequest], + notificationsapi.ListNotificationSubscriptionsResponse]: + r"""Return a callable for the list notification + subscriptions method over gRPC. + + Gets all the notification subscriptions for a + merchant. + + Returns: + Callable[[~.ListNotificationSubscriptionsRequest], + ~.ListNotificationSubscriptionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_notification_subscriptions' not in self._stubs: + self._stubs['list_notification_subscriptions'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.notifications.v1beta.NotificationsApiService/ListNotificationSubscriptions', + request_serializer=notificationsapi.ListNotificationSubscriptionsRequest.serialize, + response_deserializer=notificationsapi.ListNotificationSubscriptionsResponse.deserialize, + ) + return self._stubs['list_notification_subscriptions'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'NotificationsApiServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..dd19eebdba6c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/grpc_asyncio.py @@ -0,0 +1,515 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_notifications_v1beta.types import notificationsapi +from .base import NotificationsApiServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import NotificationsApiServiceGrpcTransport + +try: + from google.api_core import client_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.notifications.v1beta.NotificationsApiService", + "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.notifications.v1beta.NotificationsApiService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class NotificationsApiServiceGrpcAsyncIOTransport(NotificationsApiServiceTransport): + """gRPC AsyncIO backend transport for NotificationsApiService. + + Service to manage notification subscriptions for merchants + + This 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_notification_subscription(self) -> Callable[ + [notificationsapi.GetNotificationSubscriptionRequest], + Awaitable[notificationsapi.NotificationSubscription]]: + r"""Return a callable for the get notification subscription method over gRPC. + + Gets notification subscriptions for an account. + + Returns: + Callable[[~.GetNotificationSubscriptionRequest], + Awaitable[~.NotificationSubscription]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_notification_subscription' not in self._stubs: + self._stubs['get_notification_subscription'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.notifications.v1beta.NotificationsApiService/GetNotificationSubscription', + request_serializer=notificationsapi.GetNotificationSubscriptionRequest.serialize, + response_deserializer=notificationsapi.NotificationSubscription.deserialize, + ) + return self._stubs['get_notification_subscription'] + + @property + def create_notification_subscription(self) -> Callable[ + [notificationsapi.CreateNotificationSubscriptionRequest], + Awaitable[notificationsapi.NotificationSubscription]]: + r"""Return a callable for the create notification + subscription method over gRPC. + + Creates a notification subscription for a merchant. + We will allow the following types of notification + subscriptions to exist together (per merchant as a + subscriber per event type): + + 1. Subscription for all managed accounts + subscription + for self + 2. Multiple "partial" subscriptions for managed accounts + + subscription for self + + we will not allow (per merchant as a subscriber per + event type): + + 1. multiple self subscriptions. + 2. multiple "all managed accounts" subscriptions. + 3. all and partial subscriptions at the same time. + 4. multiple partial subscriptions for the same target + account + + Returns: + Callable[[~.CreateNotificationSubscriptionRequest], + Awaitable[~.NotificationSubscription]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_notification_subscription' not in self._stubs: + self._stubs['create_notification_subscription'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.notifications.v1beta.NotificationsApiService/CreateNotificationSubscription', + request_serializer=notificationsapi.CreateNotificationSubscriptionRequest.serialize, + response_deserializer=notificationsapi.NotificationSubscription.deserialize, + ) + return self._stubs['create_notification_subscription'] + + @property + def update_notification_subscription(self) -> Callable[ + [notificationsapi.UpdateNotificationSubscriptionRequest], + Awaitable[notificationsapi.NotificationSubscription]]: + r"""Return a callable for the update notification + subscription method over gRPC. + + Updates an existing notification subscription for a + merchant. + + Returns: + Callable[[~.UpdateNotificationSubscriptionRequest], + Awaitable[~.NotificationSubscription]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_notification_subscription' not in self._stubs: + self._stubs['update_notification_subscription'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.notifications.v1beta.NotificationsApiService/UpdateNotificationSubscription', + request_serializer=notificationsapi.UpdateNotificationSubscriptionRequest.serialize, + response_deserializer=notificationsapi.NotificationSubscription.deserialize, + ) + return self._stubs['update_notification_subscription'] + + @property + def delete_notification_subscription(self) -> Callable[ + [notificationsapi.DeleteNotificationSubscriptionRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete notification + subscription method over gRPC. + + Deletes a notification subscription for a merchant. + + Returns: + Callable[[~.DeleteNotificationSubscriptionRequest], + 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_notification_subscription' not in self._stubs: + self._stubs['delete_notification_subscription'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.notifications.v1beta.NotificationsApiService/DeleteNotificationSubscription', + request_serializer=notificationsapi.DeleteNotificationSubscriptionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_notification_subscription'] + + @property + def list_notification_subscriptions(self) -> Callable[ + [notificationsapi.ListNotificationSubscriptionsRequest], + Awaitable[notificationsapi.ListNotificationSubscriptionsResponse]]: + r"""Return a callable for the list notification + subscriptions method over gRPC. + + Gets all the notification subscriptions for a + merchant. + + Returns: + Callable[[~.ListNotificationSubscriptionsRequest], + Awaitable[~.ListNotificationSubscriptionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_notification_subscriptions' not in self._stubs: + self._stubs['list_notification_subscriptions'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.notifications.v1beta.NotificationsApiService/ListNotificationSubscriptions', + request_serializer=notificationsapi.ListNotificationSubscriptionsRequest.serialize, + response_deserializer=notificationsapi.ListNotificationSubscriptionsResponse.deserialize, + ) + return self._stubs['list_notification_subscriptions'] + + 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_notification_subscription: self._wrap_method( + self.get_notification_subscription, + default_timeout=None, + client_info=client_info, + ), + self.create_notification_subscription: self._wrap_method( + self.create_notification_subscription, + default_timeout=None, + client_info=client_info, + ), + self.update_notification_subscription: self._wrap_method( + self.update_notification_subscription, + default_timeout=None, + client_info=client_info, + ), + self.delete_notification_subscription: self._wrap_method( + self.delete_notification_subscription, + default_timeout=None, + client_info=client_info, + ), + self.list_notification_subscriptions: self._wrap_method( + self.list_notification_subscriptions, + 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__ = ( + 'NotificationsApiServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/rest.py new file mode 100644 index 000000000000..1b7eb10db2be --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/rest.py @@ -0,0 +1,909 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +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_notifications_v1beta.types import notificationsapi + + +from .rest_base import _BaseNotificationsApiServiceRestTransport +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}", +) + + +class NotificationsApiServiceRestInterceptor: + """Interceptor for NotificationsApiService. + + 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 NotificationsApiServiceRestTransport. + + .. code-block:: python + class MyCustomNotificationsApiServiceInterceptor(NotificationsApiServiceRestInterceptor): + def pre_create_notification_subscription(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_notification_subscription(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_notification_subscription(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_notification_subscription(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_notification_subscription(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_notification_subscriptions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_notification_subscriptions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_notification_subscription(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_notification_subscription(self, response): + logging.log(f"Received response: {response}") + return response + + transport = NotificationsApiServiceRestTransport(interceptor=MyCustomNotificationsApiServiceInterceptor()) + client = NotificationsApiServiceClient(transport=transport) + + + """ + def pre_create_notification_subscription(self, request: notificationsapi.CreateNotificationSubscriptionRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[notificationsapi.CreateNotificationSubscriptionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_notification_subscription + + Override in a subclass to manipulate the request or metadata + before they are sent to the NotificationsApiService server. + """ + return request, metadata + + def post_create_notification_subscription(self, response: notificationsapi.NotificationSubscription) -> notificationsapi.NotificationSubscription: + """Post-rpc interceptor for create_notification_subscription + + Override in a subclass to manipulate the response + after it is returned by the NotificationsApiService server but before + it is returned to user code. + """ + return response + + def pre_delete_notification_subscription(self, request: notificationsapi.DeleteNotificationSubscriptionRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[notificationsapi.DeleteNotificationSubscriptionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_notification_subscription + + Override in a subclass to manipulate the request or metadata + before they are sent to the NotificationsApiService server. + """ + return request, metadata + + def pre_get_notification_subscription(self, request: notificationsapi.GetNotificationSubscriptionRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[notificationsapi.GetNotificationSubscriptionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_notification_subscription + + Override in a subclass to manipulate the request or metadata + before they are sent to the NotificationsApiService server. + """ + return request, metadata + + def post_get_notification_subscription(self, response: notificationsapi.NotificationSubscription) -> notificationsapi.NotificationSubscription: + """Post-rpc interceptor for get_notification_subscription + + Override in a subclass to manipulate the response + after it is returned by the NotificationsApiService server but before + it is returned to user code. + """ + return response + + def pre_list_notification_subscriptions(self, request: notificationsapi.ListNotificationSubscriptionsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[notificationsapi.ListNotificationSubscriptionsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_notification_subscriptions + + Override in a subclass to manipulate the request or metadata + before they are sent to the NotificationsApiService server. + """ + return request, metadata + + def post_list_notification_subscriptions(self, response: notificationsapi.ListNotificationSubscriptionsResponse) -> notificationsapi.ListNotificationSubscriptionsResponse: + """Post-rpc interceptor for list_notification_subscriptions + + Override in a subclass to manipulate the response + after it is returned by the NotificationsApiService server but before + it is returned to user code. + """ + return response + + def pre_update_notification_subscription(self, request: notificationsapi.UpdateNotificationSubscriptionRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[notificationsapi.UpdateNotificationSubscriptionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_notification_subscription + + Override in a subclass to manipulate the request or metadata + before they are sent to the NotificationsApiService server. + """ + return request, metadata + + def post_update_notification_subscription(self, response: notificationsapi.NotificationSubscription) -> notificationsapi.NotificationSubscription: + """Post-rpc interceptor for update_notification_subscription + + Override in a subclass to manipulate the response + after it is returned by the NotificationsApiService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class NotificationsApiServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: NotificationsApiServiceRestInterceptor + + +class NotificationsApiServiceRestTransport(_BaseNotificationsApiServiceRestTransport): + """REST backend synchronous transport for NotificationsApiService. + + Service to manage notification subscriptions for merchants + + This 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[NotificationsApiServiceRestInterceptor] = 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 NotificationsApiServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateNotificationSubscription(_BaseNotificationsApiServiceRestTransport._BaseCreateNotificationSubscription, NotificationsApiServiceRestStub): + def __hash__(self): + return hash("NotificationsApiServiceRestTransport.CreateNotificationSubscription") + + @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: notificationsapi.CreateNotificationSubscriptionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> notificationsapi.NotificationSubscription: + r"""Call the create notification + subscription method over HTTP. + + Args: + request (~.notificationsapi.CreateNotificationSubscriptionRequest): + The request object. Request message for the + CreateNotificationSubscription method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.notificationsapi.NotificationSubscription: + Represents a notification + subscription owned by a Merchant + account. + + """ + + http_options = _BaseNotificationsApiServiceRestTransport._BaseCreateNotificationSubscription._get_http_options() + + request, metadata = self._interceptor.pre_create_notification_subscription(request, metadata) + transcoded_request = _BaseNotificationsApiServiceRestTransport._BaseCreateNotificationSubscription._get_transcoded_request(http_options, request) + + body = _BaseNotificationsApiServiceRestTransport._BaseCreateNotificationSubscription._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseNotificationsApiServiceRestTransport._BaseCreateNotificationSubscription._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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.notifications_v1beta.NotificationsApiServiceClient.CreateNotificationSubscription", + extra = { + "serviceName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", + "rpcName": "CreateNotificationSubscription", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NotificationsApiServiceRestTransport._CreateNotificationSubscription._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 = notificationsapi.NotificationSubscription() + pb_resp = notificationsapi.NotificationSubscription.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_notification_subscription(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = notificationsapi.NotificationSubscription.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.notifications_v1beta.NotificationsApiServiceClient.create_notification_subscription", + extra = { + "serviceName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", + "rpcName": "CreateNotificationSubscription", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteNotificationSubscription(_BaseNotificationsApiServiceRestTransport._BaseDeleteNotificationSubscription, NotificationsApiServiceRestStub): + def __hash__(self): + return hash("NotificationsApiServiceRestTransport.DeleteNotificationSubscription") + + @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: notificationsapi.DeleteNotificationSubscriptionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): + r"""Call the delete notification + subscription method over HTTP. + + Args: + request (~.notificationsapi.DeleteNotificationSubscriptionRequest): + The request object. Request message for the + DeleteNotificationSubscription method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 = _BaseNotificationsApiServiceRestTransport._BaseDeleteNotificationSubscription._get_http_options() + + request, metadata = self._interceptor.pre_delete_notification_subscription(request, metadata) + transcoded_request = _BaseNotificationsApiServiceRestTransport._BaseDeleteNotificationSubscription._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseNotificationsApiServiceRestTransport._BaseDeleteNotificationSubscription._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(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.notifications_v1beta.NotificationsApiServiceClient.DeleteNotificationSubscription", + extra = { + "serviceName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", + "rpcName": "DeleteNotificationSubscription", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NotificationsApiServiceRestTransport._DeleteNotificationSubscription._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 _GetNotificationSubscription(_BaseNotificationsApiServiceRestTransport._BaseGetNotificationSubscription, NotificationsApiServiceRestStub): + def __hash__(self): + return hash("NotificationsApiServiceRestTransport.GetNotificationSubscription") + + @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: notificationsapi.GetNotificationSubscriptionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> notificationsapi.NotificationSubscription: + r"""Call the get notification + subscription method over HTTP. + + Args: + request (~.notificationsapi.GetNotificationSubscriptionRequest): + The request object. Request message for the + GetNotificationSubscription method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.notificationsapi.NotificationSubscription: + Represents a notification + subscription owned by a Merchant + account. + + """ + + http_options = _BaseNotificationsApiServiceRestTransport._BaseGetNotificationSubscription._get_http_options() + + request, metadata = self._interceptor.pre_get_notification_subscription(request, metadata) + transcoded_request = _BaseNotificationsApiServiceRestTransport._BaseGetNotificationSubscription._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseNotificationsApiServiceRestTransport._BaseGetNotificationSubscription._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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.notifications_v1beta.NotificationsApiServiceClient.GetNotificationSubscription", + extra = { + "serviceName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", + "rpcName": "GetNotificationSubscription", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NotificationsApiServiceRestTransport._GetNotificationSubscription._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 = notificationsapi.NotificationSubscription() + pb_resp = notificationsapi.NotificationSubscription.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_notification_subscription(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = notificationsapi.NotificationSubscription.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.notifications_v1beta.NotificationsApiServiceClient.get_notification_subscription", + extra = { + "serviceName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", + "rpcName": "GetNotificationSubscription", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListNotificationSubscriptions(_BaseNotificationsApiServiceRestTransport._BaseListNotificationSubscriptions, NotificationsApiServiceRestStub): + def __hash__(self): + return hash("NotificationsApiServiceRestTransport.ListNotificationSubscriptions") + + @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: notificationsapi.ListNotificationSubscriptionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> notificationsapi.ListNotificationSubscriptionsResponse: + r"""Call the list notification + subscriptions method over HTTP. + + Args: + request (~.notificationsapi.ListNotificationSubscriptionsRequest): + The request object. Request message for the + ListNotificationSubscription method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.notificationsapi.ListNotificationSubscriptionsResponse: + Response message for the + ListNotificationSubscription method. + + """ + + http_options = _BaseNotificationsApiServiceRestTransport._BaseListNotificationSubscriptions._get_http_options() + + request, metadata = self._interceptor.pre_list_notification_subscriptions(request, metadata) + transcoded_request = _BaseNotificationsApiServiceRestTransport._BaseListNotificationSubscriptions._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseNotificationsApiServiceRestTransport._BaseListNotificationSubscriptions._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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.notifications_v1beta.NotificationsApiServiceClient.ListNotificationSubscriptions", + extra = { + "serviceName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", + "rpcName": "ListNotificationSubscriptions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NotificationsApiServiceRestTransport._ListNotificationSubscriptions._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 = notificationsapi.ListNotificationSubscriptionsResponse() + pb_resp = notificationsapi.ListNotificationSubscriptionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_notification_subscriptions(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = notificationsapi.ListNotificationSubscriptionsResponse.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.notifications_v1beta.NotificationsApiServiceClient.list_notification_subscriptions", + extra = { + "serviceName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", + "rpcName": "ListNotificationSubscriptions", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateNotificationSubscription(_BaseNotificationsApiServiceRestTransport._BaseUpdateNotificationSubscription, NotificationsApiServiceRestStub): + def __hash__(self): + return hash("NotificationsApiServiceRestTransport.UpdateNotificationSubscription") + + @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: notificationsapi.UpdateNotificationSubscriptionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> notificationsapi.NotificationSubscription: + r"""Call the update notification + subscription method over HTTP. + + Args: + request (~.notificationsapi.UpdateNotificationSubscriptionRequest): + The request object. Request message for the + UpdateNotificationSubscription method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.notificationsapi.NotificationSubscription: + Represents a notification + subscription owned by a Merchant + account. + + """ + + http_options = _BaseNotificationsApiServiceRestTransport._BaseUpdateNotificationSubscription._get_http_options() + + request, metadata = self._interceptor.pre_update_notification_subscription(request, metadata) + transcoded_request = _BaseNotificationsApiServiceRestTransport._BaseUpdateNotificationSubscription._get_transcoded_request(http_options, request) + + body = _BaseNotificationsApiServiceRestTransport._BaseUpdateNotificationSubscription._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseNotificationsApiServiceRestTransport._BaseUpdateNotificationSubscription._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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.notifications_v1beta.NotificationsApiServiceClient.UpdateNotificationSubscription", + extra = { + "serviceName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", + "rpcName": "UpdateNotificationSubscription", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NotificationsApiServiceRestTransport._UpdateNotificationSubscription._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 = notificationsapi.NotificationSubscription() + pb_resp = notificationsapi.NotificationSubscription.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_notification_subscription(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = notificationsapi.NotificationSubscription.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.notifications_v1beta.NotificationsApiServiceClient.update_notification_subscription", + extra = { + "serviceName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", + "rpcName": "UpdateNotificationSubscription", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_notification_subscription(self) -> Callable[ + [notificationsapi.CreateNotificationSubscriptionRequest], + notificationsapi.NotificationSubscription]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateNotificationSubscription(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_notification_subscription(self) -> Callable[ + [notificationsapi.DeleteNotificationSubscriptionRequest], + 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._DeleteNotificationSubscription(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_notification_subscription(self) -> Callable[ + [notificationsapi.GetNotificationSubscriptionRequest], + notificationsapi.NotificationSubscription]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetNotificationSubscription(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_notification_subscriptions(self) -> Callable[ + [notificationsapi.ListNotificationSubscriptionsRequest], + notificationsapi.ListNotificationSubscriptionsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListNotificationSubscriptions(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_notification_subscription(self) -> Callable[ + [notificationsapi.UpdateNotificationSubscriptionRequest], + notificationsapi.NotificationSubscription]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateNotificationSubscription(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'NotificationsApiServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/rest_base.py new file mode 100644 index 000000000000..b49003310c84 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/rest_base.py @@ -0,0 +1,297 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 NotificationsApiServiceTransport, 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_notifications_v1beta.types import notificationsapi + + +class _BaseNotificationsApiServiceRestTransport(NotificationsApiServiceTransport): + """Base REST backend transport for NotificationsApiService. + + 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 _BaseCreateNotificationSubscription: + 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': '/notifications/v1beta/{parent=accounts/*}/notificationsubscriptions', + 'body': 'notification_subscription', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = notificationsapi.CreateNotificationSubscriptionRequest.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(_BaseNotificationsApiServiceRestTransport._BaseCreateNotificationSubscription._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteNotificationSubscription: + 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': '/notifications/v1beta/{name=accounts/*/notificationsubscriptions/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = notificationsapi.DeleteNotificationSubscriptionRequest.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(_BaseNotificationsApiServiceRestTransport._BaseDeleteNotificationSubscription._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetNotificationSubscription: + 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': '/notifications/v1beta/{name=accounts/*/notificationsubscriptions/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = notificationsapi.GetNotificationSubscriptionRequest.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(_BaseNotificationsApiServiceRestTransport._BaseGetNotificationSubscription._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListNotificationSubscriptions: + 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': '/notifications/v1beta/{parent=accounts/*}/notificationsubscriptions', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = notificationsapi.ListNotificationSubscriptionsRequest.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(_BaseNotificationsApiServiceRestTransport._BaseListNotificationSubscriptions._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateNotificationSubscription: + 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': '/notifications/v1beta/{notification_subscription.name=accounts/*/notificationsubscriptions/*}', + 'body': 'notification_subscription', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = notificationsapi.UpdateNotificationSubscriptionRequest.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(_BaseNotificationsApiServiceRestTransport._BaseUpdateNotificationSubscription._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseNotificationsApiServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/types/__init__.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/types/__init__.py new file mode 100644 index 000000000000..a24323759992 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/types/__init__.py @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .notificationsapi import ( + CreateNotificationSubscriptionRequest, + DeleteNotificationSubscriptionRequest, + GetNotificationSubscriptionRequest, + ListNotificationSubscriptionsRequest, + ListNotificationSubscriptionsResponse, + NotificationSubscription, + ProductChange, + ProductStatusChangeMessage, + UpdateNotificationSubscriptionRequest, + Attribute, + Resource, +) + +__all__ = ( + 'CreateNotificationSubscriptionRequest', + 'DeleteNotificationSubscriptionRequest', + 'GetNotificationSubscriptionRequest', + 'ListNotificationSubscriptionsRequest', + 'ListNotificationSubscriptionsResponse', + 'NotificationSubscription', + 'ProductChange', + 'ProductStatusChangeMessage', + 'UpdateNotificationSubscriptionRequest', + 'Attribute', + 'Resource', +) diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/types/notificationsapi.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/types/notificationsapi.py new file mode 100644 index 000000000000..b28be34db58d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/types/notificationsapi.py @@ -0,0 +1,424 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.notifications.v1beta', + manifest={ + 'Resource', + 'Attribute', + 'GetNotificationSubscriptionRequest', + 'CreateNotificationSubscriptionRequest', + 'UpdateNotificationSubscriptionRequest', + 'DeleteNotificationSubscriptionRequest', + 'ListNotificationSubscriptionsRequest', + 'ListNotificationSubscriptionsResponse', + 'NotificationSubscription', + 'ProductChange', + 'ProductStatusChangeMessage', + }, +) + + +class Resource(proto.Enum): + r"""Enum to specify the resource that is being changed to notify + the merchant about. + + Values: + RESOURCE_UNSPECIFIED (0): + Unspecified resource + PRODUCT (1): + Resource type : product + """ + RESOURCE_UNSPECIFIED = 0 + PRODUCT = 1 + + +class Attribute(proto.Enum): + r"""Enum to specify the attribute in the resource that is being + changed to notify the merchant about. + + Values: + ATTRIBUTE_UNSPECIFIED (0): + Unspecified attribute + STATUS (1): + Status of the changed entity + """ + ATTRIBUTE_UNSPECIFIED = 0 + STATUS = 1 + + +class GetNotificationSubscriptionRequest(proto.Message): + r"""Request message for the GetNotificationSubscription method. + + Attributes: + name (str): + Required. The ``name`` of the notification subscription. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateNotificationSubscriptionRequest(proto.Message): + r"""Request message for the CreateNotificationSubscription + method. + + Attributes: + parent (str): + Required. The merchant account that owns the new + notification subscription. Format: ``accounts/{account}`` + notification_subscription (google.shopping.merchant_notifications_v1beta.types.NotificationSubscription): + Required. The notification subscription to + create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + notification_subscription: 'NotificationSubscription' = proto.Field( + proto.MESSAGE, + number=2, + message='NotificationSubscription', + ) + + +class UpdateNotificationSubscriptionRequest(proto.Message): + r"""Request message for the UpdateNotificationSubscription + method. + + Attributes: + notification_subscription (google.shopping.merchant_notifications_v1beta.types.NotificationSubscription): + Required. The new version of the notification + subscription that should be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + List of fields being updated. + """ + + notification_subscription: 'NotificationSubscription' = proto.Field( + proto.MESSAGE, + number=1, + message='NotificationSubscription', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteNotificationSubscriptionRequest(proto.Message): + r"""Request message for the DeleteNotificationSubscription + method. + + Attributes: + name (str): + Required. The name of the notification + subscription to be deleted. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListNotificationSubscriptionsRequest(proto.Message): + r"""Request message for the ListNotificationSubscription method. + + Attributes: + parent (str): + Required. The merchant account who owns the notification + subscriptions. Format: ``accounts/{account}`` + page_size (int): + The maximum number of notification subscriptions to return + in a page. The default value for ``page_size`` is 100. The + maximum value is ``200``. Values above ``200`` will be + coerced to ``200``. + page_token (str): + Token (if provided) to retrieve the + subsequent page. All other parameters must match + the original 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 ListNotificationSubscriptionsResponse(proto.Message): + r"""Response message for the ListNotificationSubscription method. + + Attributes: + notification_subscriptions (MutableSequence[google.shopping.merchant_notifications_v1beta.types.NotificationSubscription]): + The list of notification subscriptions + requested by the 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 + + notification_subscriptions: MutableSequence['NotificationSubscription'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='NotificationSubscription', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class NotificationSubscription(proto.Message): + r"""Represents a notification subscription owned by a Merchant + account. + + 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: + all_managed_accounts (bool): + If this value is true, the requesting account + is notified of the specified event for all + managed accounts (can be subaccounts or other + linked accounts) including newly added accounts + on a daily basis. + + This field is a member of `oneof`_ ``interested_in``. + target_account (str): + The ``name`` of the account you want to receive + notifications for. Format: ``accounts/{account}`` + + This field is a member of `oneof`_ ``interested_in``. + name (str): + Output only. The ``name`` of the notification configuration. + Generated by the Content API upon creation of a new + ``NotificationSubscription``. The ``account`` represents the + merchant ID of the merchant that owns the configuration. + Format: + ``accounts/{account}/notificationsubscriptions/{notification_subscription}`` + registered_event (google.shopping.merchant_notifications_v1beta.types.NotificationSubscription.NotificationEventType): + The event that the merchant wants to be + notified about. + call_back_uri (str): + URL to be used to push the notification to + the merchant. + """ + class NotificationEventType(proto.Enum): + r"""Represents the event type that the merchant is interested in + receiving notifications for. + + Values: + NOTIFICATION_EVENT_TYPE_UNSPECIFIED (0): + Notifications event type is unspecified. + PRODUCT_STATUS_CHANGE (1): + Notification of product status changes, for + example when product becomes disapproved. + """ + NOTIFICATION_EVENT_TYPE_UNSPECIFIED = 0 + PRODUCT_STATUS_CHANGE = 1 + + all_managed_accounts: bool = proto.Field( + proto.BOOL, + number=3, + oneof='interested_in', + ) + target_account: str = proto.Field( + proto.STRING, + number=4, + oneof='interested_in', + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + registered_event: NotificationEventType = proto.Field( + proto.ENUM, + number=2, + enum=NotificationEventType, + ) + call_back_uri: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ProductChange(proto.Message): + r"""The change that happened to the product including old value, + new value, country code as the region code and reporting + context. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + old_value (str): + The old value of the changed resource or + attribute. + + This field is a member of `oneof`_ ``_old_value``. + new_value (str): + The new value of the changed resource or + attribute. + + This field is a member of `oneof`_ ``_new_value``. + region_code (str): + Countries that have the change (if + applicable) + + This field is a member of `oneof`_ ``_region_code``. + reporting_context (google.shopping.type.types.ReportingContext.ReportingContextEnum): + Reporting contexts that have the change (if + applicable) + + This field is a member of `oneof`_ ``_reporting_context``. + """ + + old_value: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + new_value: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + region_code: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + reporting_context: types.ReportingContext.ReportingContextEnum = proto.Field( + proto.ENUM, + number=4, + optional=True, + enum=types.ReportingContext.ReportingContextEnum, + ) + + +class ProductStatusChangeMessage(proto.Message): + r"""The message that the merchant will receive to notify about + product status change event + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + account (str): + The target account that owns the entity that changed. Format + : ``accounts/{merchant_id}`` + + This field is a member of `oneof`_ ``_account``. + managing_account (str): + The account that manages the merchant's account. can be the + same as merchant id if it is standalone account. Format : + ``accounts/{service_provider_id}`` + + This field is a member of `oneof`_ ``_managing_account``. + resource_type (google.shopping.merchant_notifications_v1beta.types.Resource): + The resource that changed, in this case it will always be + ``Product``. + + This field is a member of `oneof`_ ``_resource_type``. + attribute (google.shopping.merchant_notifications_v1beta.types.Attribute): + The attribute in the resource that changed, in this case it + will be always ``Status``. + + This field is a member of `oneof`_ ``_attribute``. + changes (MutableSequence[google.shopping.merchant_notifications_v1beta.types.ProductChange]): + A message to describe the change that + happened to the product + resource_id (str): + The product id. + + This field is a member of `oneof`_ ``_resource_id``. + resource (str): + The product name. Format: + ``{product.name=accounts/{account}/products/{product}}`` + + This field is a member of `oneof`_ ``_resource``. + """ + + account: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + managing_account: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + resource_type: 'Resource' = proto.Field( + proto.ENUM, + number=3, + optional=True, + enum='Resource', + ) + attribute: 'Attribute' = proto.Field( + proto.ENUM, + number=4, + optional=True, + enum='Attribute', + ) + changes: MutableSequence['ProductChange'] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message='ProductChange', + ) + resource_id: str = proto.Field( + proto.STRING, + number=6, + optional=True, + ) + resource: str = proto.Field( + proto.STRING, + number=7, + optional=True, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/mypy.ini b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/noxfile.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/noxfile.py new file mode 100644 index 000000000000..486d3948542f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/noxfile.py @@ -0,0 +1,280 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = 'google-shopping-merchant-notifications' + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.13" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "prerelease_deps", +] + +@nox.session(python=ALL_PYTHON) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def unit(session, protobuf_implementation): + """Run the unit test suite.""" + + 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+") + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") + + # 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") + + session.run( + 'py.test', + '--quiet', + '--cov=google/shopping/merchant_notifications_v1beta/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)), + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + +@nox.session(python=ALL_PYTHON[-1]) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def prerelease_deps(session, protobuf_implementation): + """Run the unit test suite against pre-release versions of dependencies.""" + + 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 test environment dependencies + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + + # Install the package without dependencies + session.install('-e', '.', '--no-deps') + + # We test the minimum dependency versions using the minimum Python + # version so the lowest python runtime that we test has a corresponding constraints + # file, located at `testing/constraints--.txt`, which contains all of the + # 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 + ) + ] + + session.install(*constraints_deps) + + prerel_deps = [ + "googleapis-common-protos", + "google-api-core", + "google-auth", + # Exclude grpcio!=1.67.0rc1 which does not support python 3.13 + "grpcio!=1.67.0rc1", + "grpcio-status", + "protobuf", + "proto-plus", + ] + + for dep in prerel_deps: + session.install("--pre", "--no-deps", "--upgrade", dep) + + # Remaining dependencies + other_deps = [ + "requests", + ] + session.install(*other_deps) + + # Print out prerelease package versions + + session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") + session.run("python", "-c", "import google.auth; print(google.auth.__version__)") + session.run("python", "-c", "import grpc; print(grpc.__version__)") + session.run( + "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" + ) + session.run( + "python", "-c", "import proto; print(proto.__version__)" + ) + + session.run( + 'py.test', + '--quiet', + '--cov=google/shopping/merchant_notifications_v1beta/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)), + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + + +@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=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 docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==7.0.1", "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=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", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_create_notification_subscription_async.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_create_notification_subscription_async.py new file mode 100644 index 000000000000..11afd393a147 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_create_notification_subscription_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateNotificationSubscription +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-notifications + + +# [START merchantapi_v1beta_generated_NotificationsApiService_CreateNotificationSubscription_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_notifications_v1beta + + +async def sample_create_notification_subscription(): + # Create a client + client = merchant_notifications_v1beta.NotificationsApiServiceAsyncClient() + + # Initialize request argument(s) + notification_subscription = merchant_notifications_v1beta.NotificationSubscription() + notification_subscription.all_managed_accounts = True + + request = merchant_notifications_v1beta.CreateNotificationSubscriptionRequest( + parent="parent_value", + notification_subscription=notification_subscription, + ) + + # Make the request + response = await client.create_notification_subscription(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_NotificationsApiService_CreateNotificationSubscription_async] diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_create_notification_subscription_sync.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_create_notification_subscription_sync.py new file mode 100644 index 000000000000..af214ecce4e1 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_create_notification_subscription_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateNotificationSubscription +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-notifications + + +# [START merchantapi_v1beta_generated_NotificationsApiService_CreateNotificationSubscription_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_notifications_v1beta + + +def sample_create_notification_subscription(): + # Create a client + client = merchant_notifications_v1beta.NotificationsApiServiceClient() + + # Initialize request argument(s) + notification_subscription = merchant_notifications_v1beta.NotificationSubscription() + notification_subscription.all_managed_accounts = True + + request = merchant_notifications_v1beta.CreateNotificationSubscriptionRequest( + parent="parent_value", + notification_subscription=notification_subscription, + ) + + # Make the request + response = client.create_notification_subscription(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_NotificationsApiService_CreateNotificationSubscription_sync] diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_delete_notification_subscription_async.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_delete_notification_subscription_async.py new file mode 100644 index 000000000000..575ba1c51c3f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_delete_notification_subscription_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteNotificationSubscription +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-notifications + + +# [START merchantapi_v1beta_generated_NotificationsApiService_DeleteNotificationSubscription_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_notifications_v1beta + + +async def sample_delete_notification_subscription(): + # Create a client + client = merchant_notifications_v1beta.NotificationsApiServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_notifications_v1beta.DeleteNotificationSubscriptionRequest( + name="name_value", + ) + + # Make the request + await client.delete_notification_subscription(request=request) + + +# [END merchantapi_v1beta_generated_NotificationsApiService_DeleteNotificationSubscription_async] diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_delete_notification_subscription_sync.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_delete_notification_subscription_sync.py new file mode 100644 index 000000000000..32cbbdca5280 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_delete_notification_subscription_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteNotificationSubscription +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-notifications + + +# [START merchantapi_v1beta_generated_NotificationsApiService_DeleteNotificationSubscription_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_notifications_v1beta + + +def sample_delete_notification_subscription(): + # Create a client + client = merchant_notifications_v1beta.NotificationsApiServiceClient() + + # Initialize request argument(s) + request = merchant_notifications_v1beta.DeleteNotificationSubscriptionRequest( + name="name_value", + ) + + # Make the request + client.delete_notification_subscription(request=request) + + +# [END merchantapi_v1beta_generated_NotificationsApiService_DeleteNotificationSubscription_sync] diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_get_notification_subscription_async.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_get_notification_subscription_async.py new file mode 100644 index 000000000000..620d1dbcba47 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_get_notification_subscription_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetNotificationSubscription +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-notifications + + +# [START merchantapi_v1beta_generated_NotificationsApiService_GetNotificationSubscription_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_notifications_v1beta + + +async def sample_get_notification_subscription(): + # Create a client + client = merchant_notifications_v1beta.NotificationsApiServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_notifications_v1beta.GetNotificationSubscriptionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_notification_subscription(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_NotificationsApiService_GetNotificationSubscription_async] diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_get_notification_subscription_sync.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_get_notification_subscription_sync.py new file mode 100644 index 000000000000..b51236045fda --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_get_notification_subscription_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetNotificationSubscription +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-notifications + + +# [START merchantapi_v1beta_generated_NotificationsApiService_GetNotificationSubscription_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_notifications_v1beta + + +def sample_get_notification_subscription(): + # Create a client + client = merchant_notifications_v1beta.NotificationsApiServiceClient() + + # Initialize request argument(s) + request = merchant_notifications_v1beta.GetNotificationSubscriptionRequest( + name="name_value", + ) + + # Make the request + response = client.get_notification_subscription(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_NotificationsApiService_GetNotificationSubscription_sync] diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_list_notification_subscriptions_async.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_list_notification_subscriptions_async.py new file mode 100644 index 000000000000..58b97c1734ab --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_list_notification_subscriptions_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListNotificationSubscriptions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-notifications + + +# [START merchantapi_v1beta_generated_NotificationsApiService_ListNotificationSubscriptions_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_notifications_v1beta + + +async def sample_list_notification_subscriptions(): + # Create a client + client = merchant_notifications_v1beta.NotificationsApiServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_notifications_v1beta.ListNotificationSubscriptionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_notification_subscriptions(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_NotificationsApiService_ListNotificationSubscriptions_async] diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_list_notification_subscriptions_sync.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_list_notification_subscriptions_sync.py new file mode 100644 index 000000000000..54b882cffe95 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_list_notification_subscriptions_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListNotificationSubscriptions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-notifications + + +# [START merchantapi_v1beta_generated_NotificationsApiService_ListNotificationSubscriptions_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_notifications_v1beta + + +def sample_list_notification_subscriptions(): + # Create a client + client = merchant_notifications_v1beta.NotificationsApiServiceClient() + + # Initialize request argument(s) + request = merchant_notifications_v1beta.ListNotificationSubscriptionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_notification_subscriptions(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_NotificationsApiService_ListNotificationSubscriptions_sync] diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_update_notification_subscription_async.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_update_notification_subscription_async.py new file mode 100644 index 000000000000..cf8732747efe --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_update_notification_subscription_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateNotificationSubscription +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-notifications + + +# [START merchantapi_v1beta_generated_NotificationsApiService_UpdateNotificationSubscription_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_notifications_v1beta + + +async def sample_update_notification_subscription(): + # Create a client + client = merchant_notifications_v1beta.NotificationsApiServiceAsyncClient() + + # Initialize request argument(s) + notification_subscription = merchant_notifications_v1beta.NotificationSubscription() + notification_subscription.all_managed_accounts = True + + request = merchant_notifications_v1beta.UpdateNotificationSubscriptionRequest( + notification_subscription=notification_subscription, + ) + + # Make the request + response = await client.update_notification_subscription(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_NotificationsApiService_UpdateNotificationSubscription_async] diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_update_notification_subscription_sync.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_update_notification_subscription_sync.py new file mode 100644 index 000000000000..e921cd95cc4c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_update_notification_subscription_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateNotificationSubscription +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-notifications + + +# [START merchantapi_v1beta_generated_NotificationsApiService_UpdateNotificationSubscription_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_notifications_v1beta + + +def sample_update_notification_subscription(): + # Create a client + client = merchant_notifications_v1beta.NotificationsApiServiceClient() + + # Initialize request argument(s) + notification_subscription = merchant_notifications_v1beta.NotificationSubscription() + notification_subscription.all_managed_accounts = True + + request = merchant_notifications_v1beta.UpdateNotificationSubscriptionRequest( + notification_subscription=notification_subscription, + ) + + # Make the request + response = client.update_notification_subscription(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_NotificationsApiService_UpdateNotificationSubscription_sync] diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.notifications.v1beta.json b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.notifications.v1beta.json new file mode 100644 index 000000000000..b27b3eb2144a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.notifications.v1beta.json @@ -0,0 +1,830 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.shopping.merchant.notifications.v1beta", + "version": "v1beta" + } + ], + "language": "PYTHON", + "name": "google-shopping-merchant-notifications", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_notifications_v1beta.NotificationsApiServiceAsyncClient", + "shortName": "NotificationsApiServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_notifications_v1beta.NotificationsApiServiceAsyncClient.create_notification_subscription", + "method": { + "fullName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService.CreateNotificationSubscription", + "service": { + "fullName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", + "shortName": "NotificationsApiService" + }, + "shortName": "CreateNotificationSubscription" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_notifications_v1beta.types.CreateNotificationSubscriptionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "notification_subscription", + "type": "google.shopping.merchant_notifications_v1beta.types.NotificationSubscription" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.shopping.merchant_notifications_v1beta.types.NotificationSubscription", + "shortName": "create_notification_subscription" + }, + "description": "Sample for CreateNotificationSubscription", + "file": "merchantapi_v1beta_generated_notifications_api_service_create_notification_subscription_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_NotificationsApiService_CreateNotificationSubscription_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_notifications_api_service_create_notification_subscription_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_notifications_v1beta.NotificationsApiServiceClient", + "shortName": "NotificationsApiServiceClient" + }, + "fullName": "google.shopping.merchant_notifications_v1beta.NotificationsApiServiceClient.create_notification_subscription", + "method": { + "fullName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService.CreateNotificationSubscription", + "service": { + "fullName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", + "shortName": "NotificationsApiService" + }, + "shortName": "CreateNotificationSubscription" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_notifications_v1beta.types.CreateNotificationSubscriptionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "notification_subscription", + "type": "google.shopping.merchant_notifications_v1beta.types.NotificationSubscription" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.shopping.merchant_notifications_v1beta.types.NotificationSubscription", + "shortName": "create_notification_subscription" + }, + "description": "Sample for CreateNotificationSubscription", + "file": "merchantapi_v1beta_generated_notifications_api_service_create_notification_subscription_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_NotificationsApiService_CreateNotificationSubscription_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_notifications_api_service_create_notification_subscription_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_notifications_v1beta.NotificationsApiServiceAsyncClient", + "shortName": "NotificationsApiServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_notifications_v1beta.NotificationsApiServiceAsyncClient.delete_notification_subscription", + "method": { + "fullName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService.DeleteNotificationSubscription", + "service": { + "fullName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", + "shortName": "NotificationsApiService" + }, + "shortName": "DeleteNotificationSubscription" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_notifications_v1beta.types.DeleteNotificationSubscriptionRequest" + }, + { + "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_notification_subscription" + }, + "description": "Sample for DeleteNotificationSubscription", + "file": "merchantapi_v1beta_generated_notifications_api_service_delete_notification_subscription_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_NotificationsApiService_DeleteNotificationSubscription_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_notifications_api_service_delete_notification_subscription_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_notifications_v1beta.NotificationsApiServiceClient", + "shortName": "NotificationsApiServiceClient" + }, + "fullName": "google.shopping.merchant_notifications_v1beta.NotificationsApiServiceClient.delete_notification_subscription", + "method": { + "fullName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService.DeleteNotificationSubscription", + "service": { + "fullName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", + "shortName": "NotificationsApiService" + }, + "shortName": "DeleteNotificationSubscription" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_notifications_v1beta.types.DeleteNotificationSubscriptionRequest" + }, + { + "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_notification_subscription" + }, + "description": "Sample for DeleteNotificationSubscription", + "file": "merchantapi_v1beta_generated_notifications_api_service_delete_notification_subscription_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_NotificationsApiService_DeleteNotificationSubscription_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_notifications_api_service_delete_notification_subscription_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_notifications_v1beta.NotificationsApiServiceAsyncClient", + "shortName": "NotificationsApiServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_notifications_v1beta.NotificationsApiServiceAsyncClient.get_notification_subscription", + "method": { + "fullName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService.GetNotificationSubscription", + "service": { + "fullName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", + "shortName": "NotificationsApiService" + }, + "shortName": "GetNotificationSubscription" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_notifications_v1beta.types.GetNotificationSubscriptionRequest" + }, + { + "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_notifications_v1beta.types.NotificationSubscription", + "shortName": "get_notification_subscription" + }, + "description": "Sample for GetNotificationSubscription", + "file": "merchantapi_v1beta_generated_notifications_api_service_get_notification_subscription_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_NotificationsApiService_GetNotificationSubscription_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_notifications_api_service_get_notification_subscription_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_notifications_v1beta.NotificationsApiServiceClient", + "shortName": "NotificationsApiServiceClient" + }, + "fullName": "google.shopping.merchant_notifications_v1beta.NotificationsApiServiceClient.get_notification_subscription", + "method": { + "fullName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService.GetNotificationSubscription", + "service": { + "fullName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", + "shortName": "NotificationsApiService" + }, + "shortName": "GetNotificationSubscription" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_notifications_v1beta.types.GetNotificationSubscriptionRequest" + }, + { + "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_notifications_v1beta.types.NotificationSubscription", + "shortName": "get_notification_subscription" + }, + "description": "Sample for GetNotificationSubscription", + "file": "merchantapi_v1beta_generated_notifications_api_service_get_notification_subscription_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_NotificationsApiService_GetNotificationSubscription_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_notifications_api_service_get_notification_subscription_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_notifications_v1beta.NotificationsApiServiceAsyncClient", + "shortName": "NotificationsApiServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_notifications_v1beta.NotificationsApiServiceAsyncClient.list_notification_subscriptions", + "method": { + "fullName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService.ListNotificationSubscriptions", + "service": { + "fullName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", + "shortName": "NotificationsApiService" + }, + "shortName": "ListNotificationSubscriptions" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_notifications_v1beta.types.ListNotificationSubscriptionsRequest" + }, + { + "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_notifications_v1beta.services.notifications_api_service.pagers.ListNotificationSubscriptionsAsyncPager", + "shortName": "list_notification_subscriptions" + }, + "description": "Sample for ListNotificationSubscriptions", + "file": "merchantapi_v1beta_generated_notifications_api_service_list_notification_subscriptions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_NotificationsApiService_ListNotificationSubscriptions_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_notifications_api_service_list_notification_subscriptions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_notifications_v1beta.NotificationsApiServiceClient", + "shortName": "NotificationsApiServiceClient" + }, + "fullName": "google.shopping.merchant_notifications_v1beta.NotificationsApiServiceClient.list_notification_subscriptions", + "method": { + "fullName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService.ListNotificationSubscriptions", + "service": { + "fullName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", + "shortName": "NotificationsApiService" + }, + "shortName": "ListNotificationSubscriptions" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_notifications_v1beta.types.ListNotificationSubscriptionsRequest" + }, + { + "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_notifications_v1beta.services.notifications_api_service.pagers.ListNotificationSubscriptionsPager", + "shortName": "list_notification_subscriptions" + }, + "description": "Sample for ListNotificationSubscriptions", + "file": "merchantapi_v1beta_generated_notifications_api_service_list_notification_subscriptions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_NotificationsApiService_ListNotificationSubscriptions_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_notifications_api_service_list_notification_subscriptions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_notifications_v1beta.NotificationsApiServiceAsyncClient", + "shortName": "NotificationsApiServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_notifications_v1beta.NotificationsApiServiceAsyncClient.update_notification_subscription", + "method": { + "fullName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService.UpdateNotificationSubscription", + "service": { + "fullName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", + "shortName": "NotificationsApiService" + }, + "shortName": "UpdateNotificationSubscription" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_notifications_v1beta.types.UpdateNotificationSubscriptionRequest" + }, + { + "name": "notification_subscription", + "type": "google.shopping.merchant_notifications_v1beta.types.NotificationSubscription" + }, + { + "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_notifications_v1beta.types.NotificationSubscription", + "shortName": "update_notification_subscription" + }, + "description": "Sample for UpdateNotificationSubscription", + "file": "merchantapi_v1beta_generated_notifications_api_service_update_notification_subscription_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_NotificationsApiService_UpdateNotificationSubscription_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_notifications_api_service_update_notification_subscription_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_notifications_v1beta.NotificationsApiServiceClient", + "shortName": "NotificationsApiServiceClient" + }, + "fullName": "google.shopping.merchant_notifications_v1beta.NotificationsApiServiceClient.update_notification_subscription", + "method": { + "fullName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService.UpdateNotificationSubscription", + "service": { + "fullName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", + "shortName": "NotificationsApiService" + }, + "shortName": "UpdateNotificationSubscription" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_notifications_v1beta.types.UpdateNotificationSubscriptionRequest" + }, + { + "name": "notification_subscription", + "type": "google.shopping.merchant_notifications_v1beta.types.NotificationSubscription" + }, + { + "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_notifications_v1beta.types.NotificationSubscription", + "shortName": "update_notification_subscription" + }, + "description": "Sample for UpdateNotificationSubscription", + "file": "merchantapi_v1beta_generated_notifications_api_service_update_notification_subscription_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_NotificationsApiService_UpdateNotificationSubscription_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_notifications_api_service_update_notification_subscription_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/scripts/fixup_merchant_notifications_v1beta_keywords.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/scripts/fixup_merchant_notifications_v1beta_keywords.py new file mode 100644 index 000000000000..d05f3b942dcb --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/scripts/fixup_merchant_notifications_v1beta_keywords.py @@ -0,0 +1,180 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_notificationsCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_notification_subscription': ('parent', 'notification_subscription', ), + 'delete_notification_subscription': ('name', ), + 'get_notification_subscription': ('name', ), + 'list_notification_subscriptions': ('parent', 'page_size', 'page_token', ), + 'update_notification_subscription': ('notification_subscription', '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_notificationsCallTransformer(), +): + """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_notifications 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-notifications/v1beta/setup.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/setup.py new file mode 100644 index 000000000000..bac7d3ecd5e8 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/setup.py @@ -0,0 +1,99 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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-notifications' + + +description = "Google Shopping Merchant Notifications API client library" + +version = None + +with open(os.path.join(package_root, 'google/shopping/merchant_notifications/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.0dev,!=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.0dev,!=2.24.0,!=2.25.0", + "proto-plus >= 1.22.3, <2.0.0dev", + "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'", + "protobuf>=3.20.2,<6.0.0dev,!=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.0dev", +] +extras = { +} +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-notifications" + +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-notifications/v1beta/testing/constraints-3.10.txt b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/testing/constraints-3.10.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/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-notifications/v1beta/testing/constraints-3.11.txt b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/testing/constraints-3.11.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/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-notifications/v1beta/testing/constraints-3.12.txt b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/testing/constraints-3.12.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/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-notifications/v1beta/testing/constraints-3.13.txt b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/testing/constraints-3.13.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/testing/constraints-3.13.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-notifications/v1beta/testing/constraints-3.7.txt b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/testing/constraints-3.7.txt new file mode 100644 index 000000000000..130a0c0f80ab --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/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.0dev", +# 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-notifications/v1beta/testing/constraints-3.8.txt b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/testing/constraints-3.8.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/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-notifications/v1beta/testing/constraints-3.9.txt b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/testing/constraints-3.9.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/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-notifications/v1beta/tests/__init__.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-notifications/v1beta/tests/unit/__init__.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-notifications/v1beta/tests/unit/gapic/__init__.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-notifications/v1beta/tests/unit/gapic/merchant_notifications_v1beta/__init__.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/tests/unit/gapic/merchant_notifications_v1beta/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/tests/unit/gapic/merchant_notifications_v1beta/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-notifications/v1beta/tests/unit/gapic/merchant_notifications_v1beta/test_notifications_api_service.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/tests/unit/gapic/merchant_notifications_v1beta/test_notifications_api_service.py new file mode 100644 index 000000000000..c7917334ffb9 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/tests/unit/gapic/merchant_notifications_v1beta/test_notifications_api_service.py @@ -0,0 +1,5136 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_notifications_v1beta.services.notifications_api_service import NotificationsApiServiceAsyncClient +from google.shopping.merchant_notifications_v1beta.services.notifications_api_service import NotificationsApiServiceClient +from google.shopping.merchant_notifications_v1beta.services.notifications_api_service import pagers +from google.shopping.merchant_notifications_v1beta.services.notifications_api_service import transports +from google.shopping.merchant_notifications_v1beta.types import notificationsapi +import google.auth + + +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 NotificationsApiServiceClient._get_default_mtls_endpoint(None) is None + assert NotificationsApiServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert NotificationsApiServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert NotificationsApiServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert NotificationsApiServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert NotificationsApiServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert NotificationsApiServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert NotificationsApiServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert NotificationsApiServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + NotificationsApiServiceClient._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 NotificationsApiServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert NotificationsApiServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert NotificationsApiServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + NotificationsApiServiceClient._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 NotificationsApiServiceClient._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 NotificationsApiServiceClient._get_client_cert_source(None, False) is None + assert NotificationsApiServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert NotificationsApiServiceClient._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 NotificationsApiServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert NotificationsApiServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(NotificationsApiServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NotificationsApiServiceClient)) +@mock.patch.object(NotificationsApiServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NotificationsApiServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = NotificationsApiServiceClient._DEFAULT_UNIVERSE + default_endpoint = NotificationsApiServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = NotificationsApiServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert NotificationsApiServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert NotificationsApiServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == NotificationsApiServiceClient.DEFAULT_MTLS_ENDPOINT + assert NotificationsApiServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert NotificationsApiServiceClient._get_api_endpoint(None, None, default_universe, "always") == NotificationsApiServiceClient.DEFAULT_MTLS_ENDPOINT + assert NotificationsApiServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == NotificationsApiServiceClient.DEFAULT_MTLS_ENDPOINT + assert NotificationsApiServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert NotificationsApiServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + NotificationsApiServiceClient._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 NotificationsApiServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert NotificationsApiServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert NotificationsApiServiceClient._get_universe_domain(None, None) == NotificationsApiServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + NotificationsApiServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize("client_class,transport_name", [ + (NotificationsApiServiceClient, "grpc"), + (NotificationsApiServiceAsyncClient, "grpc_asyncio"), + (NotificationsApiServiceClient, "rest"), +]) +def test_notifications_api_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.NotificationsApiServiceGrpcTransport, "grpc"), + (transports.NotificationsApiServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.NotificationsApiServiceRestTransport, "rest"), +]) +def test_notifications_api_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", [ + (NotificationsApiServiceClient, "grpc"), + (NotificationsApiServiceAsyncClient, "grpc_asyncio"), + (NotificationsApiServiceClient, "rest"), +]) +def test_notifications_api_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_notifications_api_service_client_get_transport_class(): + transport = NotificationsApiServiceClient.get_transport_class() + available_transports = [ + transports.NotificationsApiServiceGrpcTransport, + transports.NotificationsApiServiceRestTransport, + ] + assert transport in available_transports + + transport = NotificationsApiServiceClient.get_transport_class("grpc") + assert transport == transports.NotificationsApiServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (NotificationsApiServiceClient, transports.NotificationsApiServiceGrpcTransport, "grpc"), + (NotificationsApiServiceAsyncClient, transports.NotificationsApiServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (NotificationsApiServiceClient, transports.NotificationsApiServiceRestTransport, "rest"), +]) +@mock.patch.object(NotificationsApiServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NotificationsApiServiceClient)) +@mock.patch.object(NotificationsApiServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NotificationsApiServiceAsyncClient)) +def test_notifications_api_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(NotificationsApiServiceClient, '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(NotificationsApiServiceClient, '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", [ + (NotificationsApiServiceClient, transports.NotificationsApiServiceGrpcTransport, "grpc", "true"), + (NotificationsApiServiceAsyncClient, transports.NotificationsApiServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (NotificationsApiServiceClient, transports.NotificationsApiServiceGrpcTransport, "grpc", "false"), + (NotificationsApiServiceAsyncClient, transports.NotificationsApiServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (NotificationsApiServiceClient, transports.NotificationsApiServiceRestTransport, "rest", "true"), + (NotificationsApiServiceClient, transports.NotificationsApiServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(NotificationsApiServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NotificationsApiServiceClient)) +@mock.patch.object(NotificationsApiServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NotificationsApiServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_notifications_api_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", [ + NotificationsApiServiceClient, NotificationsApiServiceAsyncClient +]) +@mock.patch.object(NotificationsApiServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(NotificationsApiServiceClient)) +@mock.patch.object(NotificationsApiServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(NotificationsApiServiceAsyncClient)) +def test_notifications_api_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", [ + NotificationsApiServiceClient, NotificationsApiServiceAsyncClient +]) +@mock.patch.object(NotificationsApiServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NotificationsApiServiceClient)) +@mock.patch.object(NotificationsApiServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NotificationsApiServiceAsyncClient)) +def test_notifications_api_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = NotificationsApiServiceClient._DEFAULT_UNIVERSE + default_endpoint = NotificationsApiServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = NotificationsApiServiceClient._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", [ + (NotificationsApiServiceClient, transports.NotificationsApiServiceGrpcTransport, "grpc"), + (NotificationsApiServiceAsyncClient, transports.NotificationsApiServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (NotificationsApiServiceClient, transports.NotificationsApiServiceRestTransport, "rest"), +]) +def test_notifications_api_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", [ + (NotificationsApiServiceClient, transports.NotificationsApiServiceGrpcTransport, "grpc", grpc_helpers), + (NotificationsApiServiceAsyncClient, transports.NotificationsApiServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (NotificationsApiServiceClient, transports.NotificationsApiServiceRestTransport, "rest", None), +]) +def test_notifications_api_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_notifications_api_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_notifications_v1beta.services.notifications_api_service.transports.NotificationsApiServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = NotificationsApiServiceClient( + 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", [ + (NotificationsApiServiceClient, transports.NotificationsApiServiceGrpcTransport, "grpc", grpc_helpers), + (NotificationsApiServiceAsyncClient, transports.NotificationsApiServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_notifications_api_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", [ + notificationsapi.GetNotificationSubscriptionRequest, + dict, +]) +def test_get_notification_subscription(request_type, transport: str = 'grpc'): + client = NotificationsApiServiceClient( + 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_notification_subscription), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = notificationsapi.NotificationSubscription( + name='name_value', + registered_event=notificationsapi.NotificationSubscription.NotificationEventType.PRODUCT_STATUS_CHANGE, + call_back_uri='call_back_uri_value', + all_managed_accounts=True, + ) + response = client.get_notification_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = notificationsapi.GetNotificationSubscriptionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, notificationsapi.NotificationSubscription) + assert response.name == 'name_value' + assert response.registered_event == notificationsapi.NotificationSubscription.NotificationEventType.PRODUCT_STATUS_CHANGE + assert response.call_back_uri == 'call_back_uri_value' + + +def test_get_notification_subscription_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 = NotificationsApiServiceClient( + 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 = notificationsapi.GetNotificationSubscriptionRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_notification_subscription), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_notification_subscription(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == notificationsapi.GetNotificationSubscriptionRequest( + name='name_value', + ) + +def test_get_notification_subscription_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NotificationsApiServiceClient( + 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_notification_subscription in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_notification_subscription] = mock_rpc + request = {} + client.get_notification_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_notification_subscription(request) + + # Establish that a new wrapper 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_notification_subscription_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = NotificationsApiServiceAsyncClient( + 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_notification_subscription in client._client._transport._wrapped_methods + + # 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_notification_subscription] = mock_rpc + + request = {} + await client.get_notification_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_notification_subscription(request) + + # Establish that a new wrapper 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_notification_subscription_async(transport: str = 'grpc_asyncio', request_type=notificationsapi.GetNotificationSubscriptionRequest): + client = NotificationsApiServiceAsyncClient( + 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_notification_subscription), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(notificationsapi.NotificationSubscription( + name='name_value', + registered_event=notificationsapi.NotificationSubscription.NotificationEventType.PRODUCT_STATUS_CHANGE, + call_back_uri='call_back_uri_value', + )) + response = await client.get_notification_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = notificationsapi.GetNotificationSubscriptionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, notificationsapi.NotificationSubscription) + assert response.name == 'name_value' + assert response.registered_event == notificationsapi.NotificationSubscription.NotificationEventType.PRODUCT_STATUS_CHANGE + assert response.call_back_uri == 'call_back_uri_value' + + +@pytest.mark.asyncio +async def test_get_notification_subscription_async_from_dict(): + await test_get_notification_subscription_async(request_type=dict) + +def test_get_notification_subscription_field_headers(): + client = NotificationsApiServiceClient( + 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 = notificationsapi.GetNotificationSubscriptionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_notification_subscription), + '__call__') as call: + call.return_value = notificationsapi.NotificationSubscription() + client.get_notification_subscription(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_notification_subscription_field_headers_async(): + client = NotificationsApiServiceAsyncClient( + 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 = notificationsapi.GetNotificationSubscriptionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_notification_subscription), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notificationsapi.NotificationSubscription()) + await client.get_notification_subscription(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_notification_subscription_flattened(): + client = NotificationsApiServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_notification_subscription), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = notificationsapi.NotificationSubscription() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_notification_subscription( + 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_notification_subscription_flattened_error(): + client = NotificationsApiServiceClient( + 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_notification_subscription( + notificationsapi.GetNotificationSubscriptionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_notification_subscription_flattened_async(): + client = NotificationsApiServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_notification_subscription), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = notificationsapi.NotificationSubscription() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notificationsapi.NotificationSubscription()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_notification_subscription( + 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_notification_subscription_flattened_error_async(): + client = NotificationsApiServiceAsyncClient( + 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_notification_subscription( + notificationsapi.GetNotificationSubscriptionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + notificationsapi.CreateNotificationSubscriptionRequest, + dict, +]) +def test_create_notification_subscription(request_type, transport: str = 'grpc'): + client = NotificationsApiServiceClient( + 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_notification_subscription), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = notificationsapi.NotificationSubscription( + name='name_value', + registered_event=notificationsapi.NotificationSubscription.NotificationEventType.PRODUCT_STATUS_CHANGE, + call_back_uri='call_back_uri_value', + all_managed_accounts=True, + ) + response = client.create_notification_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = notificationsapi.CreateNotificationSubscriptionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, notificationsapi.NotificationSubscription) + assert response.name == 'name_value' + assert response.registered_event == notificationsapi.NotificationSubscription.NotificationEventType.PRODUCT_STATUS_CHANGE + assert response.call_back_uri == 'call_back_uri_value' + + +def test_create_notification_subscription_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 = NotificationsApiServiceClient( + 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 = notificationsapi.CreateNotificationSubscriptionRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_notification_subscription), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_notification_subscription(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == notificationsapi.CreateNotificationSubscriptionRequest( + parent='parent_value', + ) + +def test_create_notification_subscription_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NotificationsApiServiceClient( + 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_notification_subscription in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_notification_subscription] = mock_rpc + request = {} + client.create_notification_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_notification_subscription(request) + + # Establish that a new wrapper 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_notification_subscription_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = NotificationsApiServiceAsyncClient( + 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_notification_subscription in client._client._transport._wrapped_methods + + # 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_notification_subscription] = mock_rpc + + request = {} + await client.create_notification_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_notification_subscription(request) + + # Establish that a new wrapper 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_notification_subscription_async(transport: str = 'grpc_asyncio', request_type=notificationsapi.CreateNotificationSubscriptionRequest): + client = NotificationsApiServiceAsyncClient( + 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_notification_subscription), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(notificationsapi.NotificationSubscription( + name='name_value', + registered_event=notificationsapi.NotificationSubscription.NotificationEventType.PRODUCT_STATUS_CHANGE, + call_back_uri='call_back_uri_value', + )) + response = await client.create_notification_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = notificationsapi.CreateNotificationSubscriptionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, notificationsapi.NotificationSubscription) + assert response.name == 'name_value' + assert response.registered_event == notificationsapi.NotificationSubscription.NotificationEventType.PRODUCT_STATUS_CHANGE + assert response.call_back_uri == 'call_back_uri_value' + + +@pytest.mark.asyncio +async def test_create_notification_subscription_async_from_dict(): + await test_create_notification_subscription_async(request_type=dict) + +def test_create_notification_subscription_field_headers(): + client = NotificationsApiServiceClient( + 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 = notificationsapi.CreateNotificationSubscriptionRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_notification_subscription), + '__call__') as call: + call.return_value = notificationsapi.NotificationSubscription() + client.create_notification_subscription(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_notification_subscription_field_headers_async(): + client = NotificationsApiServiceAsyncClient( + 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 = notificationsapi.CreateNotificationSubscriptionRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_notification_subscription), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notificationsapi.NotificationSubscription()) + await client.create_notification_subscription(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_notification_subscription_flattened(): + client = NotificationsApiServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_notification_subscription), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = notificationsapi.NotificationSubscription() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_notification_subscription( + parent='parent_value', + notification_subscription=notificationsapi.NotificationSubscription(all_managed_accounts=True), + ) + + # 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].notification_subscription + mock_val = notificationsapi.NotificationSubscription(all_managed_accounts=True) + assert arg == mock_val + + +def test_create_notification_subscription_flattened_error(): + client = NotificationsApiServiceClient( + 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_notification_subscription( + notificationsapi.CreateNotificationSubscriptionRequest(), + parent='parent_value', + notification_subscription=notificationsapi.NotificationSubscription(all_managed_accounts=True), + ) + +@pytest.mark.asyncio +async def test_create_notification_subscription_flattened_async(): + client = NotificationsApiServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_notification_subscription), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = notificationsapi.NotificationSubscription() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notificationsapi.NotificationSubscription()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_notification_subscription( + parent='parent_value', + notification_subscription=notificationsapi.NotificationSubscription(all_managed_accounts=True), + ) + + # 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].notification_subscription + mock_val = notificationsapi.NotificationSubscription(all_managed_accounts=True) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_notification_subscription_flattened_error_async(): + client = NotificationsApiServiceAsyncClient( + 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_notification_subscription( + notificationsapi.CreateNotificationSubscriptionRequest(), + parent='parent_value', + notification_subscription=notificationsapi.NotificationSubscription(all_managed_accounts=True), + ) + + +@pytest.mark.parametrize("request_type", [ + notificationsapi.UpdateNotificationSubscriptionRequest, + dict, +]) +def test_update_notification_subscription(request_type, transport: str = 'grpc'): + client = NotificationsApiServiceClient( + 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_notification_subscription), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = notificationsapi.NotificationSubscription( + name='name_value', + registered_event=notificationsapi.NotificationSubscription.NotificationEventType.PRODUCT_STATUS_CHANGE, + call_back_uri='call_back_uri_value', + all_managed_accounts=True, + ) + response = client.update_notification_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = notificationsapi.UpdateNotificationSubscriptionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, notificationsapi.NotificationSubscription) + assert response.name == 'name_value' + assert response.registered_event == notificationsapi.NotificationSubscription.NotificationEventType.PRODUCT_STATUS_CHANGE + assert response.call_back_uri == 'call_back_uri_value' + + +def test_update_notification_subscription_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 = NotificationsApiServiceClient( + 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 = notificationsapi.UpdateNotificationSubscriptionRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_subscription), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_notification_subscription(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == notificationsapi.UpdateNotificationSubscriptionRequest( + ) + +def test_update_notification_subscription_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NotificationsApiServiceClient( + 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_notification_subscription in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_notification_subscription] = mock_rpc + request = {} + client.update_notification_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_notification_subscription(request) + + # Establish that a new wrapper 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_notification_subscription_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = NotificationsApiServiceAsyncClient( + 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_notification_subscription in client._client._transport._wrapped_methods + + # 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_notification_subscription] = mock_rpc + + request = {} + await client.update_notification_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_notification_subscription(request) + + # Establish that a new wrapper 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_notification_subscription_async(transport: str = 'grpc_asyncio', request_type=notificationsapi.UpdateNotificationSubscriptionRequest): + client = NotificationsApiServiceAsyncClient( + 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_notification_subscription), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(notificationsapi.NotificationSubscription( + name='name_value', + registered_event=notificationsapi.NotificationSubscription.NotificationEventType.PRODUCT_STATUS_CHANGE, + call_back_uri='call_back_uri_value', + )) + response = await client.update_notification_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = notificationsapi.UpdateNotificationSubscriptionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, notificationsapi.NotificationSubscription) + assert response.name == 'name_value' + assert response.registered_event == notificationsapi.NotificationSubscription.NotificationEventType.PRODUCT_STATUS_CHANGE + assert response.call_back_uri == 'call_back_uri_value' + + +@pytest.mark.asyncio +async def test_update_notification_subscription_async_from_dict(): + await test_update_notification_subscription_async(request_type=dict) + +def test_update_notification_subscription_field_headers(): + client = NotificationsApiServiceClient( + 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 = notificationsapi.UpdateNotificationSubscriptionRequest() + + request.notification_subscription.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_subscription), + '__call__') as call: + call.return_value = notificationsapi.NotificationSubscription() + client.update_notification_subscription(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', + 'notification_subscription.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_notification_subscription_field_headers_async(): + client = NotificationsApiServiceAsyncClient( + 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 = notificationsapi.UpdateNotificationSubscriptionRequest() + + request.notification_subscription.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_subscription), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notificationsapi.NotificationSubscription()) + await client.update_notification_subscription(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', + 'notification_subscription.name=name_value', + ) in kw['metadata'] + + +def test_update_notification_subscription_flattened(): + client = NotificationsApiServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_subscription), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = notificationsapi.NotificationSubscription() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_notification_subscription( + notification_subscription=notificationsapi.NotificationSubscription(all_managed_accounts=True), + 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].notification_subscription + mock_val = notificationsapi.NotificationSubscription(all_managed_accounts=True) + 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_notification_subscription_flattened_error(): + client = NotificationsApiServiceClient( + 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_notification_subscription( + notificationsapi.UpdateNotificationSubscriptionRequest(), + notification_subscription=notificationsapi.NotificationSubscription(all_managed_accounts=True), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_notification_subscription_flattened_async(): + client = NotificationsApiServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_subscription), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = notificationsapi.NotificationSubscription() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notificationsapi.NotificationSubscription()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_notification_subscription( + notification_subscription=notificationsapi.NotificationSubscription(all_managed_accounts=True), + 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].notification_subscription + mock_val = notificationsapi.NotificationSubscription(all_managed_accounts=True) + 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_notification_subscription_flattened_error_async(): + client = NotificationsApiServiceAsyncClient( + 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_notification_subscription( + notificationsapi.UpdateNotificationSubscriptionRequest(), + notification_subscription=notificationsapi.NotificationSubscription(all_managed_accounts=True), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + notificationsapi.DeleteNotificationSubscriptionRequest, + dict, +]) +def test_delete_notification_subscription(request_type, transport: str = 'grpc'): + client = NotificationsApiServiceClient( + 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_notification_subscription), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_notification_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = notificationsapi.DeleteNotificationSubscriptionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_notification_subscription_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 = NotificationsApiServiceClient( + 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 = notificationsapi.DeleteNotificationSubscriptionRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_notification_subscription), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_notification_subscription(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == notificationsapi.DeleteNotificationSubscriptionRequest( + name='name_value', + ) + +def test_delete_notification_subscription_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NotificationsApiServiceClient( + 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_notification_subscription in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_notification_subscription] = mock_rpc + request = {} + client.delete_notification_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_notification_subscription(request) + + # Establish that a new wrapper 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_notification_subscription_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = NotificationsApiServiceAsyncClient( + 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_notification_subscription in client._client._transport._wrapped_methods + + # 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_notification_subscription] = mock_rpc + + request = {} + await client.delete_notification_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_notification_subscription(request) + + # Establish that a new wrapper 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_notification_subscription_async(transport: str = 'grpc_asyncio', request_type=notificationsapi.DeleteNotificationSubscriptionRequest): + client = NotificationsApiServiceAsyncClient( + 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_notification_subscription), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_notification_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = notificationsapi.DeleteNotificationSubscriptionRequest() + 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_notification_subscription_async_from_dict(): + await test_delete_notification_subscription_async(request_type=dict) + +def test_delete_notification_subscription_field_headers(): + client = NotificationsApiServiceClient( + 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 = notificationsapi.DeleteNotificationSubscriptionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_notification_subscription), + '__call__') as call: + call.return_value = None + client.delete_notification_subscription(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_notification_subscription_field_headers_async(): + client = NotificationsApiServiceAsyncClient( + 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 = notificationsapi.DeleteNotificationSubscriptionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_notification_subscription), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_notification_subscription(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_notification_subscription_flattened(): + client = NotificationsApiServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_notification_subscription), + '__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_notification_subscription( + 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_notification_subscription_flattened_error(): + client = NotificationsApiServiceClient( + 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_notification_subscription( + notificationsapi.DeleteNotificationSubscriptionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_notification_subscription_flattened_async(): + client = NotificationsApiServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_notification_subscription), + '__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_notification_subscription( + 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_notification_subscription_flattened_error_async(): + client = NotificationsApiServiceAsyncClient( + 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_notification_subscription( + notificationsapi.DeleteNotificationSubscriptionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + notificationsapi.ListNotificationSubscriptionsRequest, + dict, +]) +def test_list_notification_subscriptions(request_type, transport: str = 'grpc'): + client = NotificationsApiServiceClient( + 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_notification_subscriptions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = notificationsapi.ListNotificationSubscriptionsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_notification_subscriptions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = notificationsapi.ListNotificationSubscriptionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNotificationSubscriptionsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_notification_subscriptions_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 = NotificationsApiServiceClient( + 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 = notificationsapi.ListNotificationSubscriptionsRequest( + 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_notification_subscriptions), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_notification_subscriptions(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == notificationsapi.ListNotificationSubscriptionsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_notification_subscriptions_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NotificationsApiServiceClient( + 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_notification_subscriptions in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_notification_subscriptions] = mock_rpc + request = {} + client.list_notification_subscriptions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_notification_subscriptions(request) + + # Establish that a new wrapper 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_notification_subscriptions_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = NotificationsApiServiceAsyncClient( + 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_notification_subscriptions in client._client._transport._wrapped_methods + + # 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_notification_subscriptions] = mock_rpc + + request = {} + await client.list_notification_subscriptions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_notification_subscriptions(request) + + # Establish that a new wrapper 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_notification_subscriptions_async(transport: str = 'grpc_asyncio', request_type=notificationsapi.ListNotificationSubscriptionsRequest): + client = NotificationsApiServiceAsyncClient( + 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_notification_subscriptions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(notificationsapi.ListNotificationSubscriptionsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_notification_subscriptions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = notificationsapi.ListNotificationSubscriptionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNotificationSubscriptionsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_notification_subscriptions_async_from_dict(): + await test_list_notification_subscriptions_async(request_type=dict) + +def test_list_notification_subscriptions_field_headers(): + client = NotificationsApiServiceClient( + 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 = notificationsapi.ListNotificationSubscriptionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notification_subscriptions), + '__call__') as call: + call.return_value = notificationsapi.ListNotificationSubscriptionsResponse() + client.list_notification_subscriptions(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_notification_subscriptions_field_headers_async(): + client = NotificationsApiServiceAsyncClient( + 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 = notificationsapi.ListNotificationSubscriptionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notification_subscriptions), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notificationsapi.ListNotificationSubscriptionsResponse()) + await client.list_notification_subscriptions(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_notification_subscriptions_flattened(): + client = NotificationsApiServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notification_subscriptions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = notificationsapi.ListNotificationSubscriptionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_notification_subscriptions( + 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_notification_subscriptions_flattened_error(): + client = NotificationsApiServiceClient( + 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_notification_subscriptions( + notificationsapi.ListNotificationSubscriptionsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_notification_subscriptions_flattened_async(): + client = NotificationsApiServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notification_subscriptions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = notificationsapi.ListNotificationSubscriptionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notificationsapi.ListNotificationSubscriptionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_notification_subscriptions( + 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_notification_subscriptions_flattened_error_async(): + client = NotificationsApiServiceAsyncClient( + 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_notification_subscriptions( + notificationsapi.ListNotificationSubscriptionsRequest(), + parent='parent_value', + ) + + +def test_list_notification_subscriptions_pager(transport_name: str = "grpc"): + client = NotificationsApiServiceClient( + 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_notification_subscriptions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + notificationsapi.ListNotificationSubscriptionsResponse( + notification_subscriptions=[ + notificationsapi.NotificationSubscription(), + notificationsapi.NotificationSubscription(), + notificationsapi.NotificationSubscription(), + ], + next_page_token='abc', + ), + notificationsapi.ListNotificationSubscriptionsResponse( + notification_subscriptions=[], + next_page_token='def', + ), + notificationsapi.ListNotificationSubscriptionsResponse( + notification_subscriptions=[ + notificationsapi.NotificationSubscription(), + ], + next_page_token='ghi', + ), + notificationsapi.ListNotificationSubscriptionsResponse( + notification_subscriptions=[ + notificationsapi.NotificationSubscription(), + notificationsapi.NotificationSubscription(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_notification_subscriptions(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, notificationsapi.NotificationSubscription) + for i in results) +def test_list_notification_subscriptions_pages(transport_name: str = "grpc"): + client = NotificationsApiServiceClient( + 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_notification_subscriptions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + notificationsapi.ListNotificationSubscriptionsResponse( + notification_subscriptions=[ + notificationsapi.NotificationSubscription(), + notificationsapi.NotificationSubscription(), + notificationsapi.NotificationSubscription(), + ], + next_page_token='abc', + ), + notificationsapi.ListNotificationSubscriptionsResponse( + notification_subscriptions=[], + next_page_token='def', + ), + notificationsapi.ListNotificationSubscriptionsResponse( + notification_subscriptions=[ + notificationsapi.NotificationSubscription(), + ], + next_page_token='ghi', + ), + notificationsapi.ListNotificationSubscriptionsResponse( + notification_subscriptions=[ + notificationsapi.NotificationSubscription(), + notificationsapi.NotificationSubscription(), + ], + ), + RuntimeError, + ) + pages = list(client.list_notification_subscriptions(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_notification_subscriptions_async_pager(): + client = NotificationsApiServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notification_subscriptions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + notificationsapi.ListNotificationSubscriptionsResponse( + notification_subscriptions=[ + notificationsapi.NotificationSubscription(), + notificationsapi.NotificationSubscription(), + notificationsapi.NotificationSubscription(), + ], + next_page_token='abc', + ), + notificationsapi.ListNotificationSubscriptionsResponse( + notification_subscriptions=[], + next_page_token='def', + ), + notificationsapi.ListNotificationSubscriptionsResponse( + notification_subscriptions=[ + notificationsapi.NotificationSubscription(), + ], + next_page_token='ghi', + ), + notificationsapi.ListNotificationSubscriptionsResponse( + notification_subscriptions=[ + notificationsapi.NotificationSubscription(), + notificationsapi.NotificationSubscription(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_notification_subscriptions(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, notificationsapi.NotificationSubscription) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_notification_subscriptions_async_pages(): + client = NotificationsApiServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notification_subscriptions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + notificationsapi.ListNotificationSubscriptionsResponse( + notification_subscriptions=[ + notificationsapi.NotificationSubscription(), + notificationsapi.NotificationSubscription(), + notificationsapi.NotificationSubscription(), + ], + next_page_token='abc', + ), + notificationsapi.ListNotificationSubscriptionsResponse( + notification_subscriptions=[], + next_page_token='def', + ), + notificationsapi.ListNotificationSubscriptionsResponse( + notification_subscriptions=[ + notificationsapi.NotificationSubscription(), + ], + next_page_token='ghi', + ), + notificationsapi.ListNotificationSubscriptionsResponse( + notification_subscriptions=[ + notificationsapi.NotificationSubscription(), + notificationsapi.NotificationSubscription(), + ], + ), + 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_notification_subscriptions(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_notification_subscription_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 = NotificationsApiServiceClient( + 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_notification_subscription in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_notification_subscription] = mock_rpc + + request = {} + client.get_notification_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_notification_subscription(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_notification_subscription_rest_required_fields(request_type=notificationsapi.GetNotificationSubscriptionRequest): + transport_class = transports.NotificationsApiServiceRestTransport + + 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_notification_subscription._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_notification_subscription._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 = NotificationsApiServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = notificationsapi.NotificationSubscription() + # 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 = notificationsapi.NotificationSubscription.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_notification_subscription(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_notification_subscription_rest_unset_required_fields(): + transport = transports.NotificationsApiServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_notification_subscription._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_notification_subscription_rest_flattened(): + client = NotificationsApiServiceClient( + 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 = notificationsapi.NotificationSubscription() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/notificationsubscriptions/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 = notificationsapi.NotificationSubscription.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_notification_subscription(**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/notifications/v1beta/{name=accounts/*/notificationsubscriptions/*}" % client.transport._host, args[1]) + + +def test_get_notification_subscription_rest_flattened_error(transport: str = 'rest'): + client = NotificationsApiServiceClient( + 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_notification_subscription( + notificationsapi.GetNotificationSubscriptionRequest(), + name='name_value', + ) + + +def test_create_notification_subscription_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 = NotificationsApiServiceClient( + 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_notification_subscription in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_notification_subscription] = mock_rpc + + request = {} + client.create_notification_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_notification_subscription(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_notification_subscription_rest_required_fields(request_type=notificationsapi.CreateNotificationSubscriptionRequest): + transport_class = transports.NotificationsApiServiceRestTransport + + 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_notification_subscription._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_notification_subscription._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 = NotificationsApiServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = notificationsapi.NotificationSubscription() + # 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 = notificationsapi.NotificationSubscription.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_notification_subscription(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_notification_subscription_rest_unset_required_fields(): + transport = transports.NotificationsApiServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_notification_subscription._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "notificationSubscription", ))) + + +def test_create_notification_subscription_rest_flattened(): + client = NotificationsApiServiceClient( + 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 = notificationsapi.NotificationSubscription() + + # 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', + notification_subscription=notificationsapi.NotificationSubscription(all_managed_accounts=True), + ) + 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 = notificationsapi.NotificationSubscription.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_notification_subscription(**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/notifications/v1beta/{parent=accounts/*}/notificationsubscriptions" % client.transport._host, args[1]) + + +def test_create_notification_subscription_rest_flattened_error(transport: str = 'rest'): + client = NotificationsApiServiceClient( + 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_notification_subscription( + notificationsapi.CreateNotificationSubscriptionRequest(), + parent='parent_value', + notification_subscription=notificationsapi.NotificationSubscription(all_managed_accounts=True), + ) + + +def test_update_notification_subscription_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 = NotificationsApiServiceClient( + 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_notification_subscription in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_notification_subscription] = mock_rpc + + request = {} + client.update_notification_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_notification_subscription(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_notification_subscription_rest_required_fields(request_type=notificationsapi.UpdateNotificationSubscriptionRequest): + transport_class = transports.NotificationsApiServiceRestTransport + + 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_notification_subscription._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_notification_subscription._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 = NotificationsApiServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = notificationsapi.NotificationSubscription() + # 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 = notificationsapi.NotificationSubscription.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_notification_subscription(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_notification_subscription_rest_unset_required_fields(): + transport = transports.NotificationsApiServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_notification_subscription._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("notificationSubscription", ))) + + +def test_update_notification_subscription_rest_flattened(): + client = NotificationsApiServiceClient( + 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 = notificationsapi.NotificationSubscription() + + # get arguments that satisfy an http rule for this method + sample_request = {'notification_subscription': {'name': 'accounts/sample1/notificationsubscriptions/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + notification_subscription=notificationsapi.NotificationSubscription(all_managed_accounts=True), + 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 = notificationsapi.NotificationSubscription.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_notification_subscription(**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/notifications/v1beta/{notification_subscription.name=accounts/*/notificationsubscriptions/*}" % client.transport._host, args[1]) + + +def test_update_notification_subscription_rest_flattened_error(transport: str = 'rest'): + client = NotificationsApiServiceClient( + 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_notification_subscription( + notificationsapi.UpdateNotificationSubscriptionRequest(), + notification_subscription=notificationsapi.NotificationSubscription(all_managed_accounts=True), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_notification_subscription_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 = NotificationsApiServiceClient( + 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_notification_subscription in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_notification_subscription] = mock_rpc + + request = {} + client.delete_notification_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_notification_subscription(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_notification_subscription_rest_required_fields(request_type=notificationsapi.DeleteNotificationSubscriptionRequest): + transport_class = transports.NotificationsApiServiceRestTransport + + 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_notification_subscription._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_notification_subscription._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 = NotificationsApiServiceClient( + 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_notification_subscription(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_notification_subscription_rest_unset_required_fields(): + transport = transports.NotificationsApiServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_notification_subscription._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_delete_notification_subscription_rest_flattened(): + client = NotificationsApiServiceClient( + 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/notificationsubscriptions/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_notification_subscription(**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/notifications/v1beta/{name=accounts/*/notificationsubscriptions/*}" % client.transport._host, args[1]) + + +def test_delete_notification_subscription_rest_flattened_error(transport: str = 'rest'): + client = NotificationsApiServiceClient( + 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_notification_subscription( + notificationsapi.DeleteNotificationSubscriptionRequest(), + name='name_value', + ) + + +def test_list_notification_subscriptions_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 = NotificationsApiServiceClient( + 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_notification_subscriptions in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_notification_subscriptions] = mock_rpc + + request = {} + client.list_notification_subscriptions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_notification_subscriptions(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_notification_subscriptions_rest_required_fields(request_type=notificationsapi.ListNotificationSubscriptionsRequest): + transport_class = transports.NotificationsApiServiceRestTransport + + 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_notification_subscriptions._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_notification_subscriptions._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 = NotificationsApiServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = notificationsapi.ListNotificationSubscriptionsResponse() + # 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 = notificationsapi.ListNotificationSubscriptionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_notification_subscriptions(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_notification_subscriptions_rest_unset_required_fields(): + transport = transports.NotificationsApiServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_notification_subscriptions._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_notification_subscriptions_rest_flattened(): + client = NotificationsApiServiceClient( + 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 = notificationsapi.ListNotificationSubscriptionsResponse() + + # 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 = notificationsapi.ListNotificationSubscriptionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_notification_subscriptions(**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/notifications/v1beta/{parent=accounts/*}/notificationsubscriptions" % client.transport._host, args[1]) + + +def test_list_notification_subscriptions_rest_flattened_error(transport: str = 'rest'): + client = NotificationsApiServiceClient( + 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_notification_subscriptions( + notificationsapi.ListNotificationSubscriptionsRequest(), + parent='parent_value', + ) + + +def test_list_notification_subscriptions_rest_pager(transport: str = 'rest'): + client = NotificationsApiServiceClient( + 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 = ( + notificationsapi.ListNotificationSubscriptionsResponse( + notification_subscriptions=[ + notificationsapi.NotificationSubscription(), + notificationsapi.NotificationSubscription(), + notificationsapi.NotificationSubscription(), + ], + next_page_token='abc', + ), + notificationsapi.ListNotificationSubscriptionsResponse( + notification_subscriptions=[], + next_page_token='def', + ), + notificationsapi.ListNotificationSubscriptionsResponse( + notification_subscriptions=[ + notificationsapi.NotificationSubscription(), + ], + next_page_token='ghi', + ), + notificationsapi.ListNotificationSubscriptionsResponse( + notification_subscriptions=[ + notificationsapi.NotificationSubscription(), + notificationsapi.NotificationSubscription(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(notificationsapi.ListNotificationSubscriptionsResponse.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_notification_subscriptions(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, notificationsapi.NotificationSubscription) + for i in results) + + pages = list(client.list_notification_subscriptions(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.NotificationsApiServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = NotificationsApiServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.NotificationsApiServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = NotificationsApiServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.NotificationsApiServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = NotificationsApiServiceClient( + 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 = NotificationsApiServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.NotificationsApiServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = NotificationsApiServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.NotificationsApiServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = NotificationsApiServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.NotificationsApiServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.NotificationsApiServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.NotificationsApiServiceGrpcTransport, + transports.NotificationsApiServiceGrpcAsyncIOTransport, + transports.NotificationsApiServiceRestTransport, +]) +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 = NotificationsApiServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = NotificationsApiServiceClient( + 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_notification_subscription_empty_call_grpc(): + client = NotificationsApiServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_notification_subscription), + '__call__') as call: + call.return_value = notificationsapi.NotificationSubscription() + client.get_notification_subscription(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = notificationsapi.GetNotificationSubscriptionRequest() + + assert args[0] == request_msg + + +# This 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_notification_subscription_empty_call_grpc(): + client = NotificationsApiServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_notification_subscription), + '__call__') as call: + call.return_value = notificationsapi.NotificationSubscription() + client.create_notification_subscription(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = notificationsapi.CreateNotificationSubscriptionRequest() + + assert args[0] == request_msg + + +# This 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_notification_subscription_empty_call_grpc(): + client = NotificationsApiServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_subscription), + '__call__') as call: + call.return_value = notificationsapi.NotificationSubscription() + client.update_notification_subscription(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = notificationsapi.UpdateNotificationSubscriptionRequest() + + assert args[0] == request_msg + + +# This 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_notification_subscription_empty_call_grpc(): + client = NotificationsApiServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_notification_subscription), + '__call__') as call: + call.return_value = None + client.delete_notification_subscription(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = notificationsapi.DeleteNotificationSubscriptionRequest() + + assert args[0] == request_msg + + +# This 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_notification_subscriptions_empty_call_grpc(): + client = NotificationsApiServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_notification_subscriptions), + '__call__') as call: + call.return_value = notificationsapi.ListNotificationSubscriptionsResponse() + client.list_notification_subscriptions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = notificationsapi.ListNotificationSubscriptionsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = NotificationsApiServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = NotificationsApiServiceAsyncClient( + 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_notification_subscription_empty_call_grpc_asyncio(): + client = NotificationsApiServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_notification_subscription), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notificationsapi.NotificationSubscription( + name='name_value', + registered_event=notificationsapi.NotificationSubscription.NotificationEventType.PRODUCT_STATUS_CHANGE, + call_back_uri='call_back_uri_value', + )) + await client.get_notification_subscription(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = notificationsapi.GetNotificationSubscriptionRequest() + + assert args[0] == request_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_notification_subscription_empty_call_grpc_asyncio(): + client = NotificationsApiServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_notification_subscription), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notificationsapi.NotificationSubscription( + name='name_value', + registered_event=notificationsapi.NotificationSubscription.NotificationEventType.PRODUCT_STATUS_CHANGE, + call_back_uri='call_back_uri_value', + )) + await client.create_notification_subscription(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = notificationsapi.CreateNotificationSubscriptionRequest() + + assert args[0] == request_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_notification_subscription_empty_call_grpc_asyncio(): + client = NotificationsApiServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_subscription), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notificationsapi.NotificationSubscription( + name='name_value', + registered_event=notificationsapi.NotificationSubscription.NotificationEventType.PRODUCT_STATUS_CHANGE, + call_back_uri='call_back_uri_value', + )) + await client.update_notification_subscription(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = notificationsapi.UpdateNotificationSubscriptionRequest() + + assert args[0] == request_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_notification_subscription_empty_call_grpc_asyncio(): + client = NotificationsApiServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_notification_subscription), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_notification_subscription(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = notificationsapi.DeleteNotificationSubscriptionRequest() + + assert args[0] == request_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_notification_subscriptions_empty_call_grpc_asyncio(): + client = NotificationsApiServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_notification_subscriptions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notificationsapi.ListNotificationSubscriptionsResponse( + next_page_token='next_page_token_value', + )) + await client.list_notification_subscriptions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = notificationsapi.ListNotificationSubscriptionsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = NotificationsApiServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_notification_subscription_rest_bad_request(request_type=notificationsapi.GetNotificationSubscriptionRequest): + client = NotificationsApiServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/notificationsubscriptions/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_notification_subscription(request) + + +@pytest.mark.parametrize("request_type", [ + notificationsapi.GetNotificationSubscriptionRequest, + dict, +]) +def test_get_notification_subscription_rest_call_success(request_type): + client = NotificationsApiServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/notificationsubscriptions/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 = notificationsapi.NotificationSubscription( + name='name_value', + registered_event=notificationsapi.NotificationSubscription.NotificationEventType.PRODUCT_STATUS_CHANGE, + call_back_uri='call_back_uri_value', + all_managed_accounts=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 = notificationsapi.NotificationSubscription.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_notification_subscription(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, notificationsapi.NotificationSubscription) + assert response.name == 'name_value' + assert response.registered_event == notificationsapi.NotificationSubscription.NotificationEventType.PRODUCT_STATUS_CHANGE + assert response.call_back_uri == 'call_back_uri_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_notification_subscription_rest_interceptors(null_interceptor): + transport = transports.NotificationsApiServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NotificationsApiServiceRestInterceptor(), + ) + client = NotificationsApiServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.NotificationsApiServiceRestInterceptor, "post_get_notification_subscription") as post, \ + mock.patch.object(transports.NotificationsApiServiceRestInterceptor, "pre_get_notification_subscription") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = notificationsapi.GetNotificationSubscriptionRequest.pb(notificationsapi.GetNotificationSubscriptionRequest()) + 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 = notificationsapi.NotificationSubscription.to_json(notificationsapi.NotificationSubscription()) + req.return_value.content = return_value + + request = notificationsapi.GetNotificationSubscriptionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = notificationsapi.NotificationSubscription() + + client.get_notification_subscription(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_notification_subscription_rest_bad_request(request_type=notificationsapi.CreateNotificationSubscriptionRequest): + client = NotificationsApiServiceClient( + 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_notification_subscription(request) + + +@pytest.mark.parametrize("request_type", [ + notificationsapi.CreateNotificationSubscriptionRequest, + dict, +]) +def test_create_notification_subscription_rest_call_success(request_type): + client = NotificationsApiServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + request_init["notification_subscription"] = {'all_managed_accounts': True, 'target_account': 'target_account_value', 'name': 'name_value', 'registered_event': 1, 'call_back_uri': 'call_back_uri_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 = notificationsapi.CreateNotificationSubscriptionRequest.meta.fields["notification_subscription"] + + 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["notification_subscription"].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["notification_subscription"][field])): + del request_init["notification_subscription"][field][i][subfield] + else: + del request_init["notification_subscription"][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 = notificationsapi.NotificationSubscription( + name='name_value', + registered_event=notificationsapi.NotificationSubscription.NotificationEventType.PRODUCT_STATUS_CHANGE, + call_back_uri='call_back_uri_value', + all_managed_accounts=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 = notificationsapi.NotificationSubscription.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_notification_subscription(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, notificationsapi.NotificationSubscription) + assert response.name == 'name_value' + assert response.registered_event == notificationsapi.NotificationSubscription.NotificationEventType.PRODUCT_STATUS_CHANGE + assert response.call_back_uri == 'call_back_uri_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_notification_subscription_rest_interceptors(null_interceptor): + transport = transports.NotificationsApiServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NotificationsApiServiceRestInterceptor(), + ) + client = NotificationsApiServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.NotificationsApiServiceRestInterceptor, "post_create_notification_subscription") as post, \ + mock.patch.object(transports.NotificationsApiServiceRestInterceptor, "pre_create_notification_subscription") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = notificationsapi.CreateNotificationSubscriptionRequest.pb(notificationsapi.CreateNotificationSubscriptionRequest()) + 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 = notificationsapi.NotificationSubscription.to_json(notificationsapi.NotificationSubscription()) + req.return_value.content = return_value + + request = notificationsapi.CreateNotificationSubscriptionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = notificationsapi.NotificationSubscription() + + client.create_notification_subscription(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_notification_subscription_rest_bad_request(request_type=notificationsapi.UpdateNotificationSubscriptionRequest): + client = NotificationsApiServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'notification_subscription': {'name': 'accounts/sample1/notificationsubscriptions/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_notification_subscription(request) + + +@pytest.mark.parametrize("request_type", [ + notificationsapi.UpdateNotificationSubscriptionRequest, + dict, +]) +def test_update_notification_subscription_rest_call_success(request_type): + client = NotificationsApiServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'notification_subscription': {'name': 'accounts/sample1/notificationsubscriptions/sample2'}} + request_init["notification_subscription"] = {'all_managed_accounts': True, 'target_account': 'target_account_value', 'name': 'accounts/sample1/notificationsubscriptions/sample2', 'registered_event': 1, 'call_back_uri': 'call_back_uri_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 = notificationsapi.UpdateNotificationSubscriptionRequest.meta.fields["notification_subscription"] + + 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["notification_subscription"].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["notification_subscription"][field])): + del request_init["notification_subscription"][field][i][subfield] + else: + del request_init["notification_subscription"][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 = notificationsapi.NotificationSubscription( + name='name_value', + registered_event=notificationsapi.NotificationSubscription.NotificationEventType.PRODUCT_STATUS_CHANGE, + call_back_uri='call_back_uri_value', + all_managed_accounts=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 = notificationsapi.NotificationSubscription.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_notification_subscription(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, notificationsapi.NotificationSubscription) + assert response.name == 'name_value' + assert response.registered_event == notificationsapi.NotificationSubscription.NotificationEventType.PRODUCT_STATUS_CHANGE + assert response.call_back_uri == 'call_back_uri_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_notification_subscription_rest_interceptors(null_interceptor): + transport = transports.NotificationsApiServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NotificationsApiServiceRestInterceptor(), + ) + client = NotificationsApiServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.NotificationsApiServiceRestInterceptor, "post_update_notification_subscription") as post, \ + mock.patch.object(transports.NotificationsApiServiceRestInterceptor, "pre_update_notification_subscription") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = notificationsapi.UpdateNotificationSubscriptionRequest.pb(notificationsapi.UpdateNotificationSubscriptionRequest()) + 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 = notificationsapi.NotificationSubscription.to_json(notificationsapi.NotificationSubscription()) + req.return_value.content = return_value + + request = notificationsapi.UpdateNotificationSubscriptionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = notificationsapi.NotificationSubscription() + + client.update_notification_subscription(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_notification_subscription_rest_bad_request(request_type=notificationsapi.DeleteNotificationSubscriptionRequest): + client = NotificationsApiServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/notificationsubscriptions/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_notification_subscription(request) + + +@pytest.mark.parametrize("request_type", [ + notificationsapi.DeleteNotificationSubscriptionRequest, + dict, +]) +def test_delete_notification_subscription_rest_call_success(request_type): + client = NotificationsApiServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/notificationsubscriptions/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_notification_subscription(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_notification_subscription_rest_interceptors(null_interceptor): + transport = transports.NotificationsApiServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NotificationsApiServiceRestInterceptor(), + ) + client = NotificationsApiServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.NotificationsApiServiceRestInterceptor, "pre_delete_notification_subscription") as pre: + pre.assert_not_called() + pb_message = notificationsapi.DeleteNotificationSubscriptionRequest.pb(notificationsapi.DeleteNotificationSubscriptionRequest()) + 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 = notificationsapi.DeleteNotificationSubscriptionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_notification_subscription(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_list_notification_subscriptions_rest_bad_request(request_type=notificationsapi.ListNotificationSubscriptionsRequest): + client = NotificationsApiServiceClient( + 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_notification_subscriptions(request) + + +@pytest.mark.parametrize("request_type", [ + notificationsapi.ListNotificationSubscriptionsRequest, + dict, +]) +def test_list_notification_subscriptions_rest_call_success(request_type): + client = NotificationsApiServiceClient( + 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 = notificationsapi.ListNotificationSubscriptionsResponse( + 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 = notificationsapi.ListNotificationSubscriptionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_notification_subscriptions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNotificationSubscriptionsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_notification_subscriptions_rest_interceptors(null_interceptor): + transport = transports.NotificationsApiServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NotificationsApiServiceRestInterceptor(), + ) + client = NotificationsApiServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.NotificationsApiServiceRestInterceptor, "post_list_notification_subscriptions") as post, \ + mock.patch.object(transports.NotificationsApiServiceRestInterceptor, "pre_list_notification_subscriptions") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = notificationsapi.ListNotificationSubscriptionsRequest.pb(notificationsapi.ListNotificationSubscriptionsRequest()) + 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 = notificationsapi.ListNotificationSubscriptionsResponse.to_json(notificationsapi.ListNotificationSubscriptionsResponse()) + req.return_value.content = return_value + + request = notificationsapi.ListNotificationSubscriptionsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = notificationsapi.ListNotificationSubscriptionsResponse() + + client.list_notification_subscriptions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + +def test_initialize_client_w_rest(): + client = NotificationsApiServiceClient( + 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_notification_subscription_empty_call_rest(): + client = NotificationsApiServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_notification_subscription), + '__call__') as call: + client.get_notification_subscription(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = notificationsapi.GetNotificationSubscriptionRequest() + + assert args[0] == request_msg + + +# This 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_notification_subscription_empty_call_rest(): + client = NotificationsApiServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_notification_subscription), + '__call__') as call: + client.create_notification_subscription(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = notificationsapi.CreateNotificationSubscriptionRequest() + + assert args[0] == request_msg + + +# This 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_notification_subscription_empty_call_rest(): + client = NotificationsApiServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_subscription), + '__call__') as call: + client.update_notification_subscription(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = notificationsapi.UpdateNotificationSubscriptionRequest() + + assert args[0] == request_msg + + +# This 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_notification_subscription_empty_call_rest(): + client = NotificationsApiServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_notification_subscription), + '__call__') as call: + client.delete_notification_subscription(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = notificationsapi.DeleteNotificationSubscriptionRequest() + + assert args[0] == request_msg + + +# This 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_notification_subscriptions_empty_call_rest(): + client = NotificationsApiServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_notification_subscriptions), + '__call__') as call: + client.list_notification_subscriptions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = notificationsapi.ListNotificationSubscriptionsRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = NotificationsApiServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.NotificationsApiServiceGrpcTransport, + ) + +def test_notifications_api_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.NotificationsApiServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_notifications_api_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_notifications_v1beta.services.notifications_api_service.transports.NotificationsApiServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.NotificationsApiServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_notification_subscription', + 'create_notification_subscription', + 'update_notification_subscription', + 'delete_notification_subscription', + 'list_notification_subscriptions', + ) + 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_notifications_api_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_notifications_v1beta.services.notifications_api_service.transports.NotificationsApiServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.NotificationsApiServiceTransport( + 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_notifications_api_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_notifications_v1beta.services.notifications_api_service.transports.NotificationsApiServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.NotificationsApiServiceTransport() + adc.assert_called_once() + + +def test_notifications_api_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) + NotificationsApiServiceClient() + 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.NotificationsApiServiceGrpcTransport, + transports.NotificationsApiServiceGrpcAsyncIOTransport, + ], +) +def test_notifications_api_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.NotificationsApiServiceGrpcTransport, + transports.NotificationsApiServiceGrpcAsyncIOTransport, + transports.NotificationsApiServiceRestTransport, + ], +) +def test_notifications_api_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.NotificationsApiServiceGrpcTransport, grpc_helpers), + (transports.NotificationsApiServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_notifications_api_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.NotificationsApiServiceGrpcTransport, transports.NotificationsApiServiceGrpcAsyncIOTransport]) +def test_notifications_api_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_notifications_api_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.NotificationsApiServiceRestTransport ( + 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_notifications_api_service_host_no_port(transport_name): + client = NotificationsApiServiceClient( + 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_notifications_api_service_host_with_port(transport_name): + client = NotificationsApiServiceClient( + 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_notifications_api_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = NotificationsApiServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = NotificationsApiServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_notification_subscription._session + session2 = client2.transport.get_notification_subscription._session + assert session1 != session2 + session1 = client1.transport.create_notification_subscription._session + session2 = client2.transport.create_notification_subscription._session + assert session1 != session2 + session1 = client1.transport.update_notification_subscription._session + session2 = client2.transport.update_notification_subscription._session + assert session1 != session2 + session1 = client1.transport.delete_notification_subscription._session + session2 = client2.transport.delete_notification_subscription._session + assert session1 != session2 + session1 = client1.transport.list_notification_subscriptions._session + session2 = client2.transport.list_notification_subscriptions._session + assert session1 != session2 +def test_notifications_api_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.NotificationsApiServiceGrpcTransport( + 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_notifications_api_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.NotificationsApiServiceGrpcAsyncIOTransport( + 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.NotificationsApiServiceGrpcTransport, transports.NotificationsApiServiceGrpcAsyncIOTransport]) +def test_notifications_api_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.NotificationsApiServiceGrpcTransport, transports.NotificationsApiServiceGrpcAsyncIOTransport]) +def test_notifications_api_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_notification_subscription_path(): + account = "squid" + notification_subscription = "clam" + expected = "accounts/{account}/notificationsubscriptions/{notification_subscription}".format(account=account, notification_subscription=notification_subscription, ) + actual = NotificationsApiServiceClient.notification_subscription_path(account, notification_subscription) + assert expected == actual + + +def test_parse_notification_subscription_path(): + expected = { + "account": "whelk", + "notification_subscription": "octopus", + } + path = NotificationsApiServiceClient.notification_subscription_path(**expected) + + # Check that the path construction is reversible. + actual = NotificationsApiServiceClient.parse_notification_subscription_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = NotificationsApiServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = NotificationsApiServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = NotificationsApiServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = NotificationsApiServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = NotificationsApiServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = NotificationsApiServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = NotificationsApiServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = NotificationsApiServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = NotificationsApiServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = NotificationsApiServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = NotificationsApiServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = NotificationsApiServiceClient.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 = NotificationsApiServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = NotificationsApiServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = NotificationsApiServiceClient.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.NotificationsApiServiceTransport, '_prep_wrapped_messages') as prep: + client = NotificationsApiServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.NotificationsApiServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = NotificationsApiServiceClient.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 = NotificationsApiServiceClient( + 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 = NotificationsApiServiceAsyncClient( + 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 = NotificationsApiServiceClient( + 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 = NotificationsApiServiceClient( + 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", [ + (NotificationsApiServiceClient, transports.NotificationsApiServiceGrpcTransport), + (NotificationsApiServiceAsyncClient, transports.NotificationsApiServiceGrpcAsyncIOTransport), +]) +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-promotions/v1beta/.coveragerc b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/.coveragerc new file mode 100644 index 000000000000..dafc77479871 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/shopping/merchant_promotions/__init__.py + google/shopping/merchant_promotions/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-promotions/v1beta/.flake8 b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/MANIFEST.in b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/MANIFEST.in new file mode 100644 index 000000000000..4000aef85aac --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/shopping/merchant_promotions *.py +recursive-include google/shopping/merchant_promotions_v1beta *.py diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/README.rst b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/README.rst new file mode 100644 index 000000000000..cb2860617dd9 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Shopping Merchant Promotions 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 Promotions 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 diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/_static/custom.css b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/conf.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/conf.py new file mode 100644 index 000000000000..903cf3292f1b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-promotions 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("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# 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.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +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-promotions" +copyright = u"2023, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# 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 = 'en' + +# 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"] + +# 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 Python", + "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-promotions-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-promotions.tex", + u"google-shopping-merchant-promotions 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-promotions", + u"Google Shopping Merchant Promotions 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-promotions", + u"google-shopping-merchant-promotions Documentation", + author, + "google-shopping-merchant-promotions", + "GAPIC library for Google Shopping Merchant Promotions API", + "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": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", 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-promotions/v1beta/docs/index.rst b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/index.rst new file mode 100644 index 000000000000..bd406fae2308 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + merchant_promotions_v1beta/services_ + merchant_promotions_v1beta/types_ diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/merchant_promotions_v1beta/promotions_service.rst b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/merchant_promotions_v1beta/promotions_service.rst new file mode 100644 index 000000000000..229477aebf39 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/merchant_promotions_v1beta/promotions_service.rst @@ -0,0 +1,10 @@ +PromotionsService +----------------------------------- + +.. automodule:: google.shopping.merchant_promotions_v1beta.services.promotions_service + :members: + :inherited-members: + +.. automodule:: google.shopping.merchant_promotions_v1beta.services.promotions_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/merchant_promotions_v1beta/services_.rst b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/merchant_promotions_v1beta/services_.rst new file mode 100644 index 000000000000..befbacf009f8 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/merchant_promotions_v1beta/services_.rst @@ -0,0 +1,6 @@ +Services for Google Shopping Merchant Promotions v1beta API +=========================================================== +.. toctree:: + :maxdepth: 2 + + promotions_service diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/merchant_promotions_v1beta/types_.rst b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/merchant_promotions_v1beta/types_.rst new file mode 100644 index 000000000000..a95c03a1e319 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/merchant_promotions_v1beta/types_.rst @@ -0,0 +1,6 @@ +Types for Google Shopping Merchant Promotions v1beta API +======================================================== + +.. automodule:: google.shopping.merchant_promotions_v1beta.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions/__init__.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions/__init__.py new file mode 100644 index 000000000000..443803dbb301 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions/__init__.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_promotions import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.shopping.merchant_promotions_v1beta.services.promotions_service.client import PromotionsServiceClient +from google.shopping.merchant_promotions_v1beta.services.promotions_service.async_client import PromotionsServiceAsyncClient + +from google.shopping.merchant_promotions_v1beta.types.promotions import GetPromotionRequest +from google.shopping.merchant_promotions_v1beta.types.promotions import InsertPromotionRequest +from google.shopping.merchant_promotions_v1beta.types.promotions import ListPromotionsRequest +from google.shopping.merchant_promotions_v1beta.types.promotions import ListPromotionsResponse +from google.shopping.merchant_promotions_v1beta.types.promotions import Promotion +from google.shopping.merchant_promotions_v1beta.types.promotions_common import Attributes +from google.shopping.merchant_promotions_v1beta.types.promotions_common import PromotionStatus +from google.shopping.merchant_promotions_v1beta.types.promotions_common import CouponValueType +from google.shopping.merchant_promotions_v1beta.types.promotions_common import OfferType +from google.shopping.merchant_promotions_v1beta.types.promotions_common import ProductApplicability +from google.shopping.merchant_promotions_v1beta.types.promotions_common import RedemptionChannel +from google.shopping.merchant_promotions_v1beta.types.promotions_common import StoreApplicability + +__all__ = ('PromotionsServiceClient', + 'PromotionsServiceAsyncClient', + 'GetPromotionRequest', + 'InsertPromotionRequest', + 'ListPromotionsRequest', + 'ListPromotionsResponse', + 'Promotion', + 'Attributes', + 'PromotionStatus', + 'CouponValueType', + 'OfferType', + 'ProductApplicability', + 'RedemptionChannel', + 'StoreApplicability', +) diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions/gapic_version.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-promotions/v1beta/google/shopping/merchant_promotions/py.typed b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions/py.typed new file mode 100644 index 000000000000..53f2425ea9b3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-shopping-merchant-promotions package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/__init__.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/__init__.py new file mode 100644 index 000000000000..d93e5699df4b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/__init__.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_promotions_v1beta import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.promotions_service import PromotionsServiceClient +from .services.promotions_service import PromotionsServiceAsyncClient + +from .types.promotions import GetPromotionRequest +from .types.promotions import InsertPromotionRequest +from .types.promotions import ListPromotionsRequest +from .types.promotions import ListPromotionsResponse +from .types.promotions import Promotion +from .types.promotions_common import Attributes +from .types.promotions_common import PromotionStatus +from .types.promotions_common import CouponValueType +from .types.promotions_common import OfferType +from .types.promotions_common import ProductApplicability +from .types.promotions_common import RedemptionChannel +from .types.promotions_common import StoreApplicability + +__all__ = ( + 'PromotionsServiceAsyncClient', +'Attributes', +'CouponValueType', +'GetPromotionRequest', +'InsertPromotionRequest', +'ListPromotionsRequest', +'ListPromotionsResponse', +'OfferType', +'ProductApplicability', +'Promotion', +'PromotionStatus', +'PromotionsServiceClient', +'RedemptionChannel', +'StoreApplicability', +) diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/gapic_metadata.json b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/gapic_metadata.json new file mode 100644 index 000000000000..0f9f123e2e18 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/gapic_metadata.json @@ -0,0 +1,73 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.shopping.merchant_promotions_v1beta", + "protoPackage": "google.shopping.merchant.promotions.v1beta", + "schema": "1.0", + "services": { + "PromotionsService": { + "clients": { + "grpc": { + "libraryClient": "PromotionsServiceClient", + "rpcs": { + "GetPromotion": { + "methods": [ + "get_promotion" + ] + }, + "InsertPromotion": { + "methods": [ + "insert_promotion" + ] + }, + "ListPromotions": { + "methods": [ + "list_promotions" + ] + } + } + }, + "grpc-async": { + "libraryClient": "PromotionsServiceAsyncClient", + "rpcs": { + "GetPromotion": { + "methods": [ + "get_promotion" + ] + }, + "InsertPromotion": { + "methods": [ + "insert_promotion" + ] + }, + "ListPromotions": { + "methods": [ + "list_promotions" + ] + } + } + }, + "rest": { + "libraryClient": "PromotionsServiceClient", + "rpcs": { + "GetPromotion": { + "methods": [ + "get_promotion" + ] + }, + "InsertPromotion": { + "methods": [ + "insert_promotion" + ] + }, + "ListPromotions": { + "methods": [ + "list_promotions" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/gapic_version.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-promotions/v1beta/google/shopping/merchant_promotions_v1beta/py.typed b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/py.typed new file mode 100644 index 000000000000..53f2425ea9b3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-shopping-merchant-promotions package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/__init__.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/__init__.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/__init__.py new file mode 100644 index 000000000000..3cebeff587b6 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 PromotionsServiceClient +from .async_client import PromotionsServiceAsyncClient + +__all__ = ( + 'PromotionsServiceClient', + 'PromotionsServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/async_client.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/async_client.py new file mode 100644 index 000000000000..11d96f941820 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/async_client.py @@ -0,0 +1,612 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_promotions_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 + + +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_promotions_v1beta.services.promotions_service import pagers +from google.shopping.merchant_promotions_v1beta.types import promotions +from google.shopping.merchant_promotions_v1beta.types import promotions_common +from google.shopping.type.types import types +from .transports.base import PromotionsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import PromotionsServiceGrpcAsyncIOTransport +from .client import PromotionsServiceClient + +try: + from google.api_core import client_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 PromotionsServiceAsyncClient: + """Service to manage promotions for products.""" + + _client: PromotionsServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = PromotionsServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = PromotionsServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = PromotionsServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = PromotionsServiceClient._DEFAULT_UNIVERSE + + promotion_path = staticmethod(PromotionsServiceClient.promotion_path) + parse_promotion_path = staticmethod(PromotionsServiceClient.parse_promotion_path) + common_billing_account_path = staticmethod(PromotionsServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(PromotionsServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(PromotionsServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(PromotionsServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(PromotionsServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(PromotionsServiceClient.parse_common_organization_path) + common_project_path = staticmethod(PromotionsServiceClient.common_project_path) + parse_common_project_path = staticmethod(PromotionsServiceClient.parse_common_project_path) + common_location_path = staticmethod(PromotionsServiceClient.common_location_path) + parse_common_location_path = staticmethod(PromotionsServiceClient.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: + PromotionsServiceAsyncClient: The constructed client. + """ + return PromotionsServiceClient.from_service_account_info.__func__(PromotionsServiceAsyncClient, 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: + PromotionsServiceAsyncClient: The constructed client. + """ + return PromotionsServiceClient.from_service_account_file.__func__(PromotionsServiceAsyncClient, 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 PromotionsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> PromotionsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + PromotionsServiceTransport: 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 = PromotionsServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, PromotionsServiceTransport, Callable[..., PromotionsServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the promotions 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,PromotionsServiceTransport,Callable[..., PromotionsServiceTransport]]]): + 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 PromotionsServiceTransport 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 = PromotionsServiceClient( + 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.promotions_v1beta.PromotionsServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.promotions.v1beta.PromotionsService", + "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.promotions.v1beta.PromotionsService", + "credentialsType": None, + } + ) + + async def insert_promotion(self, + request: Optional[Union[promotions.InsertPromotionRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> promotions.Promotion: + r"""Inserts a promotion for your Merchant Center account. + If the promotion already exists, then it updates the + promotion instead. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_promotions_v1beta + + async def sample_insert_promotion(): + # Create a client + client = merchant_promotions_v1beta.PromotionsServiceAsyncClient() + + # Initialize request argument(s) + promotion = merchant_promotions_v1beta.Promotion() + promotion.promotion_id = "promotion_id_value" + promotion.content_language = "content_language_value" + promotion.target_country = "target_country_value" + promotion.redemption_channel = ['ONLINE'] + + request = merchant_promotions_v1beta.InsertPromotionRequest( + parent="parent_value", + promotion=promotion, + data_source="data_source_value", + ) + + # Make the request + response = await client.insert_promotion(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_promotions_v1beta.types.InsertPromotionRequest, dict]]): + The request object. Request message for the ``InsertPromotion`` 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_promotions_v1beta.types.Promotion: + Represents a promotion. See the following articles for + more details. + + Required promotion input attributes to pass data + validation checks are primarily defined below: + + \* [Promotions data + specification](\ https://support.google.com/merchants/answer/2906014) + \* [Local promotions data + specification](\ https://support.google.com/merchants/answer/10146130) + + After inserting, updating a promotion input, it may + take several minutes before the final promotion can + be retrieved. + + """ + # 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, promotions.InsertPromotionRequest): + request = promotions.InsertPromotionRequest(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_promotion] + + # Certain 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 get_promotion(self, + request: Optional[Union[promotions.GetPromotionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> promotions.Promotion: + r"""Retrieves the promotion from your Merchant Center + account. + After inserting or updating a promotion input, it may + take several minutes before the updated promotion can be + retrieved. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_promotions_v1beta + + async def sample_get_promotion(): + # Create a client + client = merchant_promotions_v1beta.PromotionsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_promotions_v1beta.GetPromotionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_promotion(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_promotions_v1beta.types.GetPromotionRequest, dict]]): + The request object. Request message for the ``GetPromotion`` method. + name (:class:`str`): + Required. The name of the promotion to retrieve. Format: + ``accounts/{account}/promotions/{promotions}`` + + 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_promotions_v1beta.types.Promotion: + Represents a promotion. See the following articles for + more details. + + Required promotion input attributes to pass data + validation checks are primarily defined below: + + \* [Promotions data + specification](\ https://support.google.com/merchants/answer/2906014) + \* [Local promotions data + specification](\ https://support.google.com/merchants/answer/10146130) + + After inserting, updating a promotion input, it may + take several minutes before the final promotion can + be retrieved. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, promotions.GetPromotionRequest): + request = promotions.GetPromotionRequest(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_promotion] + + # Certain 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_promotions(self, + request: Optional[Union[promotions.ListPromotionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListPromotionsAsyncPager: + r"""Lists the promotions in your Merchant Center account. The + response might contain fewer items than specified by + ``pageSize``. Rely on ``pageToken`` to determine if there are + more items to be requested. + + After inserting or updating a promotion, it may take several + minutes before the updated processed promotion can be retrieved. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_promotions_v1beta + + async def sample_list_promotions(): + # Create a client + client = merchant_promotions_v1beta.PromotionsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_promotions_v1beta.ListPromotionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_promotions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_promotions_v1beta.types.ListPromotionsRequest, dict]]): + The request object. Request message for the ``ListPromotions`` method. + parent (:class:`str`): + Required. The account to list processed promotions 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_promotions_v1beta.services.promotions_service.pagers.ListPromotionsAsyncPager: + Response message for the ListPromotions 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, promotions.ListPromotionsRequest): + request = promotions.ListPromotionsRequest(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_promotions] + + # Certain 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.ListPromotionsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "PromotionsServiceAsyncClient": + 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__) + + +__all__ = ( + "PromotionsServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/client.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/client.py new file mode 100644 index 000000000000..85a4938180cd --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/client.py @@ -0,0 +1,946 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +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_promotions_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 + +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_promotions_v1beta.services.promotions_service import pagers +from google.shopping.merchant_promotions_v1beta.types import promotions +from google.shopping.merchant_promotions_v1beta.types import promotions_common +from google.shopping.type.types import types +from .transports.base import PromotionsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import PromotionsServiceGrpcTransport +from .transports.grpc_asyncio import PromotionsServiceGrpcAsyncIOTransport +from .transports.rest import PromotionsServiceRestTransport + + +class PromotionsServiceClientMeta(type): + """Metaclass for the PromotionsService 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[PromotionsServiceTransport]] + _transport_registry["grpc"] = PromotionsServiceGrpcTransport + _transport_registry["grpc_asyncio"] = PromotionsServiceGrpcAsyncIOTransport + _transport_registry["rest"] = PromotionsServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[PromotionsServiceTransport]: + """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 PromotionsServiceClient(metaclass=PromotionsServiceClientMeta): + """Service to manage promotions for products.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "merchantapi.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "merchantapi.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PromotionsServiceClient: 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: + PromotionsServiceClient: 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) -> PromotionsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + PromotionsServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def promotion_path(account: str,promotion: str,) -> str: + """Returns a fully-qualified promotion string.""" + return "accounts/{account}/promotions/{promotion}".format(account=account, promotion=promotion, ) + + @staticmethod + def parse_promotion_path(path: str) -> Dict[str,str]: + """Parses a promotion path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/promotions/(?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 = PromotionsServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = PromotionsServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = PromotionsServiceClient._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 = PromotionsServiceClient._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 + + @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, PromotionsServiceTransport, Callable[..., PromotionsServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the promotions 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,PromotionsServiceTransport,Callable[..., PromotionsServiceTransport]]]): + 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 PromotionsServiceTransport 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 = PromotionsServiceClient._read_environment_variables() + self._client_cert_source = PromotionsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = PromotionsServiceClient._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, PromotionsServiceTransport) + if transport_provided: + # transport is a PromotionsServiceTransport 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(PromotionsServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + PromotionsServiceClient._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[PromotionsServiceTransport], Callable[..., PromotionsServiceTransport]] = ( + PromotionsServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., PromotionsServiceTransport], 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.promotions_v1beta.PromotionsServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.promotions.v1beta.PromotionsService", + "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.promotions.v1beta.PromotionsService", + "credentialsType": None, + } + ) + + def insert_promotion(self, + request: Optional[Union[promotions.InsertPromotionRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> promotions.Promotion: + r"""Inserts a promotion for your Merchant Center account. + If the promotion already exists, then it updates the + promotion instead. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_promotions_v1beta + + def sample_insert_promotion(): + # Create a client + client = merchant_promotions_v1beta.PromotionsServiceClient() + + # Initialize request argument(s) + promotion = merchant_promotions_v1beta.Promotion() + promotion.promotion_id = "promotion_id_value" + promotion.content_language = "content_language_value" + promotion.target_country = "target_country_value" + promotion.redemption_channel = ['ONLINE'] + + request = merchant_promotions_v1beta.InsertPromotionRequest( + parent="parent_value", + promotion=promotion, + data_source="data_source_value", + ) + + # Make the request + response = client.insert_promotion(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_promotions_v1beta.types.InsertPromotionRequest, dict]): + The request object. Request message for the ``InsertPromotion`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.shopping.merchant_promotions_v1beta.types.Promotion: + Represents a promotion. See the following articles for + more details. + + Required promotion input attributes to pass data + validation checks are primarily defined below: + + \* [Promotions data + specification](\ https://support.google.com/merchants/answer/2906014) + \* [Local promotions data + specification](\ https://support.google.com/merchants/answer/10146130) + + After inserting, updating a promotion input, it may + take several minutes before the final promotion can + be retrieved. + + """ + # 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, promotions.InsertPromotionRequest): + request = promotions.InsertPromotionRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.insert_promotion] + + # Certain 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 get_promotion(self, + request: Optional[Union[promotions.GetPromotionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> promotions.Promotion: + r"""Retrieves the promotion from your Merchant Center + account. + After inserting or updating a promotion input, it may + take several minutes before the updated promotion can be + retrieved. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_promotions_v1beta + + def sample_get_promotion(): + # Create a client + client = merchant_promotions_v1beta.PromotionsServiceClient() + + # Initialize request argument(s) + request = merchant_promotions_v1beta.GetPromotionRequest( + name="name_value", + ) + + # Make the request + response = client.get_promotion(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_promotions_v1beta.types.GetPromotionRequest, dict]): + The request object. Request message for the ``GetPromotion`` method. + name (str): + Required. The name of the promotion to retrieve. Format: + ``accounts/{account}/promotions/{promotions}`` + + 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_promotions_v1beta.types.Promotion: + Represents a promotion. See the following articles for + more details. + + Required promotion input attributes to pass data + validation checks are primarily defined below: + + \* [Promotions data + specification](\ https://support.google.com/merchants/answer/2906014) + \* [Local promotions data + specification](\ https://support.google.com/merchants/answer/10146130) + + After inserting, updating a promotion input, it may + take several minutes before the final promotion can + be retrieved. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, promotions.GetPromotionRequest): + request = promotions.GetPromotionRequest(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_promotion] + + # Certain 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_promotions(self, + request: Optional[Union[promotions.ListPromotionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListPromotionsPager: + r"""Lists the promotions in your Merchant Center account. The + response might contain fewer items than specified by + ``pageSize``. Rely on ``pageToken`` to determine if there are + more items to be requested. + + After inserting or updating a promotion, it may take several + minutes before the updated processed promotion can be retrieved. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_promotions_v1beta + + def sample_list_promotions(): + # Create a client + client = merchant_promotions_v1beta.PromotionsServiceClient() + + # Initialize request argument(s) + request = merchant_promotions_v1beta.ListPromotionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_promotions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.shopping.merchant_promotions_v1beta.types.ListPromotionsRequest, dict]): + The request object. Request message for the ``ListPromotions`` method. + parent (str): + Required. The account to list processed promotions 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_promotions_v1beta.services.promotions_service.pagers.ListPromotionsPager: + Response message for the ListPromotions 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, promotions.ListPromotionsRequest): + request = promotions.ListPromotionsRequest(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_promotions] + + # Certain 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.ListPromotionsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "PromotionsServiceClient": + 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__) + + +__all__ = ( + "PromotionsServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/pagers.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/pagers.py new file mode 100644 index 000000000000..5ca325dd375e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/pagers.py @@ -0,0 +1,166 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_promotions_v1beta.types import promotions + + +class ListPromotionsPager: + """A pager for iterating through ``list_promotions`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_promotions_v1beta.types.ListPromotionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``promotions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListPromotions`` requests and continue to iterate + through the ``promotions`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_promotions_v1beta.types.ListPromotionsResponse` + 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[..., promotions.ListPromotionsResponse], + request: promotions.ListPromotionsRequest, + response: promotions.ListPromotionsResponse, + *, + 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_promotions_v1beta.types.ListPromotionsRequest): + The initial request object. + response (google.shopping.merchant_promotions_v1beta.types.ListPromotionsResponse): + 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 = promotions.ListPromotionsRequest(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[promotions.ListPromotionsResponse]: + 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[promotions.Promotion]: + for page in self.pages: + yield from page.promotions + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListPromotionsAsyncPager: + """A pager for iterating through ``list_promotions`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_promotions_v1beta.types.ListPromotionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``promotions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListPromotions`` requests and continue to iterate + through the ``promotions`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_promotions_v1beta.types.ListPromotionsResponse` + 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[promotions.ListPromotionsResponse]], + request: promotions.ListPromotionsRequest, + response: promotions.ListPromotionsResponse, + *, + 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_promotions_v1beta.types.ListPromotionsRequest): + The initial request object. + response (google.shopping.merchant_promotions_v1beta.types.ListPromotionsResponse): + 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 = promotions.ListPromotionsRequest(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[promotions.ListPromotionsResponse]: + 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[promotions.Promotion]: + async def async_generator(): + async for page in self.pages: + for response in page.promotions: + 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-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/README.rst new file mode 100644 index 000000000000..8e430c8e2e3a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`PromotionsServiceTransport` is the ABC for all transports. +- public child `PromotionsServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `PromotionsServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BasePromotionsServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `PromotionsServiceRestTransport` 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-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/__init__.py new file mode 100644 index 000000000000..6f04436b2cd7 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 PromotionsServiceTransport +from .grpc import PromotionsServiceGrpcTransport +from .grpc_asyncio import PromotionsServiceGrpcAsyncIOTransport +from .rest import PromotionsServiceRestTransport +from .rest import PromotionsServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[PromotionsServiceTransport]] +_transport_registry['grpc'] = PromotionsServiceGrpcTransport +_transport_registry['grpc_asyncio'] = PromotionsServiceGrpcAsyncIOTransport +_transport_registry['rest'] = PromotionsServiceRestTransport + +__all__ = ( + 'PromotionsServiceTransport', + 'PromotionsServiceGrpcTransport', + 'PromotionsServiceGrpcAsyncIOTransport', + 'PromotionsServiceRestTransport', + 'PromotionsServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/base.py new file mode 100644 index 000000000000..7890c6625a55 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/base.py @@ -0,0 +1,182 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_promotions_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 + +from google.shopping.merchant_promotions_v1beta.types import promotions + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class PromotionsServiceTransport(abc.ABC): + """Abstract transport class for PromotionsService.""" + + 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.insert_promotion: gapic_v1.method.wrap_method( + self.insert_promotion, + default_timeout=None, + client_info=client_info, + ), + self.get_promotion: gapic_v1.method.wrap_method( + self.get_promotion, + default_timeout=None, + client_info=client_info, + ), + self.list_promotions: gapic_v1.method.wrap_method( + self.list_promotions, + 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 insert_promotion(self) -> Callable[ + [promotions.InsertPromotionRequest], + Union[ + promotions.Promotion, + Awaitable[promotions.Promotion] + ]]: + raise NotImplementedError() + + @property + def get_promotion(self) -> Callable[ + [promotions.GetPromotionRequest], + Union[ + promotions.Promotion, + Awaitable[promotions.Promotion] + ]]: + raise NotImplementedError() + + @property + def list_promotions(self) -> Callable[ + [promotions.ListPromotionsRequest], + Union[ + promotions.ListPromotionsResponse, + Awaitable[promotions.ListPromotionsResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'PromotionsServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/grpc.py new file mode 100644 index 000000000000..202e50e8a426 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/grpc.py @@ -0,0 +1,411 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_promotions_v1beta.types import promotions +from .base import PromotionsServiceTransport, 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.promotions.v1beta.PromotionsService", + "rpcName": 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.promotions.v1beta.PromotionsService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class PromotionsServiceGrpcTransport(PromotionsServiceTransport): + """gRPC backend transport for PromotionsService. + + Service to manage promotions for products. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'merchantapi.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'merchantapi.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'merchantapi.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def insert_promotion(self) -> Callable[ + [promotions.InsertPromotionRequest], + promotions.Promotion]: + r"""Return a callable for the insert promotion method over gRPC. + + Inserts a promotion for your Merchant Center account. + If the promotion already exists, then it updates the + promotion instead. + + Returns: + Callable[[~.InsertPromotionRequest], + ~.Promotion]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_promotion' not in self._stubs: + self._stubs['insert_promotion'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.promotions.v1beta.PromotionsService/InsertPromotion', + request_serializer=promotions.InsertPromotionRequest.serialize, + response_deserializer=promotions.Promotion.deserialize, + ) + return self._stubs['insert_promotion'] + + @property + def get_promotion(self) -> Callable[ + [promotions.GetPromotionRequest], + promotions.Promotion]: + r"""Return a callable for the get promotion method over gRPC. + + Retrieves the promotion from your Merchant Center + account. + After inserting or updating a promotion input, it may + take several minutes before the updated promotion can be + retrieved. + + Returns: + Callable[[~.GetPromotionRequest], + ~.Promotion]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_promotion' not in self._stubs: + self._stubs['get_promotion'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.promotions.v1beta.PromotionsService/GetPromotion', + request_serializer=promotions.GetPromotionRequest.serialize, + response_deserializer=promotions.Promotion.deserialize, + ) + return self._stubs['get_promotion'] + + @property + def list_promotions(self) -> Callable[ + [promotions.ListPromotionsRequest], + promotions.ListPromotionsResponse]: + r"""Return a callable for the list promotions method over gRPC. + + Lists the promotions in your Merchant Center account. The + response might contain fewer items than specified by + ``pageSize``. Rely on ``pageToken`` to determine if there are + more items to be requested. + + After inserting or updating a promotion, it may take several + minutes before the updated processed promotion can be retrieved. + + Returns: + Callable[[~.ListPromotionsRequest], + ~.ListPromotionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_promotions' not in self._stubs: + self._stubs['list_promotions'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.promotions.v1beta.PromotionsService/ListPromotions', + request_serializer=promotions.ListPromotionsRequest.serialize, + response_deserializer=promotions.ListPromotionsResponse.deserialize, + ) + return self._stubs['list_promotions'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'PromotionsServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..8d41e6f30075 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/grpc_asyncio.py @@ -0,0 +1,441 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_promotions_v1beta.types import promotions +from .base import PromotionsServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import PromotionsServiceGrpcTransport + +try: + from google.api_core import client_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.promotions.v1beta.PromotionsService", + "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.promotions.v1beta.PromotionsService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class PromotionsServiceGrpcAsyncIOTransport(PromotionsServiceTransport): + """gRPC AsyncIO backend transport for PromotionsService. + + Service to manage promotions for products. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'merchantapi.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'merchantapi.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'merchantapi.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def insert_promotion(self) -> Callable[ + [promotions.InsertPromotionRequest], + Awaitable[promotions.Promotion]]: + r"""Return a callable for the insert promotion method over gRPC. + + Inserts a promotion for your Merchant Center account. + If the promotion already exists, then it updates the + promotion instead. + + Returns: + Callable[[~.InsertPromotionRequest], + Awaitable[~.Promotion]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_promotion' not in self._stubs: + self._stubs['insert_promotion'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.promotions.v1beta.PromotionsService/InsertPromotion', + request_serializer=promotions.InsertPromotionRequest.serialize, + response_deserializer=promotions.Promotion.deserialize, + ) + return self._stubs['insert_promotion'] + + @property + def get_promotion(self) -> Callable[ + [promotions.GetPromotionRequest], + Awaitable[promotions.Promotion]]: + r"""Return a callable for the get promotion method over gRPC. + + Retrieves the promotion from your Merchant Center + account. + After inserting or updating a promotion input, it may + take several minutes before the updated promotion can be + retrieved. + + Returns: + Callable[[~.GetPromotionRequest], + Awaitable[~.Promotion]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_promotion' not in self._stubs: + self._stubs['get_promotion'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.promotions.v1beta.PromotionsService/GetPromotion', + request_serializer=promotions.GetPromotionRequest.serialize, + response_deserializer=promotions.Promotion.deserialize, + ) + return self._stubs['get_promotion'] + + @property + def list_promotions(self) -> Callable[ + [promotions.ListPromotionsRequest], + Awaitable[promotions.ListPromotionsResponse]]: + r"""Return a callable for the list promotions method over gRPC. + + Lists the promotions in your Merchant Center account. The + response might contain fewer items than specified by + ``pageSize``. Rely on ``pageToken`` to determine if there are + more items to be requested. + + After inserting or updating a promotion, it may take several + minutes before the updated processed promotion can be retrieved. + + Returns: + Callable[[~.ListPromotionsRequest], + Awaitable[~.ListPromotionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_promotions' not in self._stubs: + self._stubs['list_promotions'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.promotions.v1beta.PromotionsService/ListPromotions', + request_serializer=promotions.ListPromotionsRequest.serialize, + response_deserializer=promotions.ListPromotionsResponse.deserialize, + ) + return self._stubs['list_promotions'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.insert_promotion: self._wrap_method( + self.insert_promotion, + default_timeout=None, + client_info=client_info, + ), + self.get_promotion: self._wrap_method( + self.get_promotion, + default_timeout=None, + client_info=client_info, + ), + self.list_promotions: self._wrap_method( + self.list_promotions, + 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__ = ( + 'PromotionsServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/rest.py new file mode 100644 index 000000000000..fe0219eb6838 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/rest.py @@ -0,0 +1,657 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +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_promotions_v1beta.types import promotions + + +from .rest_base import _BasePromotionsServiceRestTransport +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}", +) + + +class PromotionsServiceRestInterceptor: + """Interceptor for PromotionsService. + + 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 PromotionsServiceRestTransport. + + .. code-block:: python + class MyCustomPromotionsServiceInterceptor(PromotionsServiceRestInterceptor): + def pre_get_promotion(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_promotion(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_insert_promotion(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_insert_promotion(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_promotions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_promotions(self, response): + logging.log(f"Received response: {response}") + return response + + transport = PromotionsServiceRestTransport(interceptor=MyCustomPromotionsServiceInterceptor()) + client = PromotionsServiceClient(transport=transport) + + + """ + def pre_get_promotion(self, request: promotions.GetPromotionRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[promotions.GetPromotionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_promotion + + Override in a subclass to manipulate the request or metadata + before they are sent to the PromotionsService server. + """ + return request, metadata + + def post_get_promotion(self, response: promotions.Promotion) -> promotions.Promotion: + """Post-rpc interceptor for get_promotion + + Override in a subclass to manipulate the response + after it is returned by the PromotionsService server but before + it is returned to user code. + """ + return response + + def pre_insert_promotion(self, request: promotions.InsertPromotionRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[promotions.InsertPromotionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for insert_promotion + + Override in a subclass to manipulate the request or metadata + before they are sent to the PromotionsService server. + """ + return request, metadata + + def post_insert_promotion(self, response: promotions.Promotion) -> promotions.Promotion: + """Post-rpc interceptor for insert_promotion + + Override in a subclass to manipulate the response + after it is returned by the PromotionsService server but before + it is returned to user code. + """ + return response + + def pre_list_promotions(self, request: promotions.ListPromotionsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[promotions.ListPromotionsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_promotions + + Override in a subclass to manipulate the request or metadata + before they are sent to the PromotionsService server. + """ + return request, metadata + + def post_list_promotions(self, response: promotions.ListPromotionsResponse) -> promotions.ListPromotionsResponse: + """Post-rpc interceptor for list_promotions + + Override in a subclass to manipulate the response + after it is returned by the PromotionsService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class PromotionsServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: PromotionsServiceRestInterceptor + + +class PromotionsServiceRestTransport(_BasePromotionsServiceRestTransport): + """REST backend synchronous transport for PromotionsService. + + Service to manage promotions for products. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__(self, *, + host: str = 'merchantapi.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[ + ], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + interceptor: Optional[PromotionsServiceRestInterceptor] = 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 PromotionsServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _GetPromotion(_BasePromotionsServiceRestTransport._BaseGetPromotion, PromotionsServiceRestStub): + def __hash__(self): + return hash("PromotionsServiceRestTransport.GetPromotion") + + @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: promotions.GetPromotionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> promotions.Promotion: + r"""Call the get promotion method over HTTP. + + Args: + request (~.promotions.GetPromotionRequest): + The request object. Request message for the ``GetPromotion`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.promotions.Promotion: + Represents a promotion. See the following articles for + more details. + + Required promotion input attributes to pass data + validation checks are primarily defined below: + + - `Promotions data + specification `__ + - `Local promotions data + specification `__ + + After inserting, updating a promotion input, it may take + several minutes before the final promotion can be + retrieved. + + """ + + http_options = _BasePromotionsServiceRestTransport._BaseGetPromotion._get_http_options() + + request, metadata = self._interceptor.pre_get_promotion(request, metadata) + transcoded_request = _BasePromotionsServiceRestTransport._BaseGetPromotion._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BasePromotionsServiceRestTransport._BaseGetPromotion._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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.promotions_v1beta.PromotionsServiceClient.GetPromotion", + extra = { + "serviceName": "google.shopping.merchant.promotions.v1beta.PromotionsService", + "rpcName": "GetPromotion", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PromotionsServiceRestTransport._GetPromotion._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 = promotions.Promotion() + pb_resp = promotions.Promotion.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_promotion(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = promotions.Promotion.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.promotions_v1beta.PromotionsServiceClient.get_promotion", + extra = { + "serviceName": "google.shopping.merchant.promotions.v1beta.PromotionsService", + "rpcName": "GetPromotion", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _InsertPromotion(_BasePromotionsServiceRestTransport._BaseInsertPromotion, PromotionsServiceRestStub): + def __hash__(self): + return hash("PromotionsServiceRestTransport.InsertPromotion") + + @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: promotions.InsertPromotionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> promotions.Promotion: + r"""Call the insert promotion method over HTTP. + + Args: + request (~.promotions.InsertPromotionRequest): + The request object. Request message for the ``InsertPromotion`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.promotions.Promotion: + Represents a promotion. See the following articles for + more details. + + Required promotion input attributes to pass data + validation checks are primarily defined below: + + - `Promotions data + specification `__ + - `Local promotions data + specification `__ + + After inserting, updating a promotion input, it may take + several minutes before the final promotion can be + retrieved. + + """ + + http_options = _BasePromotionsServiceRestTransport._BaseInsertPromotion._get_http_options() + + request, metadata = self._interceptor.pre_insert_promotion(request, metadata) + transcoded_request = _BasePromotionsServiceRestTransport._BaseInsertPromotion._get_transcoded_request(http_options, request) + + body = _BasePromotionsServiceRestTransport._BaseInsertPromotion._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BasePromotionsServiceRestTransport._BaseInsertPromotion._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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.promotions_v1beta.PromotionsServiceClient.InsertPromotion", + extra = { + "serviceName": "google.shopping.merchant.promotions.v1beta.PromotionsService", + "rpcName": "InsertPromotion", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PromotionsServiceRestTransport._InsertPromotion._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 = promotions.Promotion() + pb_resp = promotions.Promotion.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_insert_promotion(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = promotions.Promotion.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.promotions_v1beta.PromotionsServiceClient.insert_promotion", + extra = { + "serviceName": "google.shopping.merchant.promotions.v1beta.PromotionsService", + "rpcName": "InsertPromotion", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListPromotions(_BasePromotionsServiceRestTransport._BaseListPromotions, PromotionsServiceRestStub): + def __hash__(self): + return hash("PromotionsServiceRestTransport.ListPromotions") + + @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: promotions.ListPromotionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> promotions.ListPromotionsResponse: + r"""Call the list promotions method over HTTP. + + Args: + request (~.promotions.ListPromotionsRequest): + The request object. Request message for the ``ListPromotions`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.promotions.ListPromotionsResponse: + Response message for the ``ListPromotions`` method. + """ + + http_options = _BasePromotionsServiceRestTransport._BaseListPromotions._get_http_options() + + request, metadata = self._interceptor.pre_list_promotions(request, metadata) + transcoded_request = _BasePromotionsServiceRestTransport._BaseListPromotions._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BasePromotionsServiceRestTransport._BaseListPromotions._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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.promotions_v1beta.PromotionsServiceClient.ListPromotions", + extra = { + "serviceName": "google.shopping.merchant.promotions.v1beta.PromotionsService", + "rpcName": "ListPromotions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PromotionsServiceRestTransport._ListPromotions._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 = promotions.ListPromotionsResponse() + pb_resp = promotions.ListPromotionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_promotions(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = promotions.ListPromotionsResponse.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.promotions_v1beta.PromotionsServiceClient.list_promotions", + extra = { + "serviceName": "google.shopping.merchant.promotions.v1beta.PromotionsService", + "rpcName": "ListPromotions", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def get_promotion(self) -> Callable[ + [promotions.GetPromotionRequest], + promotions.Promotion]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetPromotion(self._session, self._host, self._interceptor) # type: ignore + + @property + def insert_promotion(self) -> Callable[ + [promotions.InsertPromotionRequest], + promotions.Promotion]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._InsertPromotion(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_promotions(self) -> Callable[ + [promotions.ListPromotionsRequest], + promotions.ListPromotionsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListPromotions(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'PromotionsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/rest_base.py new file mode 100644 index 000000000000..aab3dec4695e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/rest_base.py @@ -0,0 +1,212 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 PromotionsServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.shopping.merchant_promotions_v1beta.types import promotions + + +class _BasePromotionsServiceRestTransport(PromotionsServiceTransport): + """Base REST backend transport for PromotionsService. + + 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 _BaseGetPromotion: + 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': '/promotions/v1beta/{name=accounts/*/promotions/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = promotions.GetPromotionRequest.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(_BasePromotionsServiceRestTransport._BaseGetPromotion._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseInsertPromotion: + 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': '/promotions/v1beta/{parent=accounts/*}/promotions:insert', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = promotions.InsertPromotionRequest.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(_BasePromotionsServiceRestTransport._BaseInsertPromotion._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListPromotions: + 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': '/promotions/v1beta/{parent=accounts/*}/promotions', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = promotions.ListPromotionsRequest.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(_BasePromotionsServiceRestTransport._BaseListPromotions._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BasePromotionsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/types/__init__.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/types/__init__.py new file mode 100644 index 000000000000..aa349ec9d51f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/types/__init__.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .promotions import ( + GetPromotionRequest, + InsertPromotionRequest, + ListPromotionsRequest, + ListPromotionsResponse, + Promotion, +) +from .promotions_common import ( + Attributes, + PromotionStatus, + CouponValueType, + OfferType, + ProductApplicability, + RedemptionChannel, + StoreApplicability, +) + +__all__ = ( + 'GetPromotionRequest', + 'InsertPromotionRequest', + 'ListPromotionsRequest', + 'ListPromotionsResponse', + 'Promotion', + 'Attributes', + 'PromotionStatus', + 'CouponValueType', + 'OfferType', + 'ProductApplicability', + 'RedemptionChannel', + 'StoreApplicability', +) diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/types/promotions.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/types/promotions.py new file mode 100644 index 000000000000..d3d9283e4324 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/types/promotions.py @@ -0,0 +1,277 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_promotions_v1beta.types import promotions_common +from google.shopping.type.types import types + + +__protobuf__ = proto.module( + package='google.shopping.merchant.promotions.v1beta', + manifest={ + 'Promotion', + 'InsertPromotionRequest', + 'GetPromotionRequest', + 'ListPromotionsRequest', + 'ListPromotionsResponse', + }, +) + + +class Promotion(proto.Message): + r"""Represents a promotion. See the following articles for more details. + + Required promotion input attributes to pass data validation checks + are primarily defined below: + + - `Promotions data + specification `__ + - `Local promotions data + specification `__ + + After inserting, updating a promotion input, it may take several + minutes before the final promotion can be retrieved. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Identifier. The name of the promotion. Format: + ``accounts/{account}/promotions/{promotion}`` + promotion_id (str): + Required. The user provided promotion ID to uniquely + identify the promotion. Follow `minimum + requirements `__ + to prevent promotion disapprovals. + content_language (str): + Required. The two-letter `ISO + 639-1 `__ language + code for the promotion. + + Promotions is only for `selected + languages `__. + target_country (str): + Required. The target country used as part of the unique + identifier. Represented as a `CLDR territory + code `__. + + Promotions are only available in selected countries, `Free + Listings and Shopping + ads `__ + `Local Inventory + ads `__ + redemption_channel (MutableSequence[google.shopping.merchant_promotions_v1beta.types.RedemptionChannel]): + Required. `Redemption + channel `__ + for the promotion. At least one channel is required. + data_source (str): + Output only. The primary data source of the + promotion. + attributes (google.shopping.merchant_promotions_v1beta.types.Attributes): + Optional. A list of promotion attributes. + custom_attributes (MutableSequence[google.shopping.type.types.CustomAttribute]): + Optional. A list of custom (merchant-provided) attributes. + It can also be used for submitting any attribute of the data + specification in its generic form (for example, + ``{ "name": "size type", "value": "regular" }``). This is + useful for submitting attributes not explicitly exposed by + the API. + promotion_status (google.shopping.merchant_promotions_v1beta.types.PromotionStatus): + Output only. The `status of a + promotion `__, + data validation issues, that is, information about a + promotion computed asynchronously. + version_number (int): + Optional. Represents the existing version (freshness) of the + promotion, which can be used to preserve the right order + when multiple updates are done at the same time. + + If set, the insertion is prevented when version number is + lower than the current version number of the existing + promotion. Re-insertion (for example, promotion refresh + after 30 days) can be performed with the current + ``version_number``. + + If the operation is prevented, the aborted exception will be + thrown. + + This field is a member of `oneof`_ ``_version_number``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + promotion_id: str = proto.Field( + proto.STRING, + number=2, + ) + content_language: str = proto.Field( + proto.STRING, + number=3, + ) + target_country: str = proto.Field( + proto.STRING, + number=4, + ) + redemption_channel: MutableSequence[promotions_common.RedemptionChannel] = proto.RepeatedField( + proto.ENUM, + number=5, + enum=promotions_common.RedemptionChannel, + ) + data_source: str = proto.Field( + proto.STRING, + number=6, + ) + attributes: promotions_common.Attributes = proto.Field( + proto.MESSAGE, + number=7, + message=promotions_common.Attributes, + ) + custom_attributes: MutableSequence[types.CustomAttribute] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message=types.CustomAttribute, + ) + promotion_status: promotions_common.PromotionStatus = proto.Field( + proto.MESSAGE, + number=9, + message=promotions_common.PromotionStatus, + ) + version_number: int = proto.Field( + proto.INT64, + number=10, + optional=True, + ) + + +class InsertPromotionRequest(proto.Message): + r"""Request message for the ``InsertPromotion`` method. + + Attributes: + parent (str): + Required. The account where the promotion + will be inserted. Format: accounts/{account} + promotion (google.shopping.merchant_promotions_v1beta.types.Promotion): + Required. The promotion to insert. + data_source (str): + Required. The data source of the + `promotion `__ + Format: ``accounts/{account}/dataSources/{datasource}``. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + promotion: 'Promotion' = proto.Field( + proto.MESSAGE, + number=2, + message='Promotion', + ) + data_source: str = proto.Field( + proto.STRING, + number=3, + ) + + +class GetPromotionRequest(proto.Message): + r"""Request message for the ``GetPromotion`` method. + + Attributes: + name (str): + Required. The name of the promotion to retrieve. Format: + ``accounts/{account}/promotions/{promotions}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListPromotionsRequest(proto.Message): + r"""Request message for the ``ListPromotions`` method. + + Attributes: + parent (str): + Required. The account to list processed promotions for. + Format: ``accounts/{account}`` + page_size (int): + Output only. The maximum number of promotions + to return. The service may return fewer than + this value. The maximum value is 1000; values + above 1000 will be coerced to 1000. If + unspecified, the maximum number of promotions + will be returned. + page_token (str): + Output only. A page token, received from a previous + ``ListPromotions`` call. Provide this to retrieve the + subsequent page. + + When paginating, all other parameters provided to + ``ListPromotions`` 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 ListPromotionsResponse(proto.Message): + r"""Response message for the ``ListPromotions`` method. + + Attributes: + promotions (MutableSequence[google.shopping.merchant_promotions_v1beta.types.Promotion]): + The processed promotions 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 + + promotions: MutableSequence['Promotion'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Promotion', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/types/promotions_common.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/types/promotions_common.py new file mode 100644 index 000000000000..290e4bcf4ee5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/types/promotions_common.py @@ -0,0 +1,671 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 timestamp_pb2 # type: ignore +from google.shopping.type.types import types +from google.type import interval_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.shopping.merchant.promotions.v1beta', + manifest={ + 'ProductApplicability', + 'StoreApplicability', + 'OfferType', + 'RedemptionChannel', + 'CouponValueType', + 'Attributes', + 'PromotionStatus', + }, +) + + +class ProductApplicability(proto.Enum): + r"""Which product or list of products the promotion applies to. + + Values: + PRODUCT_APPLICABILITY_UNSPECIFIED (0): + Which products the promotion applies to is + unknown. + ALL_PRODUCTS (1): + Applicable to all products. + SPECIFIC_PRODUCTS (2): + Applicable to only a single product or list + of products. + """ + PRODUCT_APPLICABILITY_UNSPECIFIED = 0 + ALL_PRODUCTS = 1 + SPECIFIC_PRODUCTS = 2 + + +class StoreApplicability(proto.Enum): + r"""Store codes or list of store codes the promotion applies to. + Only for Local inventory ads promotions. + + Values: + STORE_APPLICABILITY_UNSPECIFIED (0): + Which store codes the promotion applies to is + unknown. + ALL_STORES (1): + Promotion applies to all stores. + SPECIFIC_STORES (2): + Promotion applies to only the specified + stores. + """ + STORE_APPLICABILITY_UNSPECIFIED = 0 + ALL_STORES = 1 + SPECIFIC_STORES = 2 + + +class OfferType(proto.Enum): + r"""Offer type of a promotion. + + Values: + OFFER_TYPE_UNSPECIFIED (0): + Unknown offer type. + NO_CODE (1): + Offer type without a code. + GENERIC_CODE (2): + Offer type with a code. Generic redemption code for the + promotion is required when ``offerType`` = ``GENERIC_CODE``. + """ + OFFER_TYPE_UNSPECIFIED = 0 + NO_CODE = 1 + GENERIC_CODE = 2 + + +class RedemptionChannel(proto.Enum): + r"""Channel of a promotion. + + Values: + REDEMPTION_CHANNEL_UNSPECIFIED (0): + Indicates that the channel is unspecified. + IN_STORE (1): + Indicates that the channel is in store. This is same as + ``local`` channel used for ``products``. + ONLINE (2): + Indicates that the channel is online. + """ + REDEMPTION_CHANNEL_UNSPECIFIED = 0 + IN_STORE = 1 + ONLINE = 2 + + +class CouponValueType(proto.Enum): + r"""`Coupon value + type `__ + of a promotion. + + Values: + COUPON_VALUE_TYPE_UNSPECIFIED (0): + Indicates that the coupon value type is + unspecified. + MONEY_OFF (1): + Money off coupon value type. + PERCENT_OFF (2): + Percent off coupon value type. + BUY_M_GET_N_MONEY_OFF (3): + Buy M quantity, get N money off coupon value type. + ``minimum_purchase_quantity`` and + ``get_this_quantity_discounted`` must be present. + ``money_off_amount`` must also be present. + BUY_M_GET_N_PERCENT_OFF (4): + Buy M quantity, get N percent off coupon value type. + ``minimum_purchase_quantity`` and + ``get_this_quantity_discounted`` must be present. + ``percent_off_percentage`` must also be present. + BUY_M_GET_MONEY_OFF (5): + Buy M quantity, get money off. ``minimum_purchase_quantity`` + and ``money_off_amount`` must be present. + BUY_M_GET_PERCENT_OFF (6): + Buy M quantity, get money off. ``minimum_purchase_quantity`` + and ``percent_off_percentage`` must be present. + FREE_GIFT (7): + Free gift with description only. + FREE_GIFT_WITH_VALUE (8): + Free gift with monetary value. + FREE_GIFT_WITH_ITEM_ID (9): + Free gift with item ID. + FREE_SHIPPING_STANDARD (10): + Standard free shipping coupon value type. + FREE_SHIPPING_OVERNIGHT (11): + Overnight free shipping coupon value type. + FREE_SHIPPING_TWO_DAY (12): + Two day free shipping coupon value type. + """ + COUPON_VALUE_TYPE_UNSPECIFIED = 0 + MONEY_OFF = 1 + PERCENT_OFF = 2 + BUY_M_GET_N_MONEY_OFF = 3 + BUY_M_GET_N_PERCENT_OFF = 4 + BUY_M_GET_MONEY_OFF = 5 + BUY_M_GET_PERCENT_OFF = 6 + FREE_GIFT = 7 + FREE_GIFT_WITH_VALUE = 8 + FREE_GIFT_WITH_ITEM_ID = 9 + FREE_SHIPPING_STANDARD = 10 + FREE_SHIPPING_OVERNIGHT = 11 + FREE_SHIPPING_TWO_DAY = 12 + + +class Attributes(proto.Message): + r"""Attributes. + + Attributes: + product_applicability (google.shopping.merchant_promotions_v1beta.types.ProductApplicability): + Required. Applicability of the promotion to either all + products or `only specific + products `__. + offer_type (google.shopping.merchant_promotions_v1beta.types.OfferType): + Required. + `Type `__ + of the promotion. Use this attribute to indicate whether or + not customers need a coupon code to redeem your promotion. + generic_redemption_code (str): + Optional. Generic redemption code for the promotion. To be + used with the ``offerType`` field and must meet the `minimum + requirements `__. + long_title (str): + Required. `Long + title `__ + for the promotion. + coupon_value_type (google.shopping.merchant_promotions_v1beta.types.CouponValueType): + Required. The [coupon value type] + (https://support.google.com/merchants/answer/13861986?ref_topic=13773355&sjid=17642868584668136159-NC) + attribute to signal the type of promotion that you are + running. Depending on type of the selected coupon value + `some attributes are + required `__. + promotion_destinations (MutableSequence[google.shopping.type.types.Destination.DestinationEnum]): + Required. The list of destinations where the promotion + applies to. If you don't specify a destination by including + a supported value in your data source, your promotion will + display in Shopping ads and free listings by default. + + You may have previously submitted the following values as + destinations for your products: Shopping Actions, Surfaces + across Google, Local surfaces across Google. To represent + these values use ``FREE_LISTINGS``, ``FREE_LOCAL_LISTINGS``, + ``LOCAL_INVENTORY_ADS``. For more details see `Promotion + destination `__ + item_id_inclusion (MutableSequence[str]): + Optional. Product filter by `item + ID `__ + for the promotion. The product filter attributes only + applies when the products eligible for promotion product + applicability ``product_applicability`` attribute is set to + `specific_products `__. + brand_inclusion (MutableSequence[str]): + Optional. Product filter by brand for the promotion. The + product filter attributes only applies when the products + eligible for promotion product applicability + ``product_applicability`` attribute is set to + `specific_products `__. + item_group_id_inclusion (MutableSequence[str]): + Optional. Product filter by item group ID for the promotion. + The product filter attributes only applies when the products + eligible for promotion product applicability + [product_applicability] attribute is set to + `specific_products `__. + product_type_inclusion (MutableSequence[str]): + Optional. Product filter by product type for the promotion. + The product filter attributes only applies when the products + eligible for promotion product applicability + ``product_applicability`` attribute is set to + `specific_products `__. + item_id_exclusion (MutableSequence[str]): + Optional. Product filter by `item ID + exclusion `__ + for the promotion. The product filter attributes only + applies when the products eligible for promotion product + applicability ``product_applicability`` attribute is set to + `specific_products `__. + brand_exclusion (MutableSequence[str]): + Optional. Product filter by `brand + exclusion `__ + for the promotion. The product filter attributes only + applies when the products eligible for promotion product + applicability ``product_applicability`` attribute is set to + `specific_products `__. + item_group_id_exclusion (MutableSequence[str]): + Optional. Product filter by `item group + ID `__. + The product filter attributes only applies when the products + eligible for promotion product applicability + ``product_applicability`` attribute is set to + `specific_products `__. + exclusion for the promotion. + product_type_exclusion (MutableSequence[str]): + Optional. Product filter by `product type + exclusion `__ + for the promotion. The product filter attributes only + applies when the products eligible for promotion product + applicability ``product_applicability`` attribute is set to + `specific_products `__. + minimum_purchase_amount (google.shopping.type.types.Price): + Optional. `Minimum purchase + amount `__ + for the promotion. + minimum_purchase_quantity (int): + Optional. `Minimum purchase + quantity `__ + for the promotion. + limit_quantity (int): + Optional. `Maximum purchase + quantity `__ + for the promotion. + limit_value (google.shopping.type.types.Price): + Optional. `Maximum product + price `__ + for promotion. + percent_off (int): + Optional. The `percentage + discount `__ + offered in the promotion. + money_off_amount (google.shopping.type.types.Price): + Optional. The `money off + amount `__ + offered in the promotion. + get_this_quantity_discounted (int): + Optional. The number of items discounted in the promotion. + The attribute is set when ``couponValueType`` is equal to + ``buy_m_get_n_money_off`` or ``buy_m_get_n_percent_off``. + free_gift_value (google.shopping.type.types.Price): + Optional. `Free gift + value `__ + for the promotion. + free_gift_description (str): + Optional. `Free gift + description `__ + for the promotion. + free_gift_item_id (str): + Optional. `Free gift item + ID `__ + for the promotion. + promotion_effective_time_period (google.type.interval_pb2.Interval): + Required. ``TimePeriod`` representation of the promotion's + effective dates. This attribute specifies that the promotion + can be tested on your online store during this time period. + promotion_display_time_period (google.type.interval_pb2.Interval): + Optional. ``TimePeriod`` representation of the promotion's + display dates. This attribute specifies the date and time + frame when the promotion will be live on Google.com and + Shopping ads. If the display time period for promotion + ``promotion_display_time_period`` attribute is not + specified, the promotion effective time period + ``promotion_effective_time_period`` determines the date and + time frame when the promotion will be live on Google.com and + Shopping ads. + store_applicability (google.shopping.merchant_promotions_v1beta.types.StoreApplicability): + Optional. Whether the promotion applies to `all stores, or + only specified + stores `__. + Local Inventory ads promotions throw an error if no store + applicability is included. An ``INVALID_ARGUMENT`` error is + thrown if ``store_applicability`` is set to ``ALL_STORES`` + and ``store_codes_inclusion`` or ``score_code_exclusion`` is + set to a value. + store_codes_inclusion (MutableSequence[str]): + Optional. `Store codes to + include `__ + for the promotion. The store filter attributes only applies + when the ``store_applicability`` attribute is set to + `specific_stores `__. + + Store code (the store ID from your Business Profile) of the + physical store the product is sold in. See the `Local + product inventory data + specification `__ + for more information. + store_codes_exclusion (MutableSequence[str]): + Optional. `Store codes to + exclude `__ + for the promotion. The store filter attributes only applies + when the ``store_applicability`` attribute is set to + `specific_stores `__. + promotion_url (str): + Optional. URL to the page on the merchant's site where the + promotion shows. Local Inventory ads promotions throw an + error if no ``promotion_url`` is included. URL is used to + confirm that the promotion is valid and can be redeemed. + """ + + product_applicability: 'ProductApplicability' = proto.Field( + proto.ENUM, + number=1, + enum='ProductApplicability', + ) + offer_type: 'OfferType' = proto.Field( + proto.ENUM, + number=2, + enum='OfferType', + ) + generic_redemption_code: str = proto.Field( + proto.STRING, + number=3, + ) + long_title: str = proto.Field( + proto.STRING, + number=4, + ) + coupon_value_type: 'CouponValueType' = proto.Field( + proto.ENUM, + number=5, + enum='CouponValueType', + ) + promotion_destinations: MutableSequence[types.Destination.DestinationEnum] = proto.RepeatedField( + proto.ENUM, + number=6, + enum=types.Destination.DestinationEnum, + ) + item_id_inclusion: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + brand_inclusion: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=8, + ) + item_group_id_inclusion: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=9, + ) + product_type_inclusion: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=10, + ) + item_id_exclusion: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=11, + ) + brand_exclusion: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=12, + ) + item_group_id_exclusion: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=13, + ) + product_type_exclusion: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=14, + ) + minimum_purchase_amount: types.Price = proto.Field( + proto.MESSAGE, + number=15, + message=types.Price, + ) + minimum_purchase_quantity: int = proto.Field( + proto.INT64, + number=16, + ) + limit_quantity: int = proto.Field( + proto.INT64, + number=17, + ) + limit_value: types.Price = proto.Field( + proto.MESSAGE, + number=18, + message=types.Price, + ) + percent_off: int = proto.Field( + proto.INT64, + number=19, + ) + money_off_amount: types.Price = proto.Field( + proto.MESSAGE, + number=20, + message=types.Price, + ) + get_this_quantity_discounted: int = proto.Field( + proto.INT64, + number=21, + ) + free_gift_value: types.Price = proto.Field( + proto.MESSAGE, + number=22, + message=types.Price, + ) + free_gift_description: str = proto.Field( + proto.STRING, + number=23, + ) + free_gift_item_id: str = proto.Field( + proto.STRING, + number=24, + ) + promotion_effective_time_period: interval_pb2.Interval = proto.Field( + proto.MESSAGE, + number=25, + message=interval_pb2.Interval, + ) + promotion_display_time_period: interval_pb2.Interval = proto.Field( + proto.MESSAGE, + number=26, + message=interval_pb2.Interval, + ) + store_applicability: 'StoreApplicability' = proto.Field( + proto.ENUM, + number=28, + enum='StoreApplicability', + ) + store_codes_inclusion: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=29, + ) + store_codes_exclusion: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=30, + ) + promotion_url: str = proto.Field( + proto.STRING, + number=31, + ) + + +class PromotionStatus(proto.Message): + r"""The status of the promotion. + + Attributes: + destination_statuses (MutableSequence[google.shopping.merchant_promotions_v1beta.types.PromotionStatus.DestinationStatus]): + Output only. The intended destinations for + the promotion. + item_level_issues (MutableSequence[google.shopping.merchant_promotions_v1beta.types.PromotionStatus.ItemLevelIssue]): + Output only. A list of issues associated with + the promotion. + creation_date (google.protobuf.timestamp_pb2.Timestamp): + Output only. Date on which the promotion has been created in + `ISO 8601 `__ format: + Date, time, and offset, for example + ``2020-01-02T09:00:00+01:00`` or ``2020-01-02T09:00:00Z`` + last_update_date (google.protobuf.timestamp_pb2.Timestamp): + Output only. Date on which the promotion status has been + last updated in `ISO + 8601 `__ format: + Date, time, and offset, for example + ``2020-01-02T09:00:00+01:00`` or ``2020-01-02T09:00:00Z`` + """ + + class DestinationStatus(proto.Message): + r"""The status for the specified destination. + + Attributes: + reporting_context (google.shopping.type.types.ReportingContext.ReportingContextEnum): + Output only. The name of the promotion + destination. + status (google.shopping.merchant_promotions_v1beta.types.PromotionStatus.DestinationStatus.State): + Output only. The status for the specified + destination. + """ + class State(proto.Enum): + r"""The current state of the promotion. + + Values: + STATE_UNSPECIFIED (0): + Unknown promotion state. + IN_REVIEW (1): + The promotion is under review. + REJECTED (2): + The promotion is disapproved. + LIVE (3): + The promotion is approved and active. + STOPPED (4): + The promotion is stopped by merchant. + EXPIRED (5): + The promotion is no longer active. + PENDING (6): + The promotion is not stopped, and all reviews + are approved, but the active date is in the + future. + """ + STATE_UNSPECIFIED = 0 + IN_REVIEW = 1 + REJECTED = 2 + LIVE = 3 + STOPPED = 4 + EXPIRED = 5 + PENDING = 6 + + reporting_context: types.ReportingContext.ReportingContextEnum = proto.Field( + proto.ENUM, + number=1, + enum=types.ReportingContext.ReportingContextEnum, + ) + status: 'PromotionStatus.DestinationStatus.State' = proto.Field( + proto.ENUM, + number=2, + enum='PromotionStatus.DestinationStatus.State', + ) + + class ItemLevelIssue(proto.Message): + r"""The issue associated with the promotion. + + Attributes: + code (str): + Output only. The error code of the issue. + severity (google.shopping.merchant_promotions_v1beta.types.PromotionStatus.ItemLevelIssue.Severity): + Output only. How this issue affects serving + of the promotion. + resolution (str): + Output only. Whether the issue can be + resolved by the merchant. + attribute (str): + Output only. The attribute's name, if the + issue is caused by a single attribute. + reporting_context (google.shopping.type.types.ReportingContext.ReportingContextEnum): + Output only. The destination the issue + applies to. + description (str): + Output only. A short issue description in + English. + detail (str): + Output only. A detailed issue description in + English. + documentation (str): + Output only. The URL of a web page to help + with resolving this issue. + applicable_countries (MutableSequence[str]): + Output only. List of country codes (ISO + 3166-1 alpha-2) where issue applies to the + offer. + """ + class Severity(proto.Enum): + r"""The severity of the issue. + + Values: + SEVERITY_UNSPECIFIED (0): + Not specified. + NOT_IMPACTED (1): + This issue represents a warning and does not + have a direct affect on the promotion. + DEMOTED (2): + The promotion is demoted and most likely have + limited performance in search results + DISAPPROVED (3): + Issue disapproves the promotion. + """ + SEVERITY_UNSPECIFIED = 0 + NOT_IMPACTED = 1 + DEMOTED = 2 + DISAPPROVED = 3 + + code: str = proto.Field( + proto.STRING, + number=1, + ) + severity: 'PromotionStatus.ItemLevelIssue.Severity' = proto.Field( + proto.ENUM, + number=2, + enum='PromotionStatus.ItemLevelIssue.Severity', + ) + resolution: str = proto.Field( + proto.STRING, + number=3, + ) + attribute: str = proto.Field( + proto.STRING, + number=4, + ) + reporting_context: types.ReportingContext.ReportingContextEnum = proto.Field( + proto.ENUM, + number=5, + enum=types.ReportingContext.ReportingContextEnum, + ) + description: str = proto.Field( + proto.STRING, + number=6, + ) + detail: str = proto.Field( + proto.STRING, + number=7, + ) + documentation: str = proto.Field( + proto.STRING, + number=8, + ) + applicable_countries: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=9, + ) + + destination_statuses: MutableSequence[DestinationStatus] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=DestinationStatus, + ) + item_level_issues: MutableSequence[ItemLevelIssue] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=ItemLevelIssue, + ) + creation_date: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + last_update_date: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/mypy.ini b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/noxfile.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/noxfile.py new file mode 100644 index 000000000000..3cd901f36b88 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/noxfile.py @@ -0,0 +1,280 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = 'google-shopping-merchant-promotions' + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.13" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "prerelease_deps", +] + +@nox.session(python=ALL_PYTHON) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def unit(session, protobuf_implementation): + """Run the unit test suite.""" + + 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+") + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") + + # 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") + + session.run( + 'py.test', + '--quiet', + '--cov=google/shopping/merchant_promotions_v1beta/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)), + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + +@nox.session(python=ALL_PYTHON[-1]) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def prerelease_deps(session, protobuf_implementation): + """Run the unit test suite against pre-release versions of dependencies.""" + + 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 test environment dependencies + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + + # Install the package without dependencies + session.install('-e', '.', '--no-deps') + + # We test the minimum dependency versions using the minimum Python + # version so the lowest python runtime that we test has a corresponding constraints + # file, located at `testing/constraints--.txt`, which contains all of the + # 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 + ) + ] + + session.install(*constraints_deps) + + prerel_deps = [ + "googleapis-common-protos", + "google-api-core", + "google-auth", + # Exclude grpcio!=1.67.0rc1 which does not support python 3.13 + "grpcio!=1.67.0rc1", + "grpcio-status", + "protobuf", + "proto-plus", + ] + + for dep in prerel_deps: + session.install("--pre", "--no-deps", "--upgrade", dep) + + # Remaining dependencies + other_deps = [ + "requests", + ] + session.install(*other_deps) + + # Print out prerelease package versions + + session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") + session.run("python", "-c", "import google.auth; print(google.auth.__version__)") + session.run("python", "-c", "import grpc; print(grpc.__version__)") + session.run( + "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" + ) + session.run( + "python", "-c", "import proto; print(proto.__version__)" + ) + + session.run( + 'py.test', + '--quiet', + '--cov=google/shopping/merchant_promotions_v1beta/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)), + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + + +@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=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 docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==7.0.1", "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=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", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_get_promotion_async.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_get_promotion_async.py new file mode 100644 index 000000000000..66bd0db4ca0d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_get_promotion_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetPromotion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-promotions + + +# [START merchantapi_v1beta_generated_PromotionsService_GetPromotion_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_promotions_v1beta + + +async def sample_get_promotion(): + # Create a client + client = merchant_promotions_v1beta.PromotionsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_promotions_v1beta.GetPromotionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_promotion(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_PromotionsService_GetPromotion_async] diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_get_promotion_sync.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_get_promotion_sync.py new file mode 100644 index 000000000000..6b8e9dade3e9 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_get_promotion_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetPromotion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-promotions + + +# [START merchantapi_v1beta_generated_PromotionsService_GetPromotion_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_promotions_v1beta + + +def sample_get_promotion(): + # Create a client + client = merchant_promotions_v1beta.PromotionsServiceClient() + + # Initialize request argument(s) + request = merchant_promotions_v1beta.GetPromotionRequest( + name="name_value", + ) + + # Make the request + response = client.get_promotion(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_PromotionsService_GetPromotion_sync] diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_insert_promotion_async.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_insert_promotion_async.py new file mode 100644 index 000000000000..d9245ecabde7 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_insert_promotion_async.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for InsertPromotion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-promotions + + +# [START merchantapi_v1beta_generated_PromotionsService_InsertPromotion_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_promotions_v1beta + + +async def sample_insert_promotion(): + # Create a client + client = merchant_promotions_v1beta.PromotionsServiceAsyncClient() + + # Initialize request argument(s) + promotion = merchant_promotions_v1beta.Promotion() + promotion.promotion_id = "promotion_id_value" + promotion.content_language = "content_language_value" + promotion.target_country = "target_country_value" + promotion.redemption_channel = ['ONLINE'] + + request = merchant_promotions_v1beta.InsertPromotionRequest( + parent="parent_value", + promotion=promotion, + data_source="data_source_value", + ) + + # Make the request + response = await client.insert_promotion(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_PromotionsService_InsertPromotion_async] diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_insert_promotion_sync.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_insert_promotion_sync.py new file mode 100644 index 000000000000..2fd44913b58c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_insert_promotion_sync.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for InsertPromotion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-promotions + + +# [START merchantapi_v1beta_generated_PromotionsService_InsertPromotion_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_promotions_v1beta + + +def sample_insert_promotion(): + # Create a client + client = merchant_promotions_v1beta.PromotionsServiceClient() + + # Initialize request argument(s) + promotion = merchant_promotions_v1beta.Promotion() + promotion.promotion_id = "promotion_id_value" + promotion.content_language = "content_language_value" + promotion.target_country = "target_country_value" + promotion.redemption_channel = ['ONLINE'] + + request = merchant_promotions_v1beta.InsertPromotionRequest( + parent="parent_value", + promotion=promotion, + data_source="data_source_value", + ) + + # Make the request + response = client.insert_promotion(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_PromotionsService_InsertPromotion_sync] diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_list_promotions_async.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_list_promotions_async.py new file mode 100644 index 000000000000..ae88a1355d74 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_list_promotions_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListPromotions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-promotions + + +# [START merchantapi_v1beta_generated_PromotionsService_ListPromotions_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_promotions_v1beta + + +async def sample_list_promotions(): + # Create a client + client = merchant_promotions_v1beta.PromotionsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_promotions_v1beta.ListPromotionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_promotions(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_PromotionsService_ListPromotions_async] diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_list_promotions_sync.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_list_promotions_sync.py new file mode 100644 index 000000000000..d2d3f2a247df --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_list_promotions_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListPromotions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-promotions + + +# [START merchantapi_v1beta_generated_PromotionsService_ListPromotions_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_promotions_v1beta + + +def sample_list_promotions(): + # Create a client + client = merchant_promotions_v1beta.PromotionsServiceClient() + + # Initialize request argument(s) + request = merchant_promotions_v1beta.ListPromotionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_promotions(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_PromotionsService_ListPromotions_sync] diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.promotions.v1beta.json b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.promotions.v1beta.json new file mode 100644 index 000000000000..35c4091b4ca2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.promotions.v1beta.json @@ -0,0 +1,490 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.shopping.merchant.promotions.v1beta", + "version": "v1beta" + } + ], + "language": "PYTHON", + "name": "google-shopping-merchant-promotions", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_promotions_v1beta.PromotionsServiceAsyncClient", + "shortName": "PromotionsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_promotions_v1beta.PromotionsServiceAsyncClient.get_promotion", + "method": { + "fullName": "google.shopping.merchant.promotions.v1beta.PromotionsService.GetPromotion", + "service": { + "fullName": "google.shopping.merchant.promotions.v1beta.PromotionsService", + "shortName": "PromotionsService" + }, + "shortName": "GetPromotion" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_promotions_v1beta.types.GetPromotionRequest" + }, + { + "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_promotions_v1beta.types.Promotion", + "shortName": "get_promotion" + }, + "description": "Sample for GetPromotion", + "file": "merchantapi_v1beta_generated_promotions_service_get_promotion_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_PromotionsService_GetPromotion_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_promotions_service_get_promotion_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_promotions_v1beta.PromotionsServiceClient", + "shortName": "PromotionsServiceClient" + }, + "fullName": "google.shopping.merchant_promotions_v1beta.PromotionsServiceClient.get_promotion", + "method": { + "fullName": "google.shopping.merchant.promotions.v1beta.PromotionsService.GetPromotion", + "service": { + "fullName": "google.shopping.merchant.promotions.v1beta.PromotionsService", + "shortName": "PromotionsService" + }, + "shortName": "GetPromotion" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_promotions_v1beta.types.GetPromotionRequest" + }, + { + "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_promotions_v1beta.types.Promotion", + "shortName": "get_promotion" + }, + "description": "Sample for GetPromotion", + "file": "merchantapi_v1beta_generated_promotions_service_get_promotion_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_PromotionsService_GetPromotion_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_promotions_service_get_promotion_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_promotions_v1beta.PromotionsServiceAsyncClient", + "shortName": "PromotionsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_promotions_v1beta.PromotionsServiceAsyncClient.insert_promotion", + "method": { + "fullName": "google.shopping.merchant.promotions.v1beta.PromotionsService.InsertPromotion", + "service": { + "fullName": "google.shopping.merchant.promotions.v1beta.PromotionsService", + "shortName": "PromotionsService" + }, + "shortName": "InsertPromotion" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_promotions_v1beta.types.InsertPromotionRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.shopping.merchant_promotions_v1beta.types.Promotion", + "shortName": "insert_promotion" + }, + "description": "Sample for InsertPromotion", + "file": "merchantapi_v1beta_generated_promotions_service_insert_promotion_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_PromotionsService_InsertPromotion_async", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 53, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 54, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_promotions_service_insert_promotion_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_promotions_v1beta.PromotionsServiceClient", + "shortName": "PromotionsServiceClient" + }, + "fullName": "google.shopping.merchant_promotions_v1beta.PromotionsServiceClient.insert_promotion", + "method": { + "fullName": "google.shopping.merchant.promotions.v1beta.PromotionsService.InsertPromotion", + "service": { + "fullName": "google.shopping.merchant.promotions.v1beta.PromotionsService", + "shortName": "PromotionsService" + }, + "shortName": "InsertPromotion" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_promotions_v1beta.types.InsertPromotionRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.shopping.merchant_promotions_v1beta.types.Promotion", + "shortName": "insert_promotion" + }, + "description": "Sample for InsertPromotion", + "file": "merchantapi_v1beta_generated_promotions_service_insert_promotion_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_PromotionsService_InsertPromotion_sync", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 53, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 54, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_promotions_service_insert_promotion_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_promotions_v1beta.PromotionsServiceAsyncClient", + "shortName": "PromotionsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_promotions_v1beta.PromotionsServiceAsyncClient.list_promotions", + "method": { + "fullName": "google.shopping.merchant.promotions.v1beta.PromotionsService.ListPromotions", + "service": { + "fullName": "google.shopping.merchant.promotions.v1beta.PromotionsService", + "shortName": "PromotionsService" + }, + "shortName": "ListPromotions" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_promotions_v1beta.types.ListPromotionsRequest" + }, + { + "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_promotions_v1beta.services.promotions_service.pagers.ListPromotionsAsyncPager", + "shortName": "list_promotions" + }, + "description": "Sample for ListPromotions", + "file": "merchantapi_v1beta_generated_promotions_service_list_promotions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_PromotionsService_ListPromotions_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_promotions_service_list_promotions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_promotions_v1beta.PromotionsServiceClient", + "shortName": "PromotionsServiceClient" + }, + "fullName": "google.shopping.merchant_promotions_v1beta.PromotionsServiceClient.list_promotions", + "method": { + "fullName": "google.shopping.merchant.promotions.v1beta.PromotionsService.ListPromotions", + "service": { + "fullName": "google.shopping.merchant.promotions.v1beta.PromotionsService", + "shortName": "PromotionsService" + }, + "shortName": "ListPromotions" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_promotions_v1beta.types.ListPromotionsRequest" + }, + { + "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_promotions_v1beta.services.promotions_service.pagers.ListPromotionsPager", + "shortName": "list_promotions" + }, + "description": "Sample for ListPromotions", + "file": "merchantapi_v1beta_generated_promotions_service_list_promotions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_PromotionsService_ListPromotions_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_promotions_service_list_promotions_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/scripts/fixup_merchant_promotions_v1beta_keywords.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/scripts/fixup_merchant_promotions_v1beta_keywords.py new file mode 100644 index 000000000000..398615e0afb5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/scripts/fixup_merchant_promotions_v1beta_keywords.py @@ -0,0 +1,178 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_promotionsCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'get_promotion': ('name', ), + 'insert_promotion': ('parent', 'promotion', 'data_source', ), + 'list_promotions': ('parent', 'page_size', 'page_token', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=merchant_promotionsCallTransformer(), +): + """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_promotions 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-promotions/v1beta/setup.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/setup.py new file mode 100644 index 000000000000..a4ef40e7ce4a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/setup.py @@ -0,0 +1,99 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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-promotions' + + +description = "Google Shopping Merchant Promotions API client library" + +version = None + +with open(os.path.join(package_root, 'google/shopping/merchant_promotions/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.0dev,!=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.0dev,!=2.24.0,!=2.25.0", + "proto-plus >= 1.22.3, <2.0.0dev", + "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'", + "protobuf>=3.20.2,<6.0.0dev,!=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.0dev", +] +extras = { +} +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-promotions" + +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-promotions/v1beta/testing/constraints-3.10.txt b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/testing/constraints-3.10.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/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-promotions/v1beta/testing/constraints-3.11.txt b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/testing/constraints-3.11.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/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-promotions/v1beta/testing/constraints-3.12.txt b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/testing/constraints-3.12.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/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-promotions/v1beta/testing/constraints-3.13.txt b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/testing/constraints-3.13.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/testing/constraints-3.13.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-promotions/v1beta/testing/constraints-3.7.txt b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/testing/constraints-3.7.txt new file mode 100644 index 000000000000..130a0c0f80ab --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/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.0dev", +# 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-promotions/v1beta/testing/constraints-3.8.txt b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/testing/constraints-3.8.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/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-promotions/v1beta/testing/constraints-3.9.txt b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/testing/constraints-3.9.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/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-promotions/v1beta/tests/__init__.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-promotions/v1beta/tests/unit/__init__.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-promotions/v1beta/tests/unit/gapic/__init__.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-promotions/v1beta/tests/unit/gapic/merchant_promotions_v1beta/__init__.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/tests/unit/gapic/merchant_promotions_v1beta/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/tests/unit/gapic/merchant_promotions_v1beta/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-promotions/v1beta/tests/unit/gapic/merchant_promotions_v1beta/test_promotions_service.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/tests/unit/gapic/merchant_promotions_v1beta/test_promotions_service.py new file mode 100644 index 000000000000..c6dbc6da0ec9 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/tests/unit/gapic/merchant_promotions_v1beta/test_promotions_service.py @@ -0,0 +1,3614 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable, AsyncIterable +from google.protobuf import json_format +import json +import math +import pytest +from google.api_core import api_core_version +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +try: + from google.auth.aio import credentials as ga_credentials_async + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account +from google.protobuf import timestamp_pb2 # type: ignore +from google.shopping.merchant_promotions_v1beta.services.promotions_service import PromotionsServiceAsyncClient +from google.shopping.merchant_promotions_v1beta.services.promotions_service import PromotionsServiceClient +from google.shopping.merchant_promotions_v1beta.services.promotions_service import pagers +from google.shopping.merchant_promotions_v1beta.services.promotions_service import transports +from google.shopping.merchant_promotions_v1beta.types import promotions +from google.shopping.merchant_promotions_v1beta.types import promotions_common +from google.shopping.type.types import types +from google.type import interval_pb2 # type: ignore +import google.auth + + +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 PromotionsServiceClient._get_default_mtls_endpoint(None) is None + assert PromotionsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert PromotionsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert PromotionsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert PromotionsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert PromotionsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert PromotionsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert PromotionsServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert PromotionsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + PromotionsServiceClient._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 PromotionsServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert PromotionsServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert PromotionsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + PromotionsServiceClient._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 PromotionsServiceClient._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 PromotionsServiceClient._get_client_cert_source(None, False) is None + assert PromotionsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert PromotionsServiceClient._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 PromotionsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert PromotionsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(PromotionsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PromotionsServiceClient)) +@mock.patch.object(PromotionsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PromotionsServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = PromotionsServiceClient._DEFAULT_UNIVERSE + default_endpoint = PromotionsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = PromotionsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert PromotionsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert PromotionsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == PromotionsServiceClient.DEFAULT_MTLS_ENDPOINT + assert PromotionsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert PromotionsServiceClient._get_api_endpoint(None, None, default_universe, "always") == PromotionsServiceClient.DEFAULT_MTLS_ENDPOINT + assert PromotionsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == PromotionsServiceClient.DEFAULT_MTLS_ENDPOINT + assert PromotionsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert PromotionsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + PromotionsServiceClient._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 PromotionsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert PromotionsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert PromotionsServiceClient._get_universe_domain(None, None) == PromotionsServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + PromotionsServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize("client_class,transport_name", [ + (PromotionsServiceClient, "grpc"), + (PromotionsServiceAsyncClient, "grpc_asyncio"), + (PromotionsServiceClient, "rest"), +]) +def test_promotions_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.PromotionsServiceGrpcTransport, "grpc"), + (transports.PromotionsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.PromotionsServiceRestTransport, "rest"), +]) +def test_promotions_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", [ + (PromotionsServiceClient, "grpc"), + (PromotionsServiceAsyncClient, "grpc_asyncio"), + (PromotionsServiceClient, "rest"), +]) +def test_promotions_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_promotions_service_client_get_transport_class(): + transport = PromotionsServiceClient.get_transport_class() + available_transports = [ + transports.PromotionsServiceGrpcTransport, + transports.PromotionsServiceRestTransport, + ] + assert transport in available_transports + + transport = PromotionsServiceClient.get_transport_class("grpc") + assert transport == transports.PromotionsServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (PromotionsServiceClient, transports.PromotionsServiceGrpcTransport, "grpc"), + (PromotionsServiceAsyncClient, transports.PromotionsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (PromotionsServiceClient, transports.PromotionsServiceRestTransport, "rest"), +]) +@mock.patch.object(PromotionsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PromotionsServiceClient)) +@mock.patch.object(PromotionsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PromotionsServiceAsyncClient)) +def test_promotions_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(PromotionsServiceClient, '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(PromotionsServiceClient, '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", [ + (PromotionsServiceClient, transports.PromotionsServiceGrpcTransport, "grpc", "true"), + (PromotionsServiceAsyncClient, transports.PromotionsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (PromotionsServiceClient, transports.PromotionsServiceGrpcTransport, "grpc", "false"), + (PromotionsServiceAsyncClient, transports.PromotionsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (PromotionsServiceClient, transports.PromotionsServiceRestTransport, "rest", "true"), + (PromotionsServiceClient, transports.PromotionsServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(PromotionsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PromotionsServiceClient)) +@mock.patch.object(PromotionsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PromotionsServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_promotions_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", [ + PromotionsServiceClient, PromotionsServiceAsyncClient +]) +@mock.patch.object(PromotionsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PromotionsServiceClient)) +@mock.patch.object(PromotionsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PromotionsServiceAsyncClient)) +def test_promotions_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", [ + PromotionsServiceClient, PromotionsServiceAsyncClient +]) +@mock.patch.object(PromotionsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PromotionsServiceClient)) +@mock.patch.object(PromotionsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PromotionsServiceAsyncClient)) +def test_promotions_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = PromotionsServiceClient._DEFAULT_UNIVERSE + default_endpoint = PromotionsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = PromotionsServiceClient._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", [ + (PromotionsServiceClient, transports.PromotionsServiceGrpcTransport, "grpc"), + (PromotionsServiceAsyncClient, transports.PromotionsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (PromotionsServiceClient, transports.PromotionsServiceRestTransport, "rest"), +]) +def test_promotions_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", [ + (PromotionsServiceClient, transports.PromotionsServiceGrpcTransport, "grpc", grpc_helpers), + (PromotionsServiceAsyncClient, transports.PromotionsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (PromotionsServiceClient, transports.PromotionsServiceRestTransport, "rest", None), +]) +def test_promotions_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_promotions_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_promotions_v1beta.services.promotions_service.transports.PromotionsServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = PromotionsServiceClient( + 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", [ + (PromotionsServiceClient, transports.PromotionsServiceGrpcTransport, "grpc", grpc_helpers), + (PromotionsServiceAsyncClient, transports.PromotionsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_promotions_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", [ + promotions.InsertPromotionRequest, + dict, +]) +def test_insert_promotion(request_type, transport: str = 'grpc'): + client = PromotionsServiceClient( + 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_promotion), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = promotions.Promotion( + name='name_value', + promotion_id='promotion_id_value', + content_language='content_language_value', + target_country='target_country_value', + redemption_channel=[promotions_common.RedemptionChannel.IN_STORE], + data_source='data_source_value', + version_number=1518, + ) + response = client.insert_promotion(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = promotions.InsertPromotionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, promotions.Promotion) + assert response.name == 'name_value' + assert response.promotion_id == 'promotion_id_value' + assert response.content_language == 'content_language_value' + assert response.target_country == 'target_country_value' + assert response.redemption_channel == [promotions_common.RedemptionChannel.IN_STORE] + assert response.data_source == 'data_source_value' + assert response.version_number == 1518 + + +def test_insert_promotion_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 = PromotionsServiceClient( + 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 = promotions.InsertPromotionRequest( + parent='parent_value', + data_source='data_source_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_promotion), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.insert_promotion(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == promotions.InsertPromotionRequest( + parent='parent_value', + data_source='data_source_value', + ) + +def test_insert_promotion_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = PromotionsServiceClient( + 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_promotion in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_promotion] = mock_rpc + request = {} + client.insert_promotion(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.insert_promotion(request) + + # Establish that a new wrapper 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_promotion_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = PromotionsServiceAsyncClient( + 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_promotion in client._client._transport._wrapped_methods + + # 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_promotion] = mock_rpc + + request = {} + await client.insert_promotion(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.insert_promotion(request) + + # Establish that a new wrapper 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_promotion_async(transport: str = 'grpc_asyncio', request_type=promotions.InsertPromotionRequest): + client = PromotionsServiceAsyncClient( + 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_promotion), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(promotions.Promotion( + name='name_value', + promotion_id='promotion_id_value', + content_language='content_language_value', + target_country='target_country_value', + redemption_channel=[promotions_common.RedemptionChannel.IN_STORE], + data_source='data_source_value', + version_number=1518, + )) + response = await client.insert_promotion(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = promotions.InsertPromotionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, promotions.Promotion) + assert response.name == 'name_value' + assert response.promotion_id == 'promotion_id_value' + assert response.content_language == 'content_language_value' + assert response.target_country == 'target_country_value' + assert response.redemption_channel == [promotions_common.RedemptionChannel.IN_STORE] + assert response.data_source == 'data_source_value' + assert response.version_number == 1518 + + +@pytest.mark.asyncio +async def test_insert_promotion_async_from_dict(): + await test_insert_promotion_async(request_type=dict) + +def test_insert_promotion_field_headers(): + client = PromotionsServiceClient( + 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 = promotions.InsertPromotionRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_promotion), + '__call__') as call: + call.return_value = promotions.Promotion() + client.insert_promotion(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_promotion_field_headers_async(): + client = PromotionsServiceAsyncClient( + 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 = promotions.InsertPromotionRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_promotion), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(promotions.Promotion()) + await client.insert_promotion(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + promotions.GetPromotionRequest, + dict, +]) +def test_get_promotion(request_type, transport: str = 'grpc'): + client = PromotionsServiceClient( + 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_promotion), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = promotions.Promotion( + name='name_value', + promotion_id='promotion_id_value', + content_language='content_language_value', + target_country='target_country_value', + redemption_channel=[promotions_common.RedemptionChannel.IN_STORE], + data_source='data_source_value', + version_number=1518, + ) + response = client.get_promotion(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = promotions.GetPromotionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, promotions.Promotion) + assert response.name == 'name_value' + assert response.promotion_id == 'promotion_id_value' + assert response.content_language == 'content_language_value' + assert response.target_country == 'target_country_value' + assert response.redemption_channel == [promotions_common.RedemptionChannel.IN_STORE] + assert response.data_source == 'data_source_value' + assert response.version_number == 1518 + + +def test_get_promotion_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 = PromotionsServiceClient( + 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 = promotions.GetPromotionRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_promotion), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_promotion(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == promotions.GetPromotionRequest( + name='name_value', + ) + +def test_get_promotion_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = PromotionsServiceClient( + 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_promotion in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_promotion] = mock_rpc + request = {} + client.get_promotion(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_promotion(request) + + # Establish that a new wrapper 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_promotion_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = PromotionsServiceAsyncClient( + 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_promotion in client._client._transport._wrapped_methods + + # 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_promotion] = mock_rpc + + request = {} + await client.get_promotion(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_promotion(request) + + # Establish that a new wrapper 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_promotion_async(transport: str = 'grpc_asyncio', request_type=promotions.GetPromotionRequest): + client = PromotionsServiceAsyncClient( + 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_promotion), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(promotions.Promotion( + name='name_value', + promotion_id='promotion_id_value', + content_language='content_language_value', + target_country='target_country_value', + redemption_channel=[promotions_common.RedemptionChannel.IN_STORE], + data_source='data_source_value', + version_number=1518, + )) + response = await client.get_promotion(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = promotions.GetPromotionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, promotions.Promotion) + assert response.name == 'name_value' + assert response.promotion_id == 'promotion_id_value' + assert response.content_language == 'content_language_value' + assert response.target_country == 'target_country_value' + assert response.redemption_channel == [promotions_common.RedemptionChannel.IN_STORE] + assert response.data_source == 'data_source_value' + assert response.version_number == 1518 + + +@pytest.mark.asyncio +async def test_get_promotion_async_from_dict(): + await test_get_promotion_async(request_type=dict) + +def test_get_promotion_field_headers(): + client = PromotionsServiceClient( + 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 = promotions.GetPromotionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_promotion), + '__call__') as call: + call.return_value = promotions.Promotion() + client.get_promotion(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_promotion_field_headers_async(): + client = PromotionsServiceAsyncClient( + 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 = promotions.GetPromotionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_promotion), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(promotions.Promotion()) + await client.get_promotion(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_promotion_flattened(): + client = PromotionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_promotion), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = promotions.Promotion() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_promotion( + 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_promotion_flattened_error(): + client = PromotionsServiceClient( + 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_promotion( + promotions.GetPromotionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_promotion_flattened_async(): + client = PromotionsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_promotion), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = promotions.Promotion() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(promotions.Promotion()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_promotion( + 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_promotion_flattened_error_async(): + client = PromotionsServiceAsyncClient( + 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_promotion( + promotions.GetPromotionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + promotions.ListPromotionsRequest, + dict, +]) +def test_list_promotions(request_type, transport: str = 'grpc'): + client = PromotionsServiceClient( + 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_promotions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = promotions.ListPromotionsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_promotions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = promotions.ListPromotionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPromotionsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_promotions_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 = PromotionsServiceClient( + 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 = promotions.ListPromotionsRequest( + 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_promotions), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_promotions(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == promotions.ListPromotionsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_promotions_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = PromotionsServiceClient( + 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_promotions in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_promotions] = mock_rpc + request = {} + client.list_promotions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_promotions(request) + + # Establish that a new wrapper 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_promotions_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = PromotionsServiceAsyncClient( + 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_promotions in client._client._transport._wrapped_methods + + # 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_promotions] = mock_rpc + + request = {} + await client.list_promotions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_promotions(request) + + # Establish that a new wrapper 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_promotions_async(transport: str = 'grpc_asyncio', request_type=promotions.ListPromotionsRequest): + client = PromotionsServiceAsyncClient( + 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_promotions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(promotions.ListPromotionsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_promotions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = promotions.ListPromotionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPromotionsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_promotions_async_from_dict(): + await test_list_promotions_async(request_type=dict) + +def test_list_promotions_field_headers(): + client = PromotionsServiceClient( + 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 = promotions.ListPromotionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_promotions), + '__call__') as call: + call.return_value = promotions.ListPromotionsResponse() + client.list_promotions(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_promotions_field_headers_async(): + client = PromotionsServiceAsyncClient( + 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 = promotions.ListPromotionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_promotions), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(promotions.ListPromotionsResponse()) + await client.list_promotions(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_promotions_flattened(): + client = PromotionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_promotions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = promotions.ListPromotionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_promotions( + 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_promotions_flattened_error(): + client = PromotionsServiceClient( + 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_promotions( + promotions.ListPromotionsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_promotions_flattened_async(): + client = PromotionsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_promotions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = promotions.ListPromotionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(promotions.ListPromotionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_promotions( + 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_promotions_flattened_error_async(): + client = PromotionsServiceAsyncClient( + 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_promotions( + promotions.ListPromotionsRequest(), + parent='parent_value', + ) + + +def test_list_promotions_pager(transport_name: str = "grpc"): + client = PromotionsServiceClient( + 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_promotions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + promotions.ListPromotionsResponse( + promotions=[ + promotions.Promotion(), + promotions.Promotion(), + promotions.Promotion(), + ], + next_page_token='abc', + ), + promotions.ListPromotionsResponse( + promotions=[], + next_page_token='def', + ), + promotions.ListPromotionsResponse( + promotions=[ + promotions.Promotion(), + ], + next_page_token='ghi', + ), + promotions.ListPromotionsResponse( + promotions=[ + promotions.Promotion(), + promotions.Promotion(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_promotions(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, promotions.Promotion) + for i in results) +def test_list_promotions_pages(transport_name: str = "grpc"): + client = PromotionsServiceClient( + 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_promotions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + promotions.ListPromotionsResponse( + promotions=[ + promotions.Promotion(), + promotions.Promotion(), + promotions.Promotion(), + ], + next_page_token='abc', + ), + promotions.ListPromotionsResponse( + promotions=[], + next_page_token='def', + ), + promotions.ListPromotionsResponse( + promotions=[ + promotions.Promotion(), + ], + next_page_token='ghi', + ), + promotions.ListPromotionsResponse( + promotions=[ + promotions.Promotion(), + promotions.Promotion(), + ], + ), + RuntimeError, + ) + pages = list(client.list_promotions(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_promotions_async_pager(): + client = PromotionsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_promotions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + promotions.ListPromotionsResponse( + promotions=[ + promotions.Promotion(), + promotions.Promotion(), + promotions.Promotion(), + ], + next_page_token='abc', + ), + promotions.ListPromotionsResponse( + promotions=[], + next_page_token='def', + ), + promotions.ListPromotionsResponse( + promotions=[ + promotions.Promotion(), + ], + next_page_token='ghi', + ), + promotions.ListPromotionsResponse( + promotions=[ + promotions.Promotion(), + promotions.Promotion(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_promotions(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, promotions.Promotion) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_promotions_async_pages(): + client = PromotionsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_promotions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + promotions.ListPromotionsResponse( + promotions=[ + promotions.Promotion(), + promotions.Promotion(), + promotions.Promotion(), + ], + next_page_token='abc', + ), + promotions.ListPromotionsResponse( + promotions=[], + next_page_token='def', + ), + promotions.ListPromotionsResponse( + promotions=[ + promotions.Promotion(), + ], + next_page_token='ghi', + ), + promotions.ListPromotionsResponse( + promotions=[ + promotions.Promotion(), + promotions.Promotion(), + ], + ), + 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_promotions(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_insert_promotion_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 = PromotionsServiceClient( + 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_promotion in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_promotion] = mock_rpc + + request = {} + client.insert_promotion(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.insert_promotion(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_promotion_rest_required_fields(request_type=promotions.InsertPromotionRequest): + transport_class = transports.PromotionsServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["data_source"] = "" + request = 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_promotion._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["dataSource"] = 'data_source_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).insert_promotion._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 "dataSource" in jsonified_request + assert jsonified_request["dataSource"] == 'data_source_value' + + client = PromotionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = promotions.Promotion() + # 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 = promotions.Promotion.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_promotion(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_insert_promotion_rest_unset_required_fields(): + transport = transports.PromotionsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.insert_promotion._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "promotion", "dataSource", ))) + + +def test_get_promotion_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 = PromotionsServiceClient( + 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_promotion in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_promotion] = mock_rpc + + request = {} + client.get_promotion(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_promotion(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_promotion_rest_required_fields(request_type=promotions.GetPromotionRequest): + transport_class = transports.PromotionsServiceRestTransport + + 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_promotion._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_promotion._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 = PromotionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = promotions.Promotion() + # 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 = promotions.Promotion.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_promotion(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_promotion_rest_unset_required_fields(): + transport = transports.PromotionsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_promotion._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_promotion_rest_flattened(): + client = PromotionsServiceClient( + 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 = promotions.Promotion() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/promotions/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 = promotions.Promotion.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_promotion(**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/promotions/v1beta/{name=accounts/*/promotions/*}" % client.transport._host, args[1]) + + +def test_get_promotion_rest_flattened_error(transport: str = 'rest'): + client = PromotionsServiceClient( + 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_promotion( + promotions.GetPromotionRequest(), + name='name_value', + ) + + +def test_list_promotions_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 = PromotionsServiceClient( + 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_promotions in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_promotions] = mock_rpc + + request = {} + client.list_promotions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_promotions(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_promotions_rest_required_fields(request_type=promotions.ListPromotionsRequest): + transport_class = transports.PromotionsServiceRestTransport + + 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_promotions._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_promotions._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 = PromotionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = promotions.ListPromotionsResponse() + # 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 = promotions.ListPromotionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_promotions(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_promotions_rest_unset_required_fields(): + transport = transports.PromotionsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_promotions._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_promotions_rest_flattened(): + client = PromotionsServiceClient( + 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 = promotions.ListPromotionsResponse() + + # 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 = promotions.ListPromotionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_promotions(**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/promotions/v1beta/{parent=accounts/*}/promotions" % client.transport._host, args[1]) + + +def test_list_promotions_rest_flattened_error(transport: str = 'rest'): + client = PromotionsServiceClient( + 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_promotions( + promotions.ListPromotionsRequest(), + parent='parent_value', + ) + + +def test_list_promotions_rest_pager(transport: str = 'rest'): + client = PromotionsServiceClient( + 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 = ( + promotions.ListPromotionsResponse( + promotions=[ + promotions.Promotion(), + promotions.Promotion(), + promotions.Promotion(), + ], + next_page_token='abc', + ), + promotions.ListPromotionsResponse( + promotions=[], + next_page_token='def', + ), + promotions.ListPromotionsResponse( + promotions=[ + promotions.Promotion(), + ], + next_page_token='ghi', + ), + promotions.ListPromotionsResponse( + promotions=[ + promotions.Promotion(), + promotions.Promotion(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(promotions.ListPromotionsResponse.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_promotions(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, promotions.Promotion) + for i in results) + + pages = list(client.list_promotions(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.PromotionsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PromotionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.PromotionsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PromotionsServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.PromotionsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = PromotionsServiceClient( + 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 = PromotionsServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.PromotionsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PromotionsServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.PromotionsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = PromotionsServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.PromotionsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.PromotionsServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.PromotionsServiceGrpcTransport, + transports.PromotionsServiceGrpcAsyncIOTransport, + transports.PromotionsServiceRestTransport, +]) +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 = PromotionsServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = PromotionsServiceClient( + 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_insert_promotion_empty_call_grpc(): + client = PromotionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.insert_promotion), + '__call__') as call: + call.return_value = promotions.Promotion() + client.insert_promotion(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = promotions.InsertPromotionRequest() + + assert args[0] == request_msg + + +# This 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_promotion_empty_call_grpc(): + client = PromotionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_promotion), + '__call__') as call: + call.return_value = promotions.Promotion() + client.get_promotion(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = promotions.GetPromotionRequest() + + assert args[0] == request_msg + + +# This 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_promotions_empty_call_grpc(): + client = PromotionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_promotions), + '__call__') as call: + call.return_value = promotions.ListPromotionsResponse() + client.list_promotions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = promotions.ListPromotionsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = PromotionsServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = PromotionsServiceAsyncClient( + 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_insert_promotion_empty_call_grpc_asyncio(): + client = PromotionsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.insert_promotion), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(promotions.Promotion( + name='name_value', + promotion_id='promotion_id_value', + content_language='content_language_value', + target_country='target_country_value', + redemption_channel=[promotions_common.RedemptionChannel.IN_STORE], + data_source='data_source_value', + version_number=1518, + )) + await client.insert_promotion(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = promotions.InsertPromotionRequest() + + assert args[0] == request_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_promotion_empty_call_grpc_asyncio(): + client = PromotionsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_promotion), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(promotions.Promotion( + name='name_value', + promotion_id='promotion_id_value', + content_language='content_language_value', + target_country='target_country_value', + redemption_channel=[promotions_common.RedemptionChannel.IN_STORE], + data_source='data_source_value', + version_number=1518, + )) + await client.get_promotion(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = promotions.GetPromotionRequest() + + assert args[0] == request_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_promotions_empty_call_grpc_asyncio(): + client = PromotionsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_promotions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(promotions.ListPromotionsResponse( + next_page_token='next_page_token_value', + )) + await client.list_promotions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = promotions.ListPromotionsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = PromotionsServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_insert_promotion_rest_bad_request(request_type=promotions.InsertPromotionRequest): + client = PromotionsServiceClient( + 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_promotion(request) + + +@pytest.mark.parametrize("request_type", [ + promotions.InsertPromotionRequest, + dict, +]) +def test_insert_promotion_rest_call_success(request_type): + client = PromotionsServiceClient( + 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 = promotions.Promotion( + name='name_value', + promotion_id='promotion_id_value', + content_language='content_language_value', + target_country='target_country_value', + redemption_channel=[promotions_common.RedemptionChannel.IN_STORE], + data_source='data_source_value', + version_number=1518, + ) + + # 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 = promotions.Promotion.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_promotion(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, promotions.Promotion) + assert response.name == 'name_value' + assert response.promotion_id == 'promotion_id_value' + assert response.content_language == 'content_language_value' + assert response.target_country == 'target_country_value' + assert response.redemption_channel == [promotions_common.RedemptionChannel.IN_STORE] + assert response.data_source == 'data_source_value' + assert response.version_number == 1518 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_insert_promotion_rest_interceptors(null_interceptor): + transport = transports.PromotionsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.PromotionsServiceRestInterceptor(), + ) + client = PromotionsServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.PromotionsServiceRestInterceptor, "post_insert_promotion") as post, \ + mock.patch.object(transports.PromotionsServiceRestInterceptor, "pre_insert_promotion") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = promotions.InsertPromotionRequest.pb(promotions.InsertPromotionRequest()) + 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 = promotions.Promotion.to_json(promotions.Promotion()) + req.return_value.content = return_value + + request = promotions.InsertPromotionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = promotions.Promotion() + + client.insert_promotion(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_promotion_rest_bad_request(request_type=promotions.GetPromotionRequest): + client = PromotionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/promotions/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_promotion(request) + + +@pytest.mark.parametrize("request_type", [ + promotions.GetPromotionRequest, + dict, +]) +def test_get_promotion_rest_call_success(request_type): + client = PromotionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/promotions/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 = promotions.Promotion( + name='name_value', + promotion_id='promotion_id_value', + content_language='content_language_value', + target_country='target_country_value', + redemption_channel=[promotions_common.RedemptionChannel.IN_STORE], + data_source='data_source_value', + version_number=1518, + ) + + # 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 = promotions.Promotion.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_promotion(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, promotions.Promotion) + assert response.name == 'name_value' + assert response.promotion_id == 'promotion_id_value' + assert response.content_language == 'content_language_value' + assert response.target_country == 'target_country_value' + assert response.redemption_channel == [promotions_common.RedemptionChannel.IN_STORE] + assert response.data_source == 'data_source_value' + assert response.version_number == 1518 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_promotion_rest_interceptors(null_interceptor): + transport = transports.PromotionsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.PromotionsServiceRestInterceptor(), + ) + client = PromotionsServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.PromotionsServiceRestInterceptor, "post_get_promotion") as post, \ + mock.patch.object(transports.PromotionsServiceRestInterceptor, "pre_get_promotion") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = promotions.GetPromotionRequest.pb(promotions.GetPromotionRequest()) + 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 = promotions.Promotion.to_json(promotions.Promotion()) + req.return_value.content = return_value + + request = promotions.GetPromotionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = promotions.Promotion() + + client.get_promotion(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_promotions_rest_bad_request(request_type=promotions.ListPromotionsRequest): + client = PromotionsServiceClient( + 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_promotions(request) + + +@pytest.mark.parametrize("request_type", [ + promotions.ListPromotionsRequest, + dict, +]) +def test_list_promotions_rest_call_success(request_type): + client = PromotionsServiceClient( + 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 = promotions.ListPromotionsResponse( + 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 = promotions.ListPromotionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_promotions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPromotionsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_promotions_rest_interceptors(null_interceptor): + transport = transports.PromotionsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.PromotionsServiceRestInterceptor(), + ) + client = PromotionsServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.PromotionsServiceRestInterceptor, "post_list_promotions") as post, \ + mock.patch.object(transports.PromotionsServiceRestInterceptor, "pre_list_promotions") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = promotions.ListPromotionsRequest.pb(promotions.ListPromotionsRequest()) + 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 = promotions.ListPromotionsResponse.to_json(promotions.ListPromotionsResponse()) + req.return_value.content = return_value + + request = promotions.ListPromotionsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = promotions.ListPromotionsResponse() + + client.list_promotions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + +def test_initialize_client_w_rest(): + client = PromotionsServiceClient( + 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_insert_promotion_empty_call_rest(): + client = PromotionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.insert_promotion), + '__call__') as call: + client.insert_promotion(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = promotions.InsertPromotionRequest() + + assert args[0] == request_msg + + +# This 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_promotion_empty_call_rest(): + client = PromotionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_promotion), + '__call__') as call: + client.get_promotion(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = promotions.GetPromotionRequest() + + assert args[0] == request_msg + + +# This 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_promotions_empty_call_rest(): + client = PromotionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_promotions), + '__call__') as call: + client.list_promotions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = promotions.ListPromotionsRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = PromotionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.PromotionsServiceGrpcTransport, + ) + +def test_promotions_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.PromotionsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_promotions_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_promotions_v1beta.services.promotions_service.transports.PromotionsServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.PromotionsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'insert_promotion', + 'get_promotion', + 'list_promotions', + ) + 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_promotions_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_promotions_v1beta.services.promotions_service.transports.PromotionsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PromotionsServiceTransport( + 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_promotions_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_promotions_v1beta.services.promotions_service.transports.PromotionsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PromotionsServiceTransport() + adc.assert_called_once() + + +def test_promotions_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) + PromotionsServiceClient() + 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.PromotionsServiceGrpcTransport, + transports.PromotionsServiceGrpcAsyncIOTransport, + ], +) +def test_promotions_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.PromotionsServiceGrpcTransport, + transports.PromotionsServiceGrpcAsyncIOTransport, + transports.PromotionsServiceRestTransport, + ], +) +def test_promotions_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.PromotionsServiceGrpcTransport, grpc_helpers), + (transports.PromotionsServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_promotions_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.PromotionsServiceGrpcTransport, transports.PromotionsServiceGrpcAsyncIOTransport]) +def test_promotions_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_promotions_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.PromotionsServiceRestTransport ( + 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_promotions_service_host_no_port(transport_name): + client = PromotionsServiceClient( + 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_promotions_service_host_with_port(transport_name): + client = PromotionsServiceClient( + 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_promotions_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = PromotionsServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = PromotionsServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.insert_promotion._session + session2 = client2.transport.insert_promotion._session + assert session1 != session2 + session1 = client1.transport.get_promotion._session + session2 = client2.transport.get_promotion._session + assert session1 != session2 + session1 = client1.transport.list_promotions._session + session2 = client2.transport.list_promotions._session + assert session1 != session2 +def test_promotions_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PromotionsServiceGrpcTransport( + 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_promotions_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PromotionsServiceGrpcAsyncIOTransport( + 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.PromotionsServiceGrpcTransport, transports.PromotionsServiceGrpcAsyncIOTransport]) +def test_promotions_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.PromotionsServiceGrpcTransport, transports.PromotionsServiceGrpcAsyncIOTransport]) +def test_promotions_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_promotion_path(): + account = "squid" + promotion = "clam" + expected = "accounts/{account}/promotions/{promotion}".format(account=account, promotion=promotion, ) + actual = PromotionsServiceClient.promotion_path(account, promotion) + assert expected == actual + + +def test_parse_promotion_path(): + expected = { + "account": "whelk", + "promotion": "octopus", + } + path = PromotionsServiceClient.promotion_path(**expected) + + # Check that the path construction is reversible. + actual = PromotionsServiceClient.parse_promotion_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = PromotionsServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = PromotionsServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = PromotionsServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = PromotionsServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = PromotionsServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = PromotionsServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = PromotionsServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = PromotionsServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = PromotionsServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = PromotionsServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = PromotionsServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = PromotionsServiceClient.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 = PromotionsServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = PromotionsServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = PromotionsServiceClient.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.PromotionsServiceTransport, '_prep_wrapped_messages') as prep: + client = PromotionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.PromotionsServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = PromotionsServiceClient.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 = PromotionsServiceClient( + 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 = PromotionsServiceAsyncClient( + 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 = PromotionsServiceClient( + 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 = PromotionsServiceClient( + 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", [ + (PromotionsServiceClient, transports.PromotionsServiceGrpcTransport), + (PromotionsServiceAsyncClient, transports.PromotionsServiceGrpcAsyncIOTransport), +]) +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-quota/v1beta/.coveragerc b/owl-bot-staging/google-shopping-merchant-quota/v1beta/.coveragerc new file mode 100644 index 000000000000..8114816bc3c5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/shopping/merchant_quota/__init__.py + google/shopping/merchant_quota/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-quota/v1beta/.flake8 b/owl-bot-staging/google-shopping-merchant-quota/v1beta/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/MANIFEST.in b/owl-bot-staging/google-shopping-merchant-quota/v1beta/MANIFEST.in new file mode 100644 index 000000000000..e1f38916c325 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/shopping/merchant_quota *.py +recursive-include google/shopping/merchant_quota_v1beta *.py diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/README.rst b/owl-bot-staging/google-shopping-merchant-quota/v1beta/README.rst new file mode 100644 index 000000000000..ffa65e82132a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Shopping Merchant Quota 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 Quota 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 diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/_static/custom.css b/owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/conf.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/conf.py new file mode 100644 index 000000000000..a76827c00d4d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-quota 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("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# 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.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +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-quota" +copyright = u"2023, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# 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 = 'en' + +# 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"] + +# 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 Python", + "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-quota-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-quota.tex", + u"google-shopping-merchant-quota 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-quota", + u"Google Shopping Merchant Quota 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-quota", + u"google-shopping-merchant-quota Documentation", + author, + "google-shopping-merchant-quota", + "GAPIC library for Google Shopping Merchant Quota API", + "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": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", 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-quota/v1beta/docs/index.rst b/owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/index.rst new file mode 100644 index 000000000000..c688ba3396e1 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + merchant_quota_v1beta/services_ + merchant_quota_v1beta/types_ diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/merchant_quota_v1beta/quota_service.rst b/owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/merchant_quota_v1beta/quota_service.rst new file mode 100644 index 000000000000..1743e25da211 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/merchant_quota_v1beta/quota_service.rst @@ -0,0 +1,10 @@ +QuotaService +------------------------------ + +.. automodule:: google.shopping.merchant_quota_v1beta.services.quota_service + :members: + :inherited-members: + +.. automodule:: google.shopping.merchant_quota_v1beta.services.quota_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/merchant_quota_v1beta/services_.rst b/owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/merchant_quota_v1beta/services_.rst new file mode 100644 index 000000000000..0928f3a6f1ce --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/merchant_quota_v1beta/services_.rst @@ -0,0 +1,6 @@ +Services for Google Shopping Merchant Quota v1beta API +====================================================== +.. toctree:: + :maxdepth: 2 + + quota_service diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/merchant_quota_v1beta/types_.rst b/owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/merchant_quota_v1beta/types_.rst new file mode 100644 index 000000000000..622859fdaffb --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/merchant_quota_v1beta/types_.rst @@ -0,0 +1,6 @@ +Types for Google Shopping Merchant Quota v1beta API +=================================================== + +.. automodule:: google.shopping.merchant_quota_v1beta.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota/__init__.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota/__init__.py new file mode 100644 index 000000000000..c3a300a10746 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota/__init__.py @@ -0,0 +1,35 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_quota import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.shopping.merchant_quota_v1beta.services.quota_service.client import QuotaServiceClient +from google.shopping.merchant_quota_v1beta.services.quota_service.async_client import QuotaServiceAsyncClient + +from google.shopping.merchant_quota_v1beta.types.quota import ListQuotaGroupsRequest +from google.shopping.merchant_quota_v1beta.types.quota import ListQuotaGroupsResponse +from google.shopping.merchant_quota_v1beta.types.quota import MethodDetails +from google.shopping.merchant_quota_v1beta.types.quota import QuotaGroup + +__all__ = ('QuotaServiceClient', + 'QuotaServiceAsyncClient', + 'ListQuotaGroupsRequest', + 'ListQuotaGroupsResponse', + 'MethodDetails', + 'QuotaGroup', +) diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota/gapic_version.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-quota/v1beta/google/shopping/merchant_quota/py.typed b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota/py.typed new file mode 100644 index 000000000000..c73143bc3edf --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-shopping-merchant-quota package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/__init__.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/__init__.py new file mode 100644 index 000000000000..d5c60977b344 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_quota_v1beta import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.quota_service import QuotaServiceClient +from .services.quota_service import QuotaServiceAsyncClient + +from .types.quota import ListQuotaGroupsRequest +from .types.quota import ListQuotaGroupsResponse +from .types.quota import MethodDetails +from .types.quota import QuotaGroup + +__all__ = ( + 'QuotaServiceAsyncClient', +'ListQuotaGroupsRequest', +'ListQuotaGroupsResponse', +'MethodDetails', +'QuotaGroup', +'QuotaServiceClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/gapic_metadata.json b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/gapic_metadata.json new file mode 100644 index 000000000000..8278f93d2b60 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/gapic_metadata.json @@ -0,0 +1,43 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.shopping.merchant_quota_v1beta", + "protoPackage": "google.shopping.merchant.quota.v1beta", + "schema": "1.0", + "services": { + "QuotaService": { + "clients": { + "grpc": { + "libraryClient": "QuotaServiceClient", + "rpcs": { + "ListQuotaGroups": { + "methods": [ + "list_quota_groups" + ] + } + } + }, + "grpc-async": { + "libraryClient": "QuotaServiceAsyncClient", + "rpcs": { + "ListQuotaGroups": { + "methods": [ + "list_quota_groups" + ] + } + } + }, + "rest": { + "libraryClient": "QuotaServiceClient", + "rpcs": { + "ListQuotaGroups": { + "methods": [ + "list_quota_groups" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/gapic_version.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-quota/v1beta/google/shopping/merchant_quota_v1beta/py.typed b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/py.typed new file mode 100644 index 000000000000..c73143bc3edf --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-shopping-merchant-quota package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/__init__.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/__init__.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/__init__.py new file mode 100644 index 000000000000..512b8ee436f7 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 QuotaServiceClient +from .async_client import QuotaServiceAsyncClient + +__all__ = ( + 'QuotaServiceClient', + 'QuotaServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/async_client.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/async_client.py new file mode 100644 index 000000000000..8931f91189d1 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/async_client.py @@ -0,0 +1,384 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_quota_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 + + +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_quota_v1beta.services.quota_service import pagers +from google.shopping.merchant_quota_v1beta.types import quota +from .transports.base import QuotaServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import QuotaServiceGrpcAsyncIOTransport +from .client import QuotaServiceClient + +try: + from google.api_core import client_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 QuotaServiceAsyncClient: + """Service to get method call quota information per Merchant API + method. + """ + + _client: QuotaServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = QuotaServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = QuotaServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = QuotaServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = QuotaServiceClient._DEFAULT_UNIVERSE + + quota_group_path = staticmethod(QuotaServiceClient.quota_group_path) + parse_quota_group_path = staticmethod(QuotaServiceClient.parse_quota_group_path) + common_billing_account_path = staticmethod(QuotaServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(QuotaServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(QuotaServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(QuotaServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(QuotaServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(QuotaServiceClient.parse_common_organization_path) + common_project_path = staticmethod(QuotaServiceClient.common_project_path) + parse_common_project_path = staticmethod(QuotaServiceClient.parse_common_project_path) + common_location_path = staticmethod(QuotaServiceClient.common_location_path) + parse_common_location_path = staticmethod(QuotaServiceClient.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: + QuotaServiceAsyncClient: The constructed client. + """ + return QuotaServiceClient.from_service_account_info.__func__(QuotaServiceAsyncClient, 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: + QuotaServiceAsyncClient: The constructed client. + """ + return QuotaServiceClient.from_service_account_file.__func__(QuotaServiceAsyncClient, 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 QuotaServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> QuotaServiceTransport: + """Returns the transport used by the client instance. + + Returns: + QuotaServiceTransport: 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 = QuotaServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, QuotaServiceTransport, Callable[..., QuotaServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the quota 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,QuotaServiceTransport,Callable[..., QuotaServiceTransport]]]): + 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 QuotaServiceTransport 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 = QuotaServiceClient( + 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.quota_v1beta.QuotaServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.quota.v1beta.QuotaService", + "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.quota.v1beta.QuotaService", + "credentialsType": None, + } + ) + + async def list_quota_groups(self, + request: Optional[Union[quota.ListQuotaGroupsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListQuotaGroupsAsyncPager: + r"""Lists the daily call quota and usage per group for + 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_quota_v1beta + + async def sample_list_quota_groups(): + # Create a client + client = merchant_quota_v1beta.QuotaServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_quota_v1beta.ListQuotaGroupsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_quota_groups(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_quota_v1beta.types.ListQuotaGroupsRequest, dict]]): + The request object. Request message for the + ListQuotaGroups method. + parent (:class:`str`): + Required. The merchant account who + owns the collection of method quotas + 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_quota_v1beta.services.quota_service.pagers.ListQuotaGroupsAsyncPager: + Response message for the + ListMethodGroups 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, quota.ListQuotaGroupsRequest): + request = quota.ListQuotaGroupsRequest(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_quota_groups] + + # Certain 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.ListQuotaGroupsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "QuotaServiceAsyncClient": + 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__) + + +__all__ = ( + "QuotaServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/client.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/client.py new file mode 100644 index 000000000000..9510a56dd108 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/client.py @@ -0,0 +1,719 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +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_quota_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 + +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_quota_v1beta.services.quota_service import pagers +from google.shopping.merchant_quota_v1beta.types import quota +from .transports.base import QuotaServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import QuotaServiceGrpcTransport +from .transports.grpc_asyncio import QuotaServiceGrpcAsyncIOTransport +from .transports.rest import QuotaServiceRestTransport + + +class QuotaServiceClientMeta(type): + """Metaclass for the QuotaService 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[QuotaServiceTransport]] + _transport_registry["grpc"] = QuotaServiceGrpcTransport + _transport_registry["grpc_asyncio"] = QuotaServiceGrpcAsyncIOTransport + _transport_registry["rest"] = QuotaServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[QuotaServiceTransport]: + """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 QuotaServiceClient(metaclass=QuotaServiceClientMeta): + """Service to get method call quota 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: + QuotaServiceClient: 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: + QuotaServiceClient: 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) -> QuotaServiceTransport: + """Returns the transport used by the client instance. + + Returns: + QuotaServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def quota_group_path(account: str,group: str,) -> str: + """Returns a fully-qualified quota_group string.""" + return "accounts/{account}/groups/{group}".format(account=account, group=group, ) + + @staticmethod + def parse_quota_group_path(path: str) -> Dict[str,str]: + """Parses a quota_group path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/groups/(?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 = QuotaServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = QuotaServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = QuotaServiceClient._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 = QuotaServiceClient._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 + + @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, QuotaServiceTransport, Callable[..., QuotaServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the quota 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,QuotaServiceTransport,Callable[..., QuotaServiceTransport]]]): + 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 QuotaServiceTransport 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 = QuotaServiceClient._read_environment_variables() + self._client_cert_source = QuotaServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = QuotaServiceClient._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, QuotaServiceTransport) + if transport_provided: + # transport is a QuotaServiceTransport 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(QuotaServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + QuotaServiceClient._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[QuotaServiceTransport], Callable[..., QuotaServiceTransport]] = ( + QuotaServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., QuotaServiceTransport], 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.quota_v1beta.QuotaServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.quota.v1beta.QuotaService", + "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.quota.v1beta.QuotaService", + "credentialsType": None, + } + ) + + def list_quota_groups(self, + request: Optional[Union[quota.ListQuotaGroupsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListQuotaGroupsPager: + r"""Lists the daily call quota and usage per group for + 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_quota_v1beta + + def sample_list_quota_groups(): + # Create a client + client = merchant_quota_v1beta.QuotaServiceClient() + + # Initialize request argument(s) + request = merchant_quota_v1beta.ListQuotaGroupsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_quota_groups(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.shopping.merchant_quota_v1beta.types.ListQuotaGroupsRequest, dict]): + The request object. Request message for the + ListQuotaGroups method. + parent (str): + Required. The merchant account who + owns the collection of method quotas + 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_quota_v1beta.services.quota_service.pagers.ListQuotaGroupsPager: + Response message for the + ListMethodGroups 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, quota.ListQuotaGroupsRequest): + request = quota.ListQuotaGroupsRequest(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_quota_groups] + + # Certain 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.ListQuotaGroupsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "QuotaServiceClient": + 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__) + + +__all__ = ( + "QuotaServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/pagers.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/pagers.py new file mode 100644 index 000000000000..afdb52c6f999 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/pagers.py @@ -0,0 +1,166 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_quota_v1beta.types import quota + + +class ListQuotaGroupsPager: + """A pager for iterating through ``list_quota_groups`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_quota_v1beta.types.ListQuotaGroupsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``quota_groups`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListQuotaGroups`` requests and continue to iterate + through the ``quota_groups`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_quota_v1beta.types.ListQuotaGroupsResponse` + 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[..., quota.ListQuotaGroupsResponse], + request: quota.ListQuotaGroupsRequest, + response: quota.ListQuotaGroupsResponse, + *, + 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_quota_v1beta.types.ListQuotaGroupsRequest): + The initial request object. + response (google.shopping.merchant_quota_v1beta.types.ListQuotaGroupsResponse): + 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 = quota.ListQuotaGroupsRequest(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[quota.ListQuotaGroupsResponse]: + 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[quota.QuotaGroup]: + for page in self.pages: + yield from page.quota_groups + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListQuotaGroupsAsyncPager: + """A pager for iterating through ``list_quota_groups`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_quota_v1beta.types.ListQuotaGroupsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``quota_groups`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListQuotaGroups`` requests and continue to iterate + through the ``quota_groups`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_quota_v1beta.types.ListQuotaGroupsResponse` + 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[quota.ListQuotaGroupsResponse]], + request: quota.ListQuotaGroupsRequest, + response: quota.ListQuotaGroupsResponse, + *, + 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_quota_v1beta.types.ListQuotaGroupsRequest): + The initial request object. + response (google.shopping.merchant_quota_v1beta.types.ListQuotaGroupsResponse): + 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 = quota.ListQuotaGroupsRequest(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[quota.ListQuotaGroupsResponse]: + 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[quota.QuotaGroup]: + async def async_generator(): + async for page in self.pages: + for response in page.quota_groups: + 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-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/README.rst new file mode 100644 index 000000000000..06b6eb4da828 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`QuotaServiceTransport` is the ABC for all transports. +- public child `QuotaServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `QuotaServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseQuotaServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `QuotaServiceRestTransport` 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-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/__init__.py new file mode 100644 index 000000000000..1dddb73e2611 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 QuotaServiceTransport +from .grpc import QuotaServiceGrpcTransport +from .grpc_asyncio import QuotaServiceGrpcAsyncIOTransport +from .rest import QuotaServiceRestTransport +from .rest import QuotaServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[QuotaServiceTransport]] +_transport_registry['grpc'] = QuotaServiceGrpcTransport +_transport_registry['grpc_asyncio'] = QuotaServiceGrpcAsyncIOTransport +_transport_registry['rest'] = QuotaServiceRestTransport + +__all__ = ( + 'QuotaServiceTransport', + 'QuotaServiceGrpcTransport', + 'QuotaServiceGrpcAsyncIOTransport', + 'QuotaServiceRestTransport', + 'QuotaServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/base.py new file mode 100644 index 000000000000..b4e3103cc44f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/base.py @@ -0,0 +1,154 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_quota_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 + +from google.shopping.merchant_quota_v1beta.types import quota + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class QuotaServiceTransport(abc.ABC): + """Abstract transport class for QuotaService.""" + + 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_quota_groups: gapic_v1.method.wrap_method( + self.list_quota_groups, + 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_quota_groups(self) -> Callable[ + [quota.ListQuotaGroupsRequest], + Union[ + quota.ListQuotaGroupsResponse, + Awaitable[quota.ListQuotaGroupsResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'QuotaServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/grpc.py new file mode 100644 index 000000000000..9230328ddc64 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/grpc.py @@ -0,0 +1,349 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_quota_v1beta.types import quota +from .base import QuotaServiceTransport, 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.quota.v1beta.QuotaService", + "rpcName": 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.quota.v1beta.QuotaService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class QuotaServiceGrpcTransport(QuotaServiceTransport): + """gRPC backend transport for QuotaService. + + Service to get method call quota 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 list_quota_groups(self) -> Callable[ + [quota.ListQuotaGroupsRequest], + quota.ListQuotaGroupsResponse]: + r"""Return a callable for the list quota groups method over gRPC. + + Lists the daily call quota and usage per group for + your Merchant Center account. + + Returns: + Callable[[~.ListQuotaGroupsRequest], + ~.ListQuotaGroupsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_quota_groups' not in self._stubs: + self._stubs['list_quota_groups'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.quota.v1beta.QuotaService/ListQuotaGroups', + request_serializer=quota.ListQuotaGroupsRequest.serialize, + response_deserializer=quota.ListQuotaGroupsResponse.deserialize, + ) + return self._stubs['list_quota_groups'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'QuotaServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..91389d2fd3ca --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/grpc_asyncio.py @@ -0,0 +1,369 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_quota_v1beta.types import quota +from .base import QuotaServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import QuotaServiceGrpcTransport + +try: + from google.api_core import client_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.quota.v1beta.QuotaService", + "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.quota.v1beta.QuotaService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class QuotaServiceGrpcAsyncIOTransport(QuotaServiceTransport): + """gRPC AsyncIO backend transport for QuotaService. + + Service to get method call quota 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 list_quota_groups(self) -> Callable[ + [quota.ListQuotaGroupsRequest], + Awaitable[quota.ListQuotaGroupsResponse]]: + r"""Return a callable for the list quota groups method over gRPC. + + Lists the daily call quota and usage per group for + your Merchant Center account. + + Returns: + Callable[[~.ListQuotaGroupsRequest], + Awaitable[~.ListQuotaGroupsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_quota_groups' not in self._stubs: + self._stubs['list_quota_groups'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.quota.v1beta.QuotaService/ListQuotaGroups', + request_serializer=quota.ListQuotaGroupsRequest.serialize, + response_deserializer=quota.ListQuotaGroupsResponse.deserialize, + ) + return self._stubs['list_quota_groups'] + + 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_quota_groups: self._wrap_method( + self.list_quota_groups, + 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__ = ( + 'QuotaServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/rest.py new file mode 100644 index 000000000000..e6157bea06ce --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/rest.py @@ -0,0 +1,330 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +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_quota_v1beta.types import quota + + +from .rest_base import _BaseQuotaServiceRestTransport +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}", +) + + +class QuotaServiceRestInterceptor: + """Interceptor for QuotaService. + + 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 QuotaServiceRestTransport. + + .. code-block:: python + class MyCustomQuotaServiceInterceptor(QuotaServiceRestInterceptor): + def pre_list_quota_groups(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_quota_groups(self, response): + logging.log(f"Received response: {response}") + return response + + transport = QuotaServiceRestTransport(interceptor=MyCustomQuotaServiceInterceptor()) + client = QuotaServiceClient(transport=transport) + + + """ + def pre_list_quota_groups(self, request: quota.ListQuotaGroupsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[quota.ListQuotaGroupsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_quota_groups + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuotaService server. + """ + return request, metadata + + def post_list_quota_groups(self, response: quota.ListQuotaGroupsResponse) -> quota.ListQuotaGroupsResponse: + """Post-rpc interceptor for list_quota_groups + + Override in a subclass to manipulate the response + after it is returned by the QuotaService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class QuotaServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: QuotaServiceRestInterceptor + + +class QuotaServiceRestTransport(_BaseQuotaServiceRestTransport): + """REST backend synchronous transport for QuotaService. + + Service to get method call quota 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[QuotaServiceRestInterceptor] = 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 QuotaServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _ListQuotaGroups(_BaseQuotaServiceRestTransport._BaseListQuotaGroups, QuotaServiceRestStub): + def __hash__(self): + return hash("QuotaServiceRestTransport.ListQuotaGroups") + + @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: quota.ListQuotaGroupsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> quota.ListQuotaGroupsResponse: + r"""Call the list quota groups method over HTTP. + + Args: + request (~.quota.ListQuotaGroupsRequest): + The request object. Request message for the + ListQuotaGroups method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.quota.ListQuotaGroupsResponse: + Response message for the + ListMethodGroups method. + + """ + + http_options = _BaseQuotaServiceRestTransport._BaseListQuotaGroups._get_http_options() + + request, metadata = self._interceptor.pre_list_quota_groups(request, metadata) + transcoded_request = _BaseQuotaServiceRestTransport._BaseListQuotaGroups._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseQuotaServiceRestTransport._BaseListQuotaGroups._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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.quota_v1beta.QuotaServiceClient.ListQuotaGroups", + extra = { + "serviceName": "google.shopping.merchant.quota.v1beta.QuotaService", + "rpcName": "ListQuotaGroups", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuotaServiceRestTransport._ListQuotaGroups._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 = quota.ListQuotaGroupsResponse() + pb_resp = quota.ListQuotaGroupsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_quota_groups(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = quota.ListQuotaGroupsResponse.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.quota_v1beta.QuotaServiceClient.list_quota_groups", + extra = { + "serviceName": "google.shopping.merchant.quota.v1beta.QuotaService", + "rpcName": "ListQuotaGroups", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def list_quota_groups(self) -> Callable[ + [quota.ListQuotaGroupsRequest], + quota.ListQuotaGroupsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListQuotaGroups(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'QuotaServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/rest_base.py new file mode 100644 index 000000000000..c7b406f9d383 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/rest_base.py @@ -0,0 +1,128 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 QuotaServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.shopping.merchant_quota_v1beta.types import quota + + +class _BaseQuotaServiceRestTransport(QuotaServiceTransport): + """Base REST backend transport for QuotaService. + + 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 _BaseListQuotaGroups: + 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': '/quota/v1beta/{parent=accounts/*}/quotas', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = quota.ListQuotaGroupsRequest.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(_BaseQuotaServiceRestTransport._BaseListQuotaGroups._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseQuotaServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/types/__init__.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/types/__init__.py new file mode 100644 index 000000000000..e4e09c52c9f5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/types/__init__.py @@ -0,0 +1,28 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .quota import ( + ListQuotaGroupsRequest, + ListQuotaGroupsResponse, + MethodDetails, + QuotaGroup, +) + +__all__ = ( + 'ListQuotaGroupsRequest', + 'ListQuotaGroupsResponse', + 'MethodDetails', + 'QuotaGroup', +) diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/types/quota.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/types/quota.py new file mode 100644 index 000000000000..c1a3a79456e3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/types/quota.py @@ -0,0 +1,184 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.quota.v1beta', + manifest={ + 'QuotaGroup', + 'MethodDetails', + 'ListQuotaGroupsRequest', + 'ListQuotaGroupsResponse', + }, +) + + +class QuotaGroup(proto.Message): + r"""The group information for methods in the Merchant API. The + quota is shared between all methods in the group. Even if none + of the methods within the group have usage the information for + the group is returned. + + Attributes: + name (str): + Identifier. The resource name of the quota + group. Format: accounts/{account}/quotas/{group} + Note: There is no guarantee on the format of + {group} + quota_usage (int): + Output only. The current quota usage, meaning + the number of calls already made on a given day + to the methods in the group. The daily quota + limits reset at at 12:00 PM midday UTC. + quota_limit (int): + Output only. The maximum number of calls + allowed per day for the group. + quota_minute_limit (int): + Output only. The maximum number of calls + allowed per minute for the group. + method_details (MutableSequence[google.shopping.merchant_quota_v1beta.types.MethodDetails]): + Output only. List of all methods group quota + applies to. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + quota_usage: int = proto.Field( + proto.INT64, + number=2, + ) + quota_limit: int = proto.Field( + proto.INT64, + number=3, + ) + quota_minute_limit: int = proto.Field( + proto.INT64, + number=5, + ) + method_details: MutableSequence['MethodDetails'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='MethodDetails', + ) + + +class MethodDetails(proto.Message): + r"""The method details per method in the Merchant API. + + Attributes: + method (str): + Output only. The name of the method for example + ``products.list``. + version (str): + Output only. The API version that the method + belongs to. + subapi (str): + Output only. The sub-API that the method + belongs to. + path (str): + Output only. The path for the method such as + ``products/v1/productInputs.insert`` + """ + + method: str = proto.Field( + proto.STRING, + number=1, + ) + version: str = proto.Field( + proto.STRING, + number=2, + ) + subapi: str = proto.Field( + proto.STRING, + number=3, + ) + path: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListQuotaGroupsRequest(proto.Message): + r"""Request message for the ListQuotaGroups method. + + Attributes: + parent (str): + Required. The merchant account who owns the + collection of method quotas Format: + accounts/{account} + page_size (int): + Optional. The maximum number of quotas to + return in the response, used for paging. + Defaults to 500; values above 1000 will be + coerced to 1000. + page_token (str): + Optional. Token (if provided) to retrieve the + subsequent page. All other parameters must match + the original 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 ListQuotaGroupsResponse(proto.Message): + r"""Response message for the ListMethodGroups method. + + Attributes: + quota_groups (MutableSequence[google.shopping.merchant_quota_v1beta.types.QuotaGroup]): + The methods, current quota usage and limits per each group. + The quota is shared between all methods in the group. The + groups are sorted in descending order based on + [quotaUsage][google.shopping.merchant.quota.v1main.QuotaGroup.quota_usage]. + 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 + + quota_groups: MutableSequence['QuotaGroup'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='QuotaGroup', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/mypy.ini b/owl-bot-staging/google-shopping-merchant-quota/v1beta/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/noxfile.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/noxfile.py new file mode 100644 index 000000000000..ab60f2f71caf --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/noxfile.py @@ -0,0 +1,280 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = 'google-shopping-merchant-quota' + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.13" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "prerelease_deps", +] + +@nox.session(python=ALL_PYTHON) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def unit(session, protobuf_implementation): + """Run the unit test suite.""" + + 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+") + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") + + # 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") + + session.run( + 'py.test', + '--quiet', + '--cov=google/shopping/merchant_quota_v1beta/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)), + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + +@nox.session(python=ALL_PYTHON[-1]) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def prerelease_deps(session, protobuf_implementation): + """Run the unit test suite against pre-release versions of dependencies.""" + + 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 test environment dependencies + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + + # Install the package without dependencies + session.install('-e', '.', '--no-deps') + + # We test the minimum dependency versions using the minimum Python + # version so the lowest python runtime that we test has a corresponding constraints + # file, located at `testing/constraints--.txt`, which contains all of the + # 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 + ) + ] + + session.install(*constraints_deps) + + prerel_deps = [ + "googleapis-common-protos", + "google-api-core", + "google-auth", + # Exclude grpcio!=1.67.0rc1 which does not support python 3.13 + "grpcio!=1.67.0rc1", + "grpcio-status", + "protobuf", + "proto-plus", + ] + + for dep in prerel_deps: + session.install("--pre", "--no-deps", "--upgrade", dep) + + # Remaining dependencies + other_deps = [ + "requests", + ] + session.install(*other_deps) + + # Print out prerelease package versions + + session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") + session.run("python", "-c", "import google.auth; print(google.auth.__version__)") + session.run("python", "-c", "import grpc; print(grpc.__version__)") + session.run( + "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" + ) + session.run( + "python", "-c", "import proto; print(proto.__version__)" + ) + + session.run( + 'py.test', + '--quiet', + '--cov=google/shopping/merchant_quota_v1beta/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)), + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + + +@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=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 docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==7.0.1", "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=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", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/samples/generated_samples/merchantapi_v1beta_generated_quota_service_list_quota_groups_async.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/samples/generated_samples/merchantapi_v1beta_generated_quota_service_list_quota_groups_async.py new file mode 100644 index 000000000000..9df3fdc41d00 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/samples/generated_samples/merchantapi_v1beta_generated_quota_service_list_quota_groups_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListQuotaGroups +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-quota + + +# [START merchantapi_v1beta_generated_QuotaService_ListQuotaGroups_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_quota_v1beta + + +async def sample_list_quota_groups(): + # Create a client + client = merchant_quota_v1beta.QuotaServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_quota_v1beta.ListQuotaGroupsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_quota_groups(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_QuotaService_ListQuotaGroups_async] diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/samples/generated_samples/merchantapi_v1beta_generated_quota_service_list_quota_groups_sync.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/samples/generated_samples/merchantapi_v1beta_generated_quota_service_list_quota_groups_sync.py new file mode 100644 index 000000000000..9cb0fe36a759 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/samples/generated_samples/merchantapi_v1beta_generated_quota_service_list_quota_groups_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListQuotaGroups +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-quota + + +# [START merchantapi_v1beta_generated_QuotaService_ListQuotaGroups_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_quota_v1beta + + +def sample_list_quota_groups(): + # Create a client + client = merchant_quota_v1beta.QuotaServiceClient() + + # Initialize request argument(s) + request = merchant_quota_v1beta.ListQuotaGroupsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_quota_groups(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_QuotaService_ListQuotaGroups_sync] diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.quota.v1beta.json b/owl-bot-staging/google-shopping-merchant-quota/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.quota.v1beta.json new file mode 100644 index 000000000000..48037ddf7f53 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.quota.v1beta.json @@ -0,0 +1,176 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.shopping.merchant.quota.v1beta", + "version": "v1beta" + } + ], + "language": "PYTHON", + "name": "google-shopping-merchant-quota", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_quota_v1beta.QuotaServiceAsyncClient", + "shortName": "QuotaServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_quota_v1beta.QuotaServiceAsyncClient.list_quota_groups", + "method": { + "fullName": "google.shopping.merchant.quota.v1beta.QuotaService.ListQuotaGroups", + "service": { + "fullName": "google.shopping.merchant.quota.v1beta.QuotaService", + "shortName": "QuotaService" + }, + "shortName": "ListQuotaGroups" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_quota_v1beta.types.ListQuotaGroupsRequest" + }, + { + "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_quota_v1beta.services.quota_service.pagers.ListQuotaGroupsAsyncPager", + "shortName": "list_quota_groups" + }, + "description": "Sample for ListQuotaGroups", + "file": "merchantapi_v1beta_generated_quota_service_list_quota_groups_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_QuotaService_ListQuotaGroups_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_quota_service_list_quota_groups_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_quota_v1beta.QuotaServiceClient", + "shortName": "QuotaServiceClient" + }, + "fullName": "google.shopping.merchant_quota_v1beta.QuotaServiceClient.list_quota_groups", + "method": { + "fullName": "google.shopping.merchant.quota.v1beta.QuotaService.ListQuotaGroups", + "service": { + "fullName": "google.shopping.merchant.quota.v1beta.QuotaService", + "shortName": "QuotaService" + }, + "shortName": "ListQuotaGroups" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_quota_v1beta.types.ListQuotaGroupsRequest" + }, + { + "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_quota_v1beta.services.quota_service.pagers.ListQuotaGroupsPager", + "shortName": "list_quota_groups" + }, + "description": "Sample for ListQuotaGroups", + "file": "merchantapi_v1beta_generated_quota_service_list_quota_groups_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_QuotaService_ListQuotaGroups_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_quota_service_list_quota_groups_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/scripts/fixup_merchant_quota_v1beta_keywords.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/scripts/fixup_merchant_quota_v1beta_keywords.py new file mode 100644 index 000000000000..46854d66644a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/scripts/fixup_merchant_quota_v1beta_keywords.py @@ -0,0 +1,176 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_quotaCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'list_quota_groups': ('parent', 'page_size', 'page_token', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=merchant_quotaCallTransformer(), +): + """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_quota 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-quota/v1beta/setup.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/setup.py new file mode 100644 index 000000000000..29c7175c3c3a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/setup.py @@ -0,0 +1,98 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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-quota' + + +description = "Google Shopping Merchant Quota API client library" + +version = None + +with open(os.path.join(package_root, 'google/shopping/merchant_quota/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.0dev,!=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.0dev,!=2.24.0,!=2.25.0", + "proto-plus >= 1.22.3, <2.0.0dev", + "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'", + "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", +] +extras = { +} +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-quota" + +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-quota/v1beta/testing/constraints-3.10.txt b/owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.10.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.11.txt b/owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.11.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.12.txt b/owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.12.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.13.txt b/owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.13.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.13.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.7.txt b/owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.7.txt new file mode 100644 index 000000000000..fc812592b0ee --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.7.txt @@ -0,0 +1,10 @@ +# 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.0dev", +# 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 diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.8.txt b/owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.8.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.9.txt b/owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.9.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/tests/__init__.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-quota/v1beta/tests/unit/__init__.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-quota/v1beta/tests/unit/gapic/__init__.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-quota/v1beta/tests/unit/gapic/merchant_quota_v1beta/__init__.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/tests/unit/gapic/merchant_quota_v1beta/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/tests/unit/gapic/merchant_quota_v1beta/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-quota/v1beta/tests/unit/gapic/merchant_quota_v1beta/test_quota_service.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/tests/unit/gapic/merchant_quota_v1beta/test_quota_service.py new file mode 100644 index 000000000000..bdc981b12f6f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-quota/v1beta/tests/unit/gapic/merchant_quota_v1beta/test_quota_service.py @@ -0,0 +1,2347 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_quota_v1beta.services.quota_service import QuotaServiceAsyncClient +from google.shopping.merchant_quota_v1beta.services.quota_service import QuotaServiceClient +from google.shopping.merchant_quota_v1beta.services.quota_service import pagers +from google.shopping.merchant_quota_v1beta.services.quota_service import transports +from google.shopping.merchant_quota_v1beta.types import quota +import google.auth + + +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 QuotaServiceClient._get_default_mtls_endpoint(None) is None + assert QuotaServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert QuotaServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert QuotaServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert QuotaServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert QuotaServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert QuotaServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert QuotaServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert QuotaServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + QuotaServiceClient._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 QuotaServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert QuotaServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert QuotaServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + QuotaServiceClient._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 QuotaServiceClient._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 QuotaServiceClient._get_client_cert_source(None, False) is None + assert QuotaServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert QuotaServiceClient._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 QuotaServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert QuotaServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(QuotaServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(QuotaServiceClient)) +@mock.patch.object(QuotaServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(QuotaServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = QuotaServiceClient._DEFAULT_UNIVERSE + default_endpoint = QuotaServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = QuotaServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert QuotaServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert QuotaServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == QuotaServiceClient.DEFAULT_MTLS_ENDPOINT + assert QuotaServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert QuotaServiceClient._get_api_endpoint(None, None, default_universe, "always") == QuotaServiceClient.DEFAULT_MTLS_ENDPOINT + assert QuotaServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == QuotaServiceClient.DEFAULT_MTLS_ENDPOINT + assert QuotaServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert QuotaServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + QuotaServiceClient._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 QuotaServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert QuotaServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert QuotaServiceClient._get_universe_domain(None, None) == QuotaServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + QuotaServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize("client_class,transport_name", [ + (QuotaServiceClient, "grpc"), + (QuotaServiceAsyncClient, "grpc_asyncio"), + (QuotaServiceClient, "rest"), +]) +def test_quota_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.QuotaServiceGrpcTransport, "grpc"), + (transports.QuotaServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.QuotaServiceRestTransport, "rest"), +]) +def test_quota_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", [ + (QuotaServiceClient, "grpc"), + (QuotaServiceAsyncClient, "grpc_asyncio"), + (QuotaServiceClient, "rest"), +]) +def test_quota_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_quota_service_client_get_transport_class(): + transport = QuotaServiceClient.get_transport_class() + available_transports = [ + transports.QuotaServiceGrpcTransport, + transports.QuotaServiceRestTransport, + ] + assert transport in available_transports + + transport = QuotaServiceClient.get_transport_class("grpc") + assert transport == transports.QuotaServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (QuotaServiceClient, transports.QuotaServiceGrpcTransport, "grpc"), + (QuotaServiceAsyncClient, transports.QuotaServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (QuotaServiceClient, transports.QuotaServiceRestTransport, "rest"), +]) +@mock.patch.object(QuotaServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(QuotaServiceClient)) +@mock.patch.object(QuotaServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(QuotaServiceAsyncClient)) +def test_quota_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(QuotaServiceClient, '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(QuotaServiceClient, '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", [ + (QuotaServiceClient, transports.QuotaServiceGrpcTransport, "grpc", "true"), + (QuotaServiceAsyncClient, transports.QuotaServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (QuotaServiceClient, transports.QuotaServiceGrpcTransport, "grpc", "false"), + (QuotaServiceAsyncClient, transports.QuotaServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (QuotaServiceClient, transports.QuotaServiceRestTransport, "rest", "true"), + (QuotaServiceClient, transports.QuotaServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(QuotaServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(QuotaServiceClient)) +@mock.patch.object(QuotaServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(QuotaServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_quota_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", [ + QuotaServiceClient, QuotaServiceAsyncClient +]) +@mock.patch.object(QuotaServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(QuotaServiceClient)) +@mock.patch.object(QuotaServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(QuotaServiceAsyncClient)) +def test_quota_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", [ + QuotaServiceClient, QuotaServiceAsyncClient +]) +@mock.patch.object(QuotaServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(QuotaServiceClient)) +@mock.patch.object(QuotaServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(QuotaServiceAsyncClient)) +def test_quota_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = QuotaServiceClient._DEFAULT_UNIVERSE + default_endpoint = QuotaServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = QuotaServiceClient._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", [ + (QuotaServiceClient, transports.QuotaServiceGrpcTransport, "grpc"), + (QuotaServiceAsyncClient, transports.QuotaServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (QuotaServiceClient, transports.QuotaServiceRestTransport, "rest"), +]) +def test_quota_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", [ + (QuotaServiceClient, transports.QuotaServiceGrpcTransport, "grpc", grpc_helpers), + (QuotaServiceAsyncClient, transports.QuotaServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (QuotaServiceClient, transports.QuotaServiceRestTransport, "rest", None), +]) +def test_quota_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_quota_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_quota_v1beta.services.quota_service.transports.QuotaServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = QuotaServiceClient( + 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", [ + (QuotaServiceClient, transports.QuotaServiceGrpcTransport, "grpc", grpc_helpers), + (QuotaServiceAsyncClient, transports.QuotaServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_quota_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", [ + quota.ListQuotaGroupsRequest, + dict, +]) +def test_list_quota_groups(request_type, transport: str = 'grpc'): + client = QuotaServiceClient( + 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_quota_groups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = quota.ListQuotaGroupsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_quota_groups(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = quota.ListQuotaGroupsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListQuotaGroupsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_quota_groups_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 = QuotaServiceClient( + 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 = quota.ListQuotaGroupsRequest( + 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_quota_groups), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_quota_groups(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == quota.ListQuotaGroupsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_quota_groups_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = QuotaServiceClient( + 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_quota_groups in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_quota_groups] = mock_rpc + request = {} + client.list_quota_groups(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_quota_groups(request) + + # Establish that a new wrapper 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_quota_groups_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = QuotaServiceAsyncClient( + 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_quota_groups in client._client._transport._wrapped_methods + + # 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_quota_groups] = mock_rpc + + request = {} + await client.list_quota_groups(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_quota_groups(request) + + # Establish that a new wrapper 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_quota_groups_async(transport: str = 'grpc_asyncio', request_type=quota.ListQuotaGroupsRequest): + client = QuotaServiceAsyncClient( + 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_quota_groups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(quota.ListQuotaGroupsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_quota_groups(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = quota.ListQuotaGroupsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListQuotaGroupsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_quota_groups_async_from_dict(): + await test_list_quota_groups_async(request_type=dict) + +def test_list_quota_groups_field_headers(): + client = QuotaServiceClient( + 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 = quota.ListQuotaGroupsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_quota_groups), + '__call__') as call: + call.return_value = quota.ListQuotaGroupsResponse() + client.list_quota_groups(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_quota_groups_field_headers_async(): + client = QuotaServiceAsyncClient( + 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 = quota.ListQuotaGroupsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_quota_groups), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(quota.ListQuotaGroupsResponse()) + await client.list_quota_groups(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_quota_groups_flattened(): + client = QuotaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_quota_groups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = quota.ListQuotaGroupsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_quota_groups( + 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_quota_groups_flattened_error(): + client = QuotaServiceClient( + 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_quota_groups( + quota.ListQuotaGroupsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_quota_groups_flattened_async(): + client = QuotaServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_quota_groups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = quota.ListQuotaGroupsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(quota.ListQuotaGroupsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_quota_groups( + 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_quota_groups_flattened_error_async(): + client = QuotaServiceAsyncClient( + 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_quota_groups( + quota.ListQuotaGroupsRequest(), + parent='parent_value', + ) + + +def test_list_quota_groups_pager(transport_name: str = "grpc"): + client = QuotaServiceClient( + 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_quota_groups), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + quota.ListQuotaGroupsResponse( + quota_groups=[ + quota.QuotaGroup(), + quota.QuotaGroup(), + quota.QuotaGroup(), + ], + next_page_token='abc', + ), + quota.ListQuotaGroupsResponse( + quota_groups=[], + next_page_token='def', + ), + quota.ListQuotaGroupsResponse( + quota_groups=[ + quota.QuotaGroup(), + ], + next_page_token='ghi', + ), + quota.ListQuotaGroupsResponse( + quota_groups=[ + quota.QuotaGroup(), + quota.QuotaGroup(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_quota_groups(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, quota.QuotaGroup) + for i in results) +def test_list_quota_groups_pages(transport_name: str = "grpc"): + client = QuotaServiceClient( + 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_quota_groups), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + quota.ListQuotaGroupsResponse( + quota_groups=[ + quota.QuotaGroup(), + quota.QuotaGroup(), + quota.QuotaGroup(), + ], + next_page_token='abc', + ), + quota.ListQuotaGroupsResponse( + quota_groups=[], + next_page_token='def', + ), + quota.ListQuotaGroupsResponse( + quota_groups=[ + quota.QuotaGroup(), + ], + next_page_token='ghi', + ), + quota.ListQuotaGroupsResponse( + quota_groups=[ + quota.QuotaGroup(), + quota.QuotaGroup(), + ], + ), + RuntimeError, + ) + pages = list(client.list_quota_groups(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_quota_groups_async_pager(): + client = QuotaServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_quota_groups), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + quota.ListQuotaGroupsResponse( + quota_groups=[ + quota.QuotaGroup(), + quota.QuotaGroup(), + quota.QuotaGroup(), + ], + next_page_token='abc', + ), + quota.ListQuotaGroupsResponse( + quota_groups=[], + next_page_token='def', + ), + quota.ListQuotaGroupsResponse( + quota_groups=[ + quota.QuotaGroup(), + ], + next_page_token='ghi', + ), + quota.ListQuotaGroupsResponse( + quota_groups=[ + quota.QuotaGroup(), + quota.QuotaGroup(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_quota_groups(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, quota.QuotaGroup) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_quota_groups_async_pages(): + client = QuotaServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_quota_groups), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + quota.ListQuotaGroupsResponse( + quota_groups=[ + quota.QuotaGroup(), + quota.QuotaGroup(), + quota.QuotaGroup(), + ], + next_page_token='abc', + ), + quota.ListQuotaGroupsResponse( + quota_groups=[], + next_page_token='def', + ), + quota.ListQuotaGroupsResponse( + quota_groups=[ + quota.QuotaGroup(), + ], + next_page_token='ghi', + ), + quota.ListQuotaGroupsResponse( + quota_groups=[ + quota.QuotaGroup(), + quota.QuotaGroup(), + ], + ), + 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_quota_groups(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_quota_groups_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 = QuotaServiceClient( + 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_quota_groups in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_quota_groups] = mock_rpc + + request = {} + client.list_quota_groups(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_quota_groups(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_quota_groups_rest_required_fields(request_type=quota.ListQuotaGroupsRequest): + transport_class = transports.QuotaServiceRestTransport + + 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_quota_groups._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_quota_groups._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 = QuotaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = quota.ListQuotaGroupsResponse() + # 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 = quota.ListQuotaGroupsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_quota_groups(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_quota_groups_rest_unset_required_fields(): + transport = transports.QuotaServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_quota_groups._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_quota_groups_rest_flattened(): + client = QuotaServiceClient( + 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 = quota.ListQuotaGroupsResponse() + + # 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 = quota.ListQuotaGroupsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_quota_groups(**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/quota/v1beta/{parent=accounts/*}/quotas" % client.transport._host, args[1]) + + +def test_list_quota_groups_rest_flattened_error(transport: str = 'rest'): + client = QuotaServiceClient( + 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_quota_groups( + quota.ListQuotaGroupsRequest(), + parent='parent_value', + ) + + +def test_list_quota_groups_rest_pager(transport: str = 'rest'): + client = QuotaServiceClient( + 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 = ( + quota.ListQuotaGroupsResponse( + quota_groups=[ + quota.QuotaGroup(), + quota.QuotaGroup(), + quota.QuotaGroup(), + ], + next_page_token='abc', + ), + quota.ListQuotaGroupsResponse( + quota_groups=[], + next_page_token='def', + ), + quota.ListQuotaGroupsResponse( + quota_groups=[ + quota.QuotaGroup(), + ], + next_page_token='ghi', + ), + quota.ListQuotaGroupsResponse( + quota_groups=[ + quota.QuotaGroup(), + quota.QuotaGroup(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(quota.ListQuotaGroupsResponse.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_quota_groups(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, quota.QuotaGroup) + for i in results) + + pages = list(client.list_quota_groups(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.QuotaServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = QuotaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.QuotaServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = QuotaServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.QuotaServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = QuotaServiceClient( + 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 = QuotaServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.QuotaServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = QuotaServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.QuotaServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = QuotaServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.QuotaServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.QuotaServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.QuotaServiceGrpcTransport, + transports.QuotaServiceGrpcAsyncIOTransport, + transports.QuotaServiceRestTransport, +]) +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 = QuotaServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = QuotaServiceClient( + 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_quota_groups_empty_call_grpc(): + client = QuotaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_quota_groups), + '__call__') as call: + call.return_value = quota.ListQuotaGroupsResponse() + client.list_quota_groups(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = quota.ListQuotaGroupsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = QuotaServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = QuotaServiceAsyncClient( + 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_quota_groups_empty_call_grpc_asyncio(): + client = QuotaServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_quota_groups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(quota.ListQuotaGroupsResponse( + next_page_token='next_page_token_value', + )) + await client.list_quota_groups(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = quota.ListQuotaGroupsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = QuotaServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_quota_groups_rest_bad_request(request_type=quota.ListQuotaGroupsRequest): + client = QuotaServiceClient( + 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_quota_groups(request) + + +@pytest.mark.parametrize("request_type", [ + quota.ListQuotaGroupsRequest, + dict, +]) +def test_list_quota_groups_rest_call_success(request_type): + client = QuotaServiceClient( + 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 = quota.ListQuotaGroupsResponse( + 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 = quota.ListQuotaGroupsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_quota_groups(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListQuotaGroupsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_quota_groups_rest_interceptors(null_interceptor): + transport = transports.QuotaServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.QuotaServiceRestInterceptor(), + ) + client = QuotaServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.QuotaServiceRestInterceptor, "post_list_quota_groups") as post, \ + mock.patch.object(transports.QuotaServiceRestInterceptor, "pre_list_quota_groups") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = quota.ListQuotaGroupsRequest.pb(quota.ListQuotaGroupsRequest()) + 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 = quota.ListQuotaGroupsResponse.to_json(quota.ListQuotaGroupsResponse()) + req.return_value.content = return_value + + request = quota.ListQuotaGroupsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = quota.ListQuotaGroupsResponse() + + client.list_quota_groups(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + +def test_initialize_client_w_rest(): + client = QuotaServiceClient( + 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_quota_groups_empty_call_rest(): + client = QuotaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_quota_groups), + '__call__') as call: + client.list_quota_groups(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = quota.ListQuotaGroupsRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = QuotaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.QuotaServiceGrpcTransport, + ) + +def test_quota_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.QuotaServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_quota_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_quota_v1beta.services.quota_service.transports.QuotaServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.QuotaServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_quota_groups', + ) + 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_quota_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_quota_v1beta.services.quota_service.transports.QuotaServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.QuotaServiceTransport( + 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_quota_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_quota_v1beta.services.quota_service.transports.QuotaServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.QuotaServiceTransport() + adc.assert_called_once() + + +def test_quota_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) + QuotaServiceClient() + 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.QuotaServiceGrpcTransport, + transports.QuotaServiceGrpcAsyncIOTransport, + ], +) +def test_quota_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.QuotaServiceGrpcTransport, + transports.QuotaServiceGrpcAsyncIOTransport, + transports.QuotaServiceRestTransport, + ], +) +def test_quota_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.QuotaServiceGrpcTransport, grpc_helpers), + (transports.QuotaServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_quota_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.QuotaServiceGrpcTransport, transports.QuotaServiceGrpcAsyncIOTransport]) +def test_quota_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_quota_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.QuotaServiceRestTransport ( + 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_quota_service_host_no_port(transport_name): + client = QuotaServiceClient( + 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_quota_service_host_with_port(transport_name): + client = QuotaServiceClient( + 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_quota_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = QuotaServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = QuotaServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_quota_groups._session + session2 = client2.transport.list_quota_groups._session + assert session1 != session2 +def test_quota_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.QuotaServiceGrpcTransport( + 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_quota_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.QuotaServiceGrpcAsyncIOTransport( + 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.QuotaServiceGrpcTransport, transports.QuotaServiceGrpcAsyncIOTransport]) +def test_quota_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.QuotaServiceGrpcTransport, transports.QuotaServiceGrpcAsyncIOTransport]) +def test_quota_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_quota_group_path(): + account = "squid" + group = "clam" + expected = "accounts/{account}/groups/{group}".format(account=account, group=group, ) + actual = QuotaServiceClient.quota_group_path(account, group) + assert expected == actual + + +def test_parse_quota_group_path(): + expected = { + "account": "whelk", + "group": "octopus", + } + path = QuotaServiceClient.quota_group_path(**expected) + + # Check that the path construction is reversible. + actual = QuotaServiceClient.parse_quota_group_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = QuotaServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = QuotaServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = QuotaServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = QuotaServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = QuotaServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = QuotaServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = QuotaServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = QuotaServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = QuotaServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = QuotaServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = QuotaServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = QuotaServiceClient.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 = QuotaServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = QuotaServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = QuotaServiceClient.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.QuotaServiceTransport, '_prep_wrapped_messages') as prep: + client = QuotaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.QuotaServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = QuotaServiceClient.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 = QuotaServiceClient( + 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 = QuotaServiceAsyncClient( + 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 = QuotaServiceClient( + 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 = QuotaServiceClient( + 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", [ + (QuotaServiceClient, transports.QuotaServiceGrpcTransport), + (QuotaServiceAsyncClient, transports.QuotaServiceGrpcAsyncIOTransport), +]) +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-reports/v1beta/.coveragerc b/owl-bot-staging/google-shopping-merchant-reports/v1beta/.coveragerc new file mode 100644 index 000000000000..ee0fc2257adb --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/v1beta/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/shopping/merchant_reports/__init__.py + google/shopping/merchant_reports/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-reports/v1beta/.flake8 b/owl-bot-staging/google-shopping-merchant-reports/v1beta/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/v1beta/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/MANIFEST.in b/owl-bot-staging/google-shopping-merchant-reports/v1beta/MANIFEST.in new file mode 100644 index 000000000000..baaee74264b4 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/v1beta/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/shopping/merchant_reports *.py +recursive-include google/shopping/merchant_reports_v1beta *.py diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/README.rst b/owl-bot-staging/google-shopping-merchant-reports/v1beta/README.rst new file mode 100644 index 000000000000..33f7f87a7a6c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/v1beta/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Shopping Merchant Reports 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 Reports 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 diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/_static/custom.css b/owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/conf.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/conf.py new file mode 100644 index 000000000000..e082f6d42016 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-reports 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("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# 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.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +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-reports" +copyright = u"2023, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# 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 = 'en' + +# 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"] + +# 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 Python", + "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-reports-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-reports.tex", + u"google-shopping-merchant-reports 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-reports", + u"Google Shopping Merchant Reports 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-reports", + u"google-shopping-merchant-reports Documentation", + author, + "google-shopping-merchant-reports", + "GAPIC library for Google Shopping Merchant Reports API", + "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": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", 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-reports/v1beta/docs/index.rst b/owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/index.rst new file mode 100644 index 000000000000..56b119bc9a3d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + merchant_reports_v1beta/services_ + merchant_reports_v1beta/types_ diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/merchant_reports_v1beta/report_service.rst b/owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/merchant_reports_v1beta/report_service.rst new file mode 100644 index 000000000000..38d2a647339e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/merchant_reports_v1beta/report_service.rst @@ -0,0 +1,10 @@ +ReportService +------------------------------- + +.. automodule:: google.shopping.merchant_reports_v1beta.services.report_service + :members: + :inherited-members: + +.. automodule:: google.shopping.merchant_reports_v1beta.services.report_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/merchant_reports_v1beta/services_.rst b/owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/merchant_reports_v1beta/services_.rst new file mode 100644 index 000000000000..55109976f640 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/merchant_reports_v1beta/services_.rst @@ -0,0 +1,6 @@ +Services for Google Shopping Merchant Reports v1beta API +======================================================== +.. toctree:: + :maxdepth: 2 + + report_service diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/merchant_reports_v1beta/types_.rst b/owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/merchant_reports_v1beta/types_.rst new file mode 100644 index 000000000000..3f9d6a921dbd --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/merchant_reports_v1beta/types_.rst @@ -0,0 +1,6 @@ +Types for Google Shopping Merchant Reports v1beta API +===================================================== + +.. automodule:: google.shopping.merchant_reports_v1beta.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports/__init__.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports/__init__.py new file mode 100644 index 000000000000..9a1854b53a00 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports/__init__.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_reports import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.shopping.merchant_reports_v1beta.services.report_service.client import ReportServiceClient +from google.shopping.merchant_reports_v1beta.services.report_service.async_client import ReportServiceAsyncClient + +from google.shopping.merchant_reports_v1beta.types.reports import BestSellersBrandView +from google.shopping.merchant_reports_v1beta.types.reports import BestSellersProductClusterView +from google.shopping.merchant_reports_v1beta.types.reports import CompetitiveVisibilityBenchmarkView +from google.shopping.merchant_reports_v1beta.types.reports import CompetitiveVisibilityCompetitorView +from google.shopping.merchant_reports_v1beta.types.reports import CompetitiveVisibilityTopMerchantView +from google.shopping.merchant_reports_v1beta.types.reports import MarketingMethod +from google.shopping.merchant_reports_v1beta.types.reports import NonProductPerformanceView +from google.shopping.merchant_reports_v1beta.types.reports import PriceCompetitivenessProductView +from google.shopping.merchant_reports_v1beta.types.reports import PriceInsightsProductView +from google.shopping.merchant_reports_v1beta.types.reports import ProductPerformanceView +from google.shopping.merchant_reports_v1beta.types.reports import ProductView +from google.shopping.merchant_reports_v1beta.types.reports import RelativeDemand +from google.shopping.merchant_reports_v1beta.types.reports import RelativeDemandChangeType +from google.shopping.merchant_reports_v1beta.types.reports import ReportGranularity +from google.shopping.merchant_reports_v1beta.types.reports import ReportRow +from google.shopping.merchant_reports_v1beta.types.reports import SearchRequest +from google.shopping.merchant_reports_v1beta.types.reports import SearchResponse +from google.shopping.merchant_reports_v1beta.types.reports import TrafficSource + +__all__ = ('ReportServiceClient', + 'ReportServiceAsyncClient', + 'BestSellersBrandView', + 'BestSellersProductClusterView', + 'CompetitiveVisibilityBenchmarkView', + 'CompetitiveVisibilityCompetitorView', + 'CompetitiveVisibilityTopMerchantView', + 'MarketingMethod', + 'NonProductPerformanceView', + 'PriceCompetitivenessProductView', + 'PriceInsightsProductView', + 'ProductPerformanceView', + 'ProductView', + 'RelativeDemand', + 'RelativeDemandChangeType', + 'ReportGranularity', + 'ReportRow', + 'SearchRequest', + 'SearchResponse', + 'TrafficSource', +) diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports/gapic_version.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-reports/v1beta/google/shopping/merchant_reports/py.typed b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports/py.typed new file mode 100644 index 000000000000..925c5df4dab6 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-shopping-merchant-reports package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/__init__.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/__init__.py new file mode 100644 index 000000000000..3f709e1477bb --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/__init__.py @@ -0,0 +1,64 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_reports_v1beta import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.report_service import ReportServiceClient +from .services.report_service import ReportServiceAsyncClient + +from .types.reports import BestSellersBrandView +from .types.reports import BestSellersProductClusterView +from .types.reports import CompetitiveVisibilityBenchmarkView +from .types.reports import CompetitiveVisibilityCompetitorView +from .types.reports import CompetitiveVisibilityTopMerchantView +from .types.reports import MarketingMethod +from .types.reports import NonProductPerformanceView +from .types.reports import PriceCompetitivenessProductView +from .types.reports import PriceInsightsProductView +from .types.reports import ProductPerformanceView +from .types.reports import ProductView +from .types.reports import RelativeDemand +from .types.reports import RelativeDemandChangeType +from .types.reports import ReportGranularity +from .types.reports import ReportRow +from .types.reports import SearchRequest +from .types.reports import SearchResponse +from .types.reports import TrafficSource + +__all__ = ( + 'ReportServiceAsyncClient', +'BestSellersBrandView', +'BestSellersProductClusterView', +'CompetitiveVisibilityBenchmarkView', +'CompetitiveVisibilityCompetitorView', +'CompetitiveVisibilityTopMerchantView', +'MarketingMethod', +'NonProductPerformanceView', +'PriceCompetitivenessProductView', +'PriceInsightsProductView', +'ProductPerformanceView', +'ProductView', +'RelativeDemand', +'RelativeDemandChangeType', +'ReportGranularity', +'ReportRow', +'ReportServiceClient', +'SearchRequest', +'SearchResponse', +'TrafficSource', +) diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/gapic_metadata.json b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/gapic_metadata.json new file mode 100644 index 000000000000..77c560dce3aa --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/gapic_metadata.json @@ -0,0 +1,43 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.shopping.merchant_reports_v1beta", + "protoPackage": "google.shopping.merchant.reports.v1beta", + "schema": "1.0", + "services": { + "ReportService": { + "clients": { + "grpc": { + "libraryClient": "ReportServiceClient", + "rpcs": { + "Search": { + "methods": [ + "search" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ReportServiceAsyncClient", + "rpcs": { + "Search": { + "methods": [ + "search" + ] + } + } + }, + "rest": { + "libraryClient": "ReportServiceClient", + "rpcs": { + "Search": { + "methods": [ + "search" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/gapic_version.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-reports/v1beta/google/shopping/merchant_reports_v1beta/py.typed b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/py.typed new file mode 100644 index 000000000000..925c5df4dab6 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-shopping-merchant-reports package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/__init__.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/__init__.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/__init__.py new file mode 100644 index 000000000000..90845062383d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 ReportServiceClient +from .async_client import ReportServiceAsyncClient + +__all__ = ( + 'ReportServiceClient', + 'ReportServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/async_client.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/async_client.py new file mode 100644 index 000000000000..d2879ac7215b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/async_client.py @@ -0,0 +1,385 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_reports_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 + + +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_reports_v1beta.services.report_service import pagers +from google.shopping.merchant_reports_v1beta.types import reports +from .transports.base import ReportServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ReportServiceGrpcAsyncIOTransport +from .client import ReportServiceClient + +try: + from google.api_core import client_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 ReportServiceAsyncClient: + """Service for retrieving reports and insights about your + products, their performance, and their competitive environment + on Google. + """ + + _client: ReportServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = ReportServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ReportServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = ReportServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = ReportServiceClient._DEFAULT_UNIVERSE + + common_billing_account_path = staticmethod(ReportServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ReportServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ReportServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(ReportServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(ReportServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(ReportServiceClient.parse_common_organization_path) + common_project_path = staticmethod(ReportServiceClient.common_project_path) + parse_common_project_path = staticmethod(ReportServiceClient.parse_common_project_path) + common_location_path = staticmethod(ReportServiceClient.common_location_path) + parse_common_location_path = staticmethod(ReportServiceClient.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: + ReportServiceAsyncClient: The constructed client. + """ + return ReportServiceClient.from_service_account_info.__func__(ReportServiceAsyncClient, 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: + ReportServiceAsyncClient: The constructed client. + """ + return ReportServiceClient.from_service_account_file.__func__(ReportServiceAsyncClient, 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 ReportServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ReportServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ReportServiceTransport: 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 = ReportServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, ReportServiceTransport, Callable[..., ReportServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the report 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,ReportServiceTransport,Callable[..., ReportServiceTransport]]]): + 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 ReportServiceTransport 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 = ReportServiceClient( + 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.reports_v1beta.ReportServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.reports.v1beta.ReportService", + "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.reports.v1beta.ReportService", + "credentialsType": None, + } + ) + + async def search(self, + request: Optional[Union[reports.SearchRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.SearchAsyncPager: + r"""Retrieves a report defined by a search query. The response might + contain fewer rows than specified by ``page_size``. Rely on + ``next_page_token`` to determine if there are more rows to be + requested. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_reports_v1beta + + async def sample_search(): + # Create a client + client = merchant_reports_v1beta.ReportServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_reports_v1beta.SearchRequest( + parent="parent_value", + query="query_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_reports_v1beta.types.SearchRequest, dict]]): + The request object. Request message for the ``ReportService.Search`` method. + parent (:class:`str`): + Required. Id of the account making + the call. Must be a standalone account + or an MCA subaccount. 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_reports_v1beta.services.report_service.pagers.SearchAsyncPager: + Response message for the ReportService.Search 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, reports.SearchRequest): + request = reports.SearchRequest(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.search] + + # Certain 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.SearchAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "ReportServiceAsyncClient": + 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__) + + +__all__ = ( + "ReportServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/client.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/client.py new file mode 100644 index 000000000000..dbef05c011c0 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/client.py @@ -0,0 +1,711 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +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_reports_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 + +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_reports_v1beta.services.report_service import pagers +from google.shopping.merchant_reports_v1beta.types import reports +from .transports.base import ReportServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ReportServiceGrpcTransport +from .transports.grpc_asyncio import ReportServiceGrpcAsyncIOTransport +from .transports.rest import ReportServiceRestTransport + + +class ReportServiceClientMeta(type): + """Metaclass for the ReportService 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[ReportServiceTransport]] + _transport_registry["grpc"] = ReportServiceGrpcTransport + _transport_registry["grpc_asyncio"] = ReportServiceGrpcAsyncIOTransport + _transport_registry["rest"] = ReportServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[ReportServiceTransport]: + """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 ReportServiceClient(metaclass=ReportServiceClientMeta): + """Service for retrieving reports and insights about your + products, their performance, and their competitive environment + on Google. + """ + + @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: + ReportServiceClient: 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: + ReportServiceClient: 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) -> ReportServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ReportServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @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 = ReportServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = ReportServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ReportServiceClient._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 = ReportServiceClient._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 + + @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, ReportServiceTransport, Callable[..., ReportServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the report 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,ReportServiceTransport,Callable[..., ReportServiceTransport]]]): + 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 ReportServiceTransport 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 = ReportServiceClient._read_environment_variables() + self._client_cert_source = ReportServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = ReportServiceClient._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, ReportServiceTransport) + if transport_provided: + # transport is a ReportServiceTransport 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(ReportServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + ReportServiceClient._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[ReportServiceTransport], Callable[..., ReportServiceTransport]] = ( + ReportServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., ReportServiceTransport], 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.reports_v1beta.ReportServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.reports.v1beta.ReportService", + "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.reports.v1beta.ReportService", + "credentialsType": None, + } + ) + + def search(self, + request: Optional[Union[reports.SearchRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.SearchPager: + r"""Retrieves a report defined by a search query. The response might + contain fewer rows than specified by ``page_size``. Rely on + ``next_page_token`` to determine if there are more rows to be + requested. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_reports_v1beta + + def sample_search(): + # Create a client + client = merchant_reports_v1beta.ReportServiceClient() + + # Initialize request argument(s) + request = merchant_reports_v1beta.SearchRequest( + parent="parent_value", + query="query_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.shopping.merchant_reports_v1beta.types.SearchRequest, dict]): + The request object. Request message for the ``ReportService.Search`` method. + parent (str): + Required. Id of the account making + the call. Must be a standalone account + or an MCA subaccount. 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_reports_v1beta.services.report_service.pagers.SearchPager: + Response message for the ReportService.Search 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, reports.SearchRequest): + request = reports.SearchRequest(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.search] + + # Certain 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.SearchPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "ReportServiceClient": + 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__) + + +__all__ = ( + "ReportServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/pagers.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/pagers.py new file mode 100644 index 000000000000..272b1d940d9b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/pagers.py @@ -0,0 +1,166 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_reports_v1beta.types import reports + + +class SearchPager: + """A pager for iterating through ``search`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_reports_v1beta.types.SearchResponse` object, and + provides an ``__iter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``Search`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_reports_v1beta.types.SearchResponse` + 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[..., reports.SearchResponse], + request: reports.SearchRequest, + response: reports.SearchResponse, + *, + 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_reports_v1beta.types.SearchRequest): + The initial request object. + response (google.shopping.merchant_reports_v1beta.types.SearchResponse): + 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 = reports.SearchRequest(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[reports.SearchResponse]: + 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[reports.ReportRow]: + for page in self.pages: + yield from page.results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class SearchAsyncPager: + """A pager for iterating through ``search`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_reports_v1beta.types.SearchResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``Search`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_reports_v1beta.types.SearchResponse` + 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[reports.SearchResponse]], + request: reports.SearchRequest, + response: reports.SearchResponse, + *, + 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_reports_v1beta.types.SearchRequest): + The initial request object. + response (google.shopping.merchant_reports_v1beta.types.SearchResponse): + 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 = reports.SearchRequest(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[reports.SearchResponse]: + 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[reports.ReportRow]: + async def async_generator(): + async for page in self.pages: + for response in page.results: + 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-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/README.rst new file mode 100644 index 000000000000..3ff494d6f149 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`ReportServiceTransport` is the ABC for all transports. +- public child `ReportServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `ReportServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseReportServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `ReportServiceRestTransport` 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-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/__init__.py new file mode 100644 index 000000000000..a2d3480db148 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 ReportServiceTransport +from .grpc import ReportServiceGrpcTransport +from .grpc_asyncio import ReportServiceGrpcAsyncIOTransport +from .rest import ReportServiceRestTransport +from .rest import ReportServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ReportServiceTransport]] +_transport_registry['grpc'] = ReportServiceGrpcTransport +_transport_registry['grpc_asyncio'] = ReportServiceGrpcAsyncIOTransport +_transport_registry['rest'] = ReportServiceRestTransport + +__all__ = ( + 'ReportServiceTransport', + 'ReportServiceGrpcTransport', + 'ReportServiceGrpcAsyncIOTransport', + 'ReportServiceRestTransport', + 'ReportServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/base.py new file mode 100644 index 000000000000..93d8c8bff712 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/base.py @@ -0,0 +1,154 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_reports_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 + +from google.shopping.merchant_reports_v1beta.types import reports + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class ReportServiceTransport(abc.ABC): + """Abstract transport class for ReportService.""" + + 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.search: gapic_v1.method.wrap_method( + self.search, + 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 search(self) -> Callable[ + [reports.SearchRequest], + Union[ + reports.SearchResponse, + Awaitable[reports.SearchResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'ReportServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/grpc.py new file mode 100644 index 000000000000..0ce8c3266cbb --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/grpc.py @@ -0,0 +1,352 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_reports_v1beta.types import reports +from .base import ReportServiceTransport, 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.reports.v1beta.ReportService", + "rpcName": 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.reports.v1beta.ReportService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class ReportServiceGrpcTransport(ReportServiceTransport): + """gRPC backend transport for ReportService. + + Service for retrieving reports and insights about your + products, their performance, and their competitive environment + on Google. + + This 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 search(self) -> Callable[ + [reports.SearchRequest], + reports.SearchResponse]: + r"""Return a callable for the search method over gRPC. + + Retrieves a report defined by a search query. The response might + contain fewer rows than specified by ``page_size``. Rely on + ``next_page_token`` to determine if there are more rows to be + requested. + + Returns: + Callable[[~.SearchRequest], + ~.SearchResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search' not in self._stubs: + self._stubs['search'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.reports.v1beta.ReportService/Search', + request_serializer=reports.SearchRequest.serialize, + response_deserializer=reports.SearchResponse.deserialize, + ) + return self._stubs['search'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'ReportServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..0820b13df3a3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/grpc_asyncio.py @@ -0,0 +1,372 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_reports_v1beta.types import reports +from .base import ReportServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import ReportServiceGrpcTransport + +try: + from google.api_core import client_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.reports.v1beta.ReportService", + "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.reports.v1beta.ReportService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class ReportServiceGrpcAsyncIOTransport(ReportServiceTransport): + """gRPC AsyncIO backend transport for ReportService. + + Service for retrieving reports and insights about your + products, their performance, and their competitive environment + on Google. + + This 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 search(self) -> Callable[ + [reports.SearchRequest], + Awaitable[reports.SearchResponse]]: + r"""Return a callable for the search method over gRPC. + + Retrieves a report defined by a search query. The response might + contain fewer rows than specified by ``page_size``. Rely on + ``next_page_token`` to determine if there are more rows to be + requested. + + Returns: + Callable[[~.SearchRequest], + Awaitable[~.SearchResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search' not in self._stubs: + self._stubs['search'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.reports.v1beta.ReportService/Search', + request_serializer=reports.SearchRequest.serialize, + response_deserializer=reports.SearchResponse.deserialize, + ) + return self._stubs['search'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.search: self._wrap_method( + self.search, + 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__ = ( + 'ReportServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/rest.py new file mode 100644 index 000000000000..870bb0a81407 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/rest.py @@ -0,0 +1,333 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +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_reports_v1beta.types import reports + + +from .rest_base import _BaseReportServiceRestTransport +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}", +) + + +class ReportServiceRestInterceptor: + """Interceptor for ReportService. + + 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 ReportServiceRestTransport. + + .. code-block:: python + class MyCustomReportServiceInterceptor(ReportServiceRestInterceptor): + def pre_search(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_search(self, response): + logging.log(f"Received response: {response}") + return response + + transport = ReportServiceRestTransport(interceptor=MyCustomReportServiceInterceptor()) + client = ReportServiceClient(transport=transport) + + + """ + def pre_search(self, request: reports.SearchRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[reports.SearchRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for search + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReportService server. + """ + return request, metadata + + def post_search(self, response: reports.SearchResponse) -> reports.SearchResponse: + """Post-rpc interceptor for search + + Override in a subclass to manipulate the response + after it is returned by the ReportService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class ReportServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: ReportServiceRestInterceptor + + +class ReportServiceRestTransport(_BaseReportServiceRestTransport): + """REST backend synchronous transport for ReportService. + + Service for retrieving reports and insights about your + products, their performance, and their competitive environment + on Google. + + This 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[ReportServiceRestInterceptor] = 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 ReportServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _Search(_BaseReportServiceRestTransport._BaseSearch, ReportServiceRestStub): + def __hash__(self): + return hash("ReportServiceRestTransport.Search") + + @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: reports.SearchRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> reports.SearchResponse: + r"""Call the search method over HTTP. + + Args: + request (~.reports.SearchRequest): + The request object. Request message for the ``ReportService.Search`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.reports.SearchResponse: + Response message for the ``ReportService.Search`` + method. + + """ + + http_options = _BaseReportServiceRestTransport._BaseSearch._get_http_options() + + request, metadata = self._interceptor.pre_search(request, metadata) + transcoded_request = _BaseReportServiceRestTransport._BaseSearch._get_transcoded_request(http_options, request) + + body = _BaseReportServiceRestTransport._BaseSearch._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseReportServiceRestTransport._BaseSearch._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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.reports_v1beta.ReportServiceClient.Search", + extra = { + "serviceName": "google.shopping.merchant.reports.v1beta.ReportService", + "rpcName": "Search", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ReportServiceRestTransport._Search._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 = reports.SearchResponse() + pb_resp = reports.SearchResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_search(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = reports.SearchResponse.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.reports_v1beta.ReportServiceClient.search", + extra = { + "serviceName": "google.shopping.merchant.reports.v1beta.ReportService", + "rpcName": "Search", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def search(self) -> Callable[ + [reports.SearchRequest], + reports.SearchResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Search(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'ReportServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/rest_base.py new file mode 100644 index 000000000000..b7f01e752a42 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/rest_base.py @@ -0,0 +1,138 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 ReportServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.shopping.merchant_reports_v1beta.types import reports + + +class _BaseReportServiceRestTransport(ReportServiceTransport): + """Base REST backend transport for ReportService. + + 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 _BaseSearch: + 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': '/reports/v1beta/{parent=accounts/*}/reports:search', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = reports.SearchRequest.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(_BaseReportServiceRestTransport._BaseSearch._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseReportServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/types/__init__.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/types/__init__.py new file mode 100644 index 000000000000..5e965be69091 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/types/__init__.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .reports import ( + BestSellersBrandView, + BestSellersProductClusterView, + CompetitiveVisibilityBenchmarkView, + CompetitiveVisibilityCompetitorView, + CompetitiveVisibilityTopMerchantView, + MarketingMethod, + NonProductPerformanceView, + PriceCompetitivenessProductView, + PriceInsightsProductView, + ProductPerformanceView, + ProductView, + RelativeDemand, + RelativeDemandChangeType, + ReportGranularity, + ReportRow, + SearchRequest, + SearchResponse, + TrafficSource, +) + +__all__ = ( + 'BestSellersBrandView', + 'BestSellersProductClusterView', + 'CompetitiveVisibilityBenchmarkView', + 'CompetitiveVisibilityCompetitorView', + 'CompetitiveVisibilityTopMerchantView', + 'MarketingMethod', + 'NonProductPerformanceView', + 'PriceCompetitivenessProductView', + 'PriceInsightsProductView', + 'ProductPerformanceView', + 'ProductView', + 'RelativeDemand', + 'RelativeDemandChangeType', + 'ReportGranularity', + 'ReportRow', + 'SearchRequest', + 'SearchResponse', + 'TrafficSource', +) diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/types/reports.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/types/reports.py new file mode 100644 index 000000000000..49712fcea3ab --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/types/reports.py @@ -0,0 +1,2521 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 timestamp_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.reports.v1beta', + manifest={ + 'SearchRequest', + 'SearchResponse', + 'ReportRow', + 'ProductPerformanceView', + 'ProductView', + 'PriceCompetitivenessProductView', + 'PriceInsightsProductView', + 'BestSellersProductClusterView', + 'BestSellersBrandView', + 'NonProductPerformanceView', + 'CompetitiveVisibilityCompetitorView', + 'CompetitiveVisibilityTopMerchantView', + 'CompetitiveVisibilityBenchmarkView', + 'MarketingMethod', + 'ReportGranularity', + 'RelativeDemand', + 'RelativeDemandChangeType', + 'TrafficSource', + }, +) + + +class SearchRequest(proto.Message): + r"""Request message for the ``ReportService.Search`` method. + + Attributes: + parent (str): + Required. Id of the account making the call. + Must be a standalone account or an MCA + subaccount. Format: accounts/{account} + query (str): + Required. Query that defines a report to be + retrieved. + For details on how to construct your query, see + the Query Language guide. For the full list of + available tables and fields, see the Available + fields. + page_size (int): + Optional. Number of ``ReportRows`` to retrieve in a single + page. Defaults to 1000. Values above 5000 are coerced to + 5000. + page_token (str): + Optional. Token of the page to retrieve. If not specified, + the first page of results is returned. In order to request + the next page of results, the value obtained from + ``next_page_token`` in the previous response should be used. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + query: str = proto.Field( + proto.STRING, + number=2, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + page_token: str = proto.Field( + proto.STRING, + number=4, + ) + + +class SearchResponse(proto.Message): + r"""Response message for the ``ReportService.Search`` method. + + Attributes: + results (MutableSequence[google.shopping.merchant_reports_v1beta.types.ReportRow]): + Rows that matched the search query. + next_page_token (str): + Token which can be sent as ``page_token`` to retrieve the + next page. If omitted, there are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + results: MutableSequence['ReportRow'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ReportRow', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ReportRow(proto.Message): + r"""Result row returned from the search query. + + Only the message corresponding to the queried table is populated + in the response. Within the populated message, only the fields + requested explicitly in the query are populated. + + Attributes: + product_performance_view (google.shopping.merchant_reports_v1beta.types.ProductPerformanceView): + Fields available for query in ``product_performance_view`` + table. + non_product_performance_view (google.shopping.merchant_reports_v1beta.types.NonProductPerformanceView): + Fields available for query in + ``non_product_performance_view`` table. + product_view (google.shopping.merchant_reports_v1beta.types.ProductView): + Fields available for query in ``product_view`` table. + price_competitiveness_product_view (google.shopping.merchant_reports_v1beta.types.PriceCompetitivenessProductView): + Fields available for query in + ``price_competitiveness_product_view`` table. + price_insights_product_view (google.shopping.merchant_reports_v1beta.types.PriceInsightsProductView): + Fields available for query in + ``price_insights_product_view`` table. + best_sellers_product_cluster_view (google.shopping.merchant_reports_v1beta.types.BestSellersProductClusterView): + Fields available for query in + ``best_sellers_product_cluster_view`` table. + best_sellers_brand_view (google.shopping.merchant_reports_v1beta.types.BestSellersBrandView): + Fields available for query in ``best_sellers_brand_view`` + table. + competitive_visibility_competitor_view (google.shopping.merchant_reports_v1beta.types.CompetitiveVisibilityCompetitorView): + Fields available for query in + ``competitive_visibility_competitor_view`` table. + competitive_visibility_top_merchant_view (google.shopping.merchant_reports_v1beta.types.CompetitiveVisibilityTopMerchantView): + Fields available for query in + ``competitive_visibility_top_merchant_view`` table. + competitive_visibility_benchmark_view (google.shopping.merchant_reports_v1beta.types.CompetitiveVisibilityBenchmarkView): + Fields available for query in + ``competitive_visibility_benchmark_view`` table. + """ + + product_performance_view: 'ProductPerformanceView' = proto.Field( + proto.MESSAGE, + number=1, + message='ProductPerformanceView', + ) + non_product_performance_view: 'NonProductPerformanceView' = proto.Field( + proto.MESSAGE, + number=7, + message='NonProductPerformanceView', + ) + product_view: 'ProductView' = proto.Field( + proto.MESSAGE, + number=2, + message='ProductView', + ) + price_competitiveness_product_view: 'PriceCompetitivenessProductView' = proto.Field( + proto.MESSAGE, + number=3, + message='PriceCompetitivenessProductView', + ) + price_insights_product_view: 'PriceInsightsProductView' = proto.Field( + proto.MESSAGE, + number=4, + message='PriceInsightsProductView', + ) + best_sellers_product_cluster_view: 'BestSellersProductClusterView' = proto.Field( + proto.MESSAGE, + number=5, + message='BestSellersProductClusterView', + ) + best_sellers_brand_view: 'BestSellersBrandView' = proto.Field( + proto.MESSAGE, + number=6, + message='BestSellersBrandView', + ) + competitive_visibility_competitor_view: 'CompetitiveVisibilityCompetitorView' = proto.Field( + proto.MESSAGE, + number=8, + message='CompetitiveVisibilityCompetitorView', + ) + competitive_visibility_top_merchant_view: 'CompetitiveVisibilityTopMerchantView' = proto.Field( + proto.MESSAGE, + number=9, + message='CompetitiveVisibilityTopMerchantView', + ) + competitive_visibility_benchmark_view: 'CompetitiveVisibilityBenchmarkView' = proto.Field( + proto.MESSAGE, + number=10, + message='CompetitiveVisibilityBenchmarkView', + ) + + +class ProductPerformanceView(proto.Message): + r"""Fields available for query in ``product_performance_view`` table. + + Product performance data for your account, including performance + metrics (for example, ``clicks``) and dimensions according to which + performance metrics are segmented (for example, ``offer_id``). + Values of product dimensions, such as ``offer_id``, reflect the + state of a product at the time of the impression. + + Segment fields cannot be selected in queries without also selecting + at least one metric field. + + Values are only set for fields requested explicitly in the request's + search query. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + marketing_method (google.shopping.merchant_reports_v1beta.types.MarketingMethod.MarketingMethodEnum): + Marketing method to which metrics apply. + Segment. + + This field is a member of `oneof`_ ``_marketing_method``. + date (google.type.date_pb2.Date): + Date in the merchant timezone to which metrics apply. + Segment. + + Condition on ``date`` is required in the ``WHERE`` clause. + week (google.type.date_pb2.Date): + First day of the week (Monday) of the metrics + date in the merchant timezone. Segment. + customer_country_code (str): + Code of the country where the customer is + located at the time of the event. Represented in + the ISO 3166 format. Segment. + + If the customer country cannot be determined, a + special 'ZZ' code is returned. + + This field is a member of `oneof`_ ``_customer_country_code``. + offer_id (str): + Merchant-provided id of the product. Segment. + + This field is a member of `oneof`_ ``_offer_id``. + title (str): + Title of the product. Segment. + + This field is a member of `oneof`_ ``_title``. + brand (str): + Brand of the product. Segment. + + This field is a member of `oneof`_ ``_brand``. + category_l1 (str): + `Product category (1st + level) `__ + in Google's product taxonomy. Segment. + + This field is a member of `oneof`_ ``_category_l1``. + category_l2 (str): + `Product category (2nd + level) `__ + in Google's product taxonomy. Segment. + + This field is a member of `oneof`_ ``_category_l2``. + category_l3 (str): + `Product category (3rd + level) `__ + in Google's product taxonomy. Segment. + + This field is a member of `oneof`_ ``_category_l3``. + category_l4 (str): + `Product category (4th + level) `__ + in Google's product taxonomy. Segment. + + This field is a member of `oneof`_ ``_category_l4``. + category_l5 (str): + `Product category (5th + level) `__ + in Google's product taxonomy. Segment. + + This field is a member of `oneof`_ ``_category_l5``. + product_type_l1 (str): + `Product type (1st + level) `__ + in merchant's own product taxonomy. Segment. + + This field is a member of `oneof`_ ``_product_type_l1``. + product_type_l2 (str): + `Product type (2nd + level) `__ + in merchant's own product taxonomy. Segment. + + This field is a member of `oneof`_ ``_product_type_l2``. + product_type_l3 (str): + `Product type (3rd + level) `__ + in merchant's own product taxonomy. Segment. + + This field is a member of `oneof`_ ``_product_type_l3``. + product_type_l4 (str): + `Product type (4th + level) `__ + in merchant's own product taxonomy. Segment. + + This field is a member of `oneof`_ ``_product_type_l4``. + product_type_l5 (str): + `Product type (5th + level) `__ + in merchant's own product taxonomy. Segment. + + This field is a member of `oneof`_ ``_product_type_l5``. + custom_label0 (str): + Custom label 0 for custom grouping of + products. Segment. + + This field is a member of `oneof`_ ``_custom_label0``. + custom_label1 (str): + Custom label 1 for custom grouping of + products. Segment. + + This field is a member of `oneof`_ ``_custom_label1``. + custom_label2 (str): + Custom label 2 for custom grouping of + products. Segment. + + This field is a member of `oneof`_ ``_custom_label2``. + custom_label3 (str): + Custom label 3 for custom grouping of + products. Segment. + + This field is a member of `oneof`_ ``_custom_label3``. + custom_label4 (str): + Custom label 4 for custom grouping of + products. Segment. + + This field is a member of `oneof`_ ``_custom_label4``. + clicks (int): + Number of clicks. Metric. + + This field is a member of `oneof`_ ``_clicks``. + impressions (int): + Number of times merchant's products are + shown. Metric. + + This field is a member of `oneof`_ ``_impressions``. + click_through_rate (float): + Click-through rate - the number of clicks + merchant's products receive (clicks) divided by + the number of times the products are shown + (impressions). Metric. + + This field is a member of `oneof`_ ``_click_through_rate``. + conversions (float): + Number of conversions attributed to the product, reported on + the conversion date. Depending on the attribution model, a + conversion might be distributed across multiple clicks, + where each click gets its own credit assigned. This metric + is a sum of all such credits. Metric. + + Available only for the ``FREE`` traffic source. + + This field is a member of `oneof`_ ``_conversions``. + conversion_value (google.shopping.type.types.Price): + Value of conversions attributed to the product, reported on + the conversion date. Metric. + + Available only for the ``FREE`` traffic source. + conversion_rate (float): + Number of conversions divided by the number of clicks, + reported on the impression date. Metric. + + Available only for the ``FREE`` traffic source. + + This field is a member of `oneof`_ ``_conversion_rate``. + """ + + marketing_method: 'MarketingMethod.MarketingMethodEnum' = proto.Field( + proto.ENUM, + number=1, + optional=True, + enum='MarketingMethod.MarketingMethodEnum', + ) + date: date_pb2.Date = proto.Field( + proto.MESSAGE, + number=2, + message=date_pb2.Date, + ) + week: date_pb2.Date = proto.Field( + proto.MESSAGE, + number=3, + message=date_pb2.Date, + ) + customer_country_code: str = proto.Field( + proto.STRING, + number=4, + optional=True, + ) + offer_id: str = proto.Field( + proto.STRING, + number=5, + optional=True, + ) + title: str = proto.Field( + proto.STRING, + number=6, + optional=True, + ) + brand: str = proto.Field( + proto.STRING, + number=7, + optional=True, + ) + category_l1: str = proto.Field( + proto.STRING, + number=8, + optional=True, + ) + category_l2: str = proto.Field( + proto.STRING, + number=9, + optional=True, + ) + category_l3: str = proto.Field( + proto.STRING, + number=10, + optional=True, + ) + category_l4: str = proto.Field( + proto.STRING, + number=11, + optional=True, + ) + category_l5: str = proto.Field( + proto.STRING, + number=12, + optional=True, + ) + product_type_l1: str = proto.Field( + proto.STRING, + number=13, + optional=True, + ) + product_type_l2: str = proto.Field( + proto.STRING, + number=14, + optional=True, + ) + product_type_l3: str = proto.Field( + proto.STRING, + number=15, + optional=True, + ) + product_type_l4: str = proto.Field( + proto.STRING, + number=16, + optional=True, + ) + product_type_l5: str = proto.Field( + proto.STRING, + number=17, + optional=True, + ) + custom_label0: str = proto.Field( + proto.STRING, + number=18, + optional=True, + ) + custom_label1: str = proto.Field( + proto.STRING, + number=19, + optional=True, + ) + custom_label2: str = proto.Field( + proto.STRING, + number=20, + optional=True, + ) + custom_label3: str = proto.Field( + proto.STRING, + number=21, + optional=True, + ) + custom_label4: str = proto.Field( + proto.STRING, + number=22, + optional=True, + ) + clicks: int = proto.Field( + proto.INT64, + number=23, + optional=True, + ) + impressions: int = proto.Field( + proto.INT64, + number=24, + optional=True, + ) + click_through_rate: float = proto.Field( + proto.DOUBLE, + number=25, + optional=True, + ) + conversions: float = proto.Field( + proto.DOUBLE, + number=26, + optional=True, + ) + conversion_value: types.Price = proto.Field( + proto.MESSAGE, + number=27, + message=types.Price, + ) + conversion_rate: float = proto.Field( + proto.DOUBLE, + number=28, + optional=True, + ) + + +class ProductView(proto.Message): + r"""Fields available for query in ``product_view`` table. + + Products in the current inventory. Products in this table are the + same as in Products sub-API but not all product attributes from + Products sub-API are available for query in this table. In contrast + to Products sub-API, this table allows to filter the returned list + of products by product attributes. To retrieve a single product by + ``id`` or list all products, Products sub-API should be used. + + Values are only set for fields requested explicitly in the request's + search query. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + id (str): + REST ID of the product, in the form of + ``channel~languageCode~feedLabel~offerId``. Merchant API + methods that operate on products take this as their ``name`` + parameter. + + Required in the ``SELECT`` clause. + + This field is a member of `oneof`_ ``_id``. + channel (google.shopping.type.types.Channel.ChannelEnum): + Channel of the product. Can be ``ONLINE`` or ``LOCAL``. + + This field is a member of `oneof`_ ``_channel``. + language_code (str): + Language code of the product in BCP 47 + format. + + This field is a member of `oneof`_ ``_language_code``. + feed_label (str): + Feed label of the product. + + This field is a member of `oneof`_ ``_feed_label``. + offer_id (str): + Merchant-provided id of the product. + + This field is a member of `oneof`_ ``_offer_id``. + title (str): + Title of the product. + + This field is a member of `oneof`_ ``_title``. + brand (str): + Brand of the product. + + This field is a member of `oneof`_ ``_brand``. + category_l1 (str): + Product category (1st level) in `Google's product + taxonomy `__. + + This field is a member of `oneof`_ ``_category_l1``. + category_l2 (str): + Product category (2nd level) in `Google's product + taxonomy `__. + + This field is a member of `oneof`_ ``_category_l2``. + category_l3 (str): + Product category (3rd level) in `Google's product + taxonomy `__. + + This field is a member of `oneof`_ ``_category_l3``. + category_l4 (str): + Product category (4th level) in `Google's product + taxonomy `__. + + This field is a member of `oneof`_ ``_category_l4``. + category_l5 (str): + Product category (5th level) in `Google's product + taxonomy `__. + + This field is a member of `oneof`_ ``_category_l5``. + product_type_l1 (str): + Product type (1st level) in merchant's own `product + taxonomy `__. + + This field is a member of `oneof`_ ``_product_type_l1``. + product_type_l2 (str): + Product type (2nd level) in merchant's own `product + taxonomy `__. + + This field is a member of `oneof`_ ``_product_type_l2``. + product_type_l3 (str): + Product type (3rd level) in merchant's own `product + taxonomy `__. + + This field is a member of `oneof`_ ``_product_type_l3``. + product_type_l4 (str): + Product type (4th level) in merchant's own `product + taxonomy `__. + + This field is a member of `oneof`_ ``_product_type_l4``. + product_type_l5 (str): + Product type (5th level) in merchant's own `product + taxonomy `__. + + This field is a member of `oneof`_ ``_product_type_l5``. + price (google.shopping.type.types.Price): + Product price. Absent if the information + about the price of the product is not available. + condition (str): + `Condition `__ + of the product. + + This field is a member of `oneof`_ ``_condition``. + availability (str): + `Availability `__ + of the product. + + This field is a member of `oneof`_ ``_availability``. + shipping_label (str): + Normalized `shipping + label `__ + specified in the data source. + + This field is a member of `oneof`_ ``_shipping_label``. + gtin (MutableSequence[str]): + List of Global Trade Item Numbers (GTINs) of + the product. + item_group_id (str): + Item group id provided by the merchant for + grouping variants together. + + This field is a member of `oneof`_ ``_item_group_id``. + thumbnail_link (str): + Link to the processed image of the product, + hosted on the Google infrastructure. + + This field is a member of `oneof`_ ``_thumbnail_link``. + creation_time (google.protobuf.timestamp_pb2.Timestamp): + The time the merchant created the product in + timestamp seconds. + expiration_date (google.type.date_pb2.Date): + Expiration date for the product, specified on + insertion. + aggregated_reporting_context_status (google.shopping.merchant_reports_v1beta.types.ProductView.AggregatedReportingContextStatus): + Aggregated status. + + This field is a member of `oneof`_ ``_aggregated_reporting_context_status``. + item_issues (MutableSequence[google.shopping.merchant_reports_v1beta.types.ProductView.ItemIssue]): + List of item issues for the product. + + **This field cannot be used for sorting the results.** + + **Only selected attributes of this field (for example, + ``item_issues.severity.aggregated_severity``) can be used + for filtering the results.** + click_potential (google.shopping.merchant_reports_v1beta.types.ProductView.ClickPotential): + Estimated performance potential compared to + highest performing products of the merchant. + click_potential_rank (int): + Rank of the product based on its click potential. A product + with ``click_potential_rank`` 1 has the highest click + potential among the merchant's products that fulfill the + search query conditions. + + This field is a member of `oneof`_ ``_click_potential_rank``. + """ + class AggregatedReportingContextStatus(proto.Enum): + r"""Status of the product aggregated for all reporting contexts. + + Here's an example of how the aggregated status is computed: + + Free listings \| Shopping ads \| Status + --------------|--------------|------------------------------ + Approved \| Approved \| ELIGIBLE Approved \| Pending \| ELIGIBLE + Approved \| Disapproved \| ELIGIBLE_LIMITED Pending \| Pending \| + PENDING Disapproved \| Disapproved \| NOT_ELIGIBLE_OR_DISAPPROVED + + Values: + AGGREGATED_REPORTING_CONTEXT_STATUS_UNSPECIFIED (0): + Not specified. + NOT_ELIGIBLE_OR_DISAPPROVED (1): + Product is not eligible or is disapproved for + all reporting contexts. + PENDING (2): + Product's status is pending in all reporting + contexts. + ELIGIBLE_LIMITED (3): + Product is eligible for some (but not all) + reporting contexts. + ELIGIBLE (4): + Product is eligible for all reporting + contexts. + """ + AGGREGATED_REPORTING_CONTEXT_STATUS_UNSPECIFIED = 0 + NOT_ELIGIBLE_OR_DISAPPROVED = 1 + PENDING = 2 + ELIGIBLE_LIMITED = 3 + ELIGIBLE = 4 + + class ClickPotential(proto.Enum): + r"""A product's `click + potential `__ + estimates its performance potential compared to highest performing + products of the merchant. Click potential of a product helps + merchants to prioritize which products to fix and helps them + understand how products are performing against their potential. + + Values: + CLICK_POTENTIAL_UNSPECIFIED (0): + Unknown predicted clicks impact. + LOW (1): + Potential to receive a low number of clicks + compared to the highest performing products of + the merchant. + MEDIUM (2): + Potential to receive a moderate number of + clicks compared to the highest performing + products of the merchant. + HIGH (3): + Potential to receive a similar number of + clicks as the highest performing products of the + merchant. + """ + CLICK_POTENTIAL_UNSPECIFIED = 0 + LOW = 1 + MEDIUM = 2 + HIGH = 3 + + class ItemIssue(proto.Message): + r"""Item issue associated with the product. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + type_ (google.shopping.merchant_reports_v1beta.types.ProductView.ItemIssue.ItemIssueType): + Item issue type. + severity (google.shopping.merchant_reports_v1beta.types.ProductView.ItemIssue.ItemIssueSeverity): + Item issue severity. + resolution (google.shopping.merchant_reports_v1beta.types.ProductView.ItemIssue.ItemIssueResolution): + Item issue resolution. + + This field is a member of `oneof`_ ``_resolution``. + """ + class ItemIssueResolution(proto.Enum): + r"""How to resolve the issue. + + Values: + ITEM_ISSUE_RESOLUTION_UNSPECIFIED (0): + Not specified. + MERCHANT_ACTION (1): + The merchant has to fix the issue. + PENDING_PROCESSING (2): + The issue will be resolved automatically (for + example, image crawl) or through a Google + review. No merchant action is required now. + Resolution might lead to another issue (for + example, if crawl fails). + """ + ITEM_ISSUE_RESOLUTION_UNSPECIFIED = 0 + MERCHANT_ACTION = 1 + PENDING_PROCESSING = 2 + + class ItemIssueType(proto.Message): + r"""Issue type. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + code (str): + Error code of the issue, equivalent to the ``code`` of + `Product + issues `__. + + This field is a member of `oneof`_ ``_code``. + canonical_attribute (str): + Canonical attribute name for + attribute-specific issues. + + This field is a member of `oneof`_ ``_canonical_attribute``. + """ + + code: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + canonical_attribute: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + + class ItemIssueSeverity(proto.Message): + r"""How the issue affects the serving of the product. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + severity_per_reporting_context (MutableSequence[google.shopping.merchant_reports_v1beta.types.ProductView.ItemIssue.ItemIssueSeverity.IssueSeverityPerReportingContext]): + Issue severity per reporting context. + aggregated_severity (google.shopping.merchant_reports_v1beta.types.ProductView.ItemIssue.ItemIssueSeverity.AggregatedIssueSeverity): + Aggregated severity of the issue for all reporting contexts + it affects. + + **This field can be used for filtering the results.** + + This field is a member of `oneof`_ ``_aggregated_severity``. + """ + class AggregatedIssueSeverity(proto.Enum): + r"""Issue severity aggregated for all reporting contexts. + + Values: + AGGREGATED_ISSUE_SEVERITY_UNSPECIFIED (0): + Not specified. + DISAPPROVED (1): + Issue disapproves the product in at least one + reporting context. + DEMOTED (2): + Issue demotes the product in all reporting + contexts it affects. + PENDING (3): + Issue resolution is ``PENDING_PROCESSING``. + """ + AGGREGATED_ISSUE_SEVERITY_UNSPECIFIED = 0 + DISAPPROVED = 1 + DEMOTED = 2 + PENDING = 3 + + class IssueSeverityPerReportingContext(proto.Message): + r"""Issue severity per reporting context. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + reporting_context (google.shopping.type.types.ReportingContext.ReportingContextEnum): + Reporting context the issue applies to. + + This field is a member of `oneof`_ ``_reporting_context``. + disapproved_countries (MutableSequence[str]): + List of disapproved countries in the + reporting context, represented in ISO 3166 + format. + demoted_countries (MutableSequence[str]): + List of demoted countries in the reporting + context, represented in ISO 3166 format. + """ + + reporting_context: types.ReportingContext.ReportingContextEnum = proto.Field( + proto.ENUM, + number=1, + optional=True, + enum=types.ReportingContext.ReportingContextEnum, + ) + disapproved_countries: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + demoted_countries: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + severity_per_reporting_context: MutableSequence['ProductView.ItemIssue.ItemIssueSeverity.IssueSeverityPerReportingContext'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ProductView.ItemIssue.ItemIssueSeverity.IssueSeverityPerReportingContext', + ) + aggregated_severity: 'ProductView.ItemIssue.ItemIssueSeverity.AggregatedIssueSeverity' = proto.Field( + proto.ENUM, + number=2, + optional=True, + enum='ProductView.ItemIssue.ItemIssueSeverity.AggregatedIssueSeverity', + ) + + type_: 'ProductView.ItemIssue.ItemIssueType' = proto.Field( + proto.MESSAGE, + number=1, + message='ProductView.ItemIssue.ItemIssueType', + ) + severity: 'ProductView.ItemIssue.ItemIssueSeverity' = proto.Field( + proto.MESSAGE, + number=2, + message='ProductView.ItemIssue.ItemIssueSeverity', + ) + resolution: 'ProductView.ItemIssue.ItemIssueResolution' = proto.Field( + proto.ENUM, + number=3, + optional=True, + enum='ProductView.ItemIssue.ItemIssueResolution', + ) + + id: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + channel: types.Channel.ChannelEnum = proto.Field( + proto.ENUM, + number=28, + optional=True, + enum=types.Channel.ChannelEnum, + ) + language_code: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + feed_label: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + offer_id: str = proto.Field( + proto.STRING, + number=4, + optional=True, + ) + title: str = proto.Field( + proto.STRING, + number=5, + optional=True, + ) + brand: str = proto.Field( + proto.STRING, + number=6, + optional=True, + ) + category_l1: str = proto.Field( + proto.STRING, + number=7, + optional=True, + ) + category_l2: str = proto.Field( + proto.STRING, + number=8, + optional=True, + ) + category_l3: str = proto.Field( + proto.STRING, + number=9, + optional=True, + ) + category_l4: str = proto.Field( + proto.STRING, + number=10, + optional=True, + ) + category_l5: str = proto.Field( + proto.STRING, + number=11, + optional=True, + ) + product_type_l1: str = proto.Field( + proto.STRING, + number=12, + optional=True, + ) + product_type_l2: str = proto.Field( + proto.STRING, + number=13, + optional=True, + ) + product_type_l3: str = proto.Field( + proto.STRING, + number=14, + optional=True, + ) + product_type_l4: str = proto.Field( + proto.STRING, + number=15, + optional=True, + ) + product_type_l5: str = proto.Field( + proto.STRING, + number=16, + optional=True, + ) + price: types.Price = proto.Field( + proto.MESSAGE, + number=17, + message=types.Price, + ) + condition: str = proto.Field( + proto.STRING, + number=18, + optional=True, + ) + availability: str = proto.Field( + proto.STRING, + number=19, + optional=True, + ) + shipping_label: str = proto.Field( + proto.STRING, + number=20, + optional=True, + ) + gtin: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=21, + ) + item_group_id: str = proto.Field( + proto.STRING, + number=22, + optional=True, + ) + thumbnail_link: str = proto.Field( + proto.STRING, + number=23, + optional=True, + ) + creation_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=24, + message=timestamp_pb2.Timestamp, + ) + expiration_date: date_pb2.Date = proto.Field( + proto.MESSAGE, + number=25, + message=date_pb2.Date, + ) + aggregated_reporting_context_status: AggregatedReportingContextStatus = proto.Field( + proto.ENUM, + number=26, + optional=True, + enum=AggregatedReportingContextStatus, + ) + item_issues: MutableSequence[ItemIssue] = proto.RepeatedField( + proto.MESSAGE, + number=27, + message=ItemIssue, + ) + click_potential: ClickPotential = proto.Field( + proto.ENUM, + number=29, + enum=ClickPotential, + ) + click_potential_rank: int = proto.Field( + proto.INT64, + number=30, + optional=True, + ) + + +class PriceCompetitivenessProductView(proto.Message): + r"""Fields available for query in ``price_competitiveness_product_view`` + table. + + `Price + competitiveness `__ + report. + + Values are only set for fields requested explicitly in the request's + search query. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + report_country_code (str): + Country of the price benchmark. Represented in the ISO 3166 + format. + + Required in the ``SELECT`` clause. + + This field is a member of `oneof`_ ``_report_country_code``. + id (str): + REST ID of the product, in the form of + ``channel~languageCode~feedLabel~offerId``. Can be used to + join data with the ``product_view`` table. + + Required in the ``SELECT`` clause. + + This field is a member of `oneof`_ ``_id``. + offer_id (str): + Merchant-provided id of the product. + + This field is a member of `oneof`_ ``_offer_id``. + title (str): + Title of the product. + + This field is a member of `oneof`_ ``_title``. + brand (str): + Brand of the product. + + This field is a member of `oneof`_ ``_brand``. + category_l1 (str): + Product category (1st level) in `Google's product + taxonomy `__. + + This field is a member of `oneof`_ ``_category_l1``. + category_l2 (str): + Product category (2nd level) in `Google's product + taxonomy `__. + + This field is a member of `oneof`_ ``_category_l2``. + category_l3 (str): + Product category (3rd level) in `Google's product + taxonomy `__. + + This field is a member of `oneof`_ ``_category_l3``. + category_l4 (str): + Product category (4th level) in `Google's product + taxonomy `__. + + This field is a member of `oneof`_ ``_category_l4``. + category_l5 (str): + Product category (5th level) in `Google's product + taxonomy `__. + + This field is a member of `oneof`_ ``_category_l5``. + product_type_l1 (str): + Product type (1st level) in merchant's own `product + taxonomy `__. + + This field is a member of `oneof`_ ``_product_type_l1``. + product_type_l2 (str): + Product type (2nd level) in merchant's own `product + taxonomy `__. + + This field is a member of `oneof`_ ``_product_type_l2``. + product_type_l3 (str): + Product type (3rd level) in merchant's own `product + taxonomy `__. + + This field is a member of `oneof`_ ``_product_type_l3``. + product_type_l4 (str): + Product type (4th level) in merchant's own `product + taxonomy `__. + + This field is a member of `oneof`_ ``_product_type_l4``. + product_type_l5 (str): + Product type (5th level) in merchant's own `product + taxonomy `__. + + This field is a member of `oneof`_ ``_product_type_l5``. + price (google.shopping.type.types.Price): + Current price of the product. + benchmark_price (google.shopping.type.types.Price): + Latest available price benchmark for the + product's catalog in the benchmark country. + """ + + report_country_code: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + id: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + offer_id: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + title: str = proto.Field( + proto.STRING, + number=4, + optional=True, + ) + brand: str = proto.Field( + proto.STRING, + number=5, + optional=True, + ) + category_l1: str = proto.Field( + proto.STRING, + number=6, + optional=True, + ) + category_l2: str = proto.Field( + proto.STRING, + number=7, + optional=True, + ) + category_l3: str = proto.Field( + proto.STRING, + number=8, + optional=True, + ) + category_l4: str = proto.Field( + proto.STRING, + number=9, + optional=True, + ) + category_l5: str = proto.Field( + proto.STRING, + number=10, + optional=True, + ) + product_type_l1: str = proto.Field( + proto.STRING, + number=11, + optional=True, + ) + product_type_l2: str = proto.Field( + proto.STRING, + number=12, + optional=True, + ) + product_type_l3: str = proto.Field( + proto.STRING, + number=13, + optional=True, + ) + product_type_l4: str = proto.Field( + proto.STRING, + number=14, + optional=True, + ) + product_type_l5: str = proto.Field( + proto.STRING, + number=15, + optional=True, + ) + price: types.Price = proto.Field( + proto.MESSAGE, + number=16, + message=types.Price, + ) + benchmark_price: types.Price = proto.Field( + proto.MESSAGE, + number=17, + message=types.Price, + ) + + +class PriceInsightsProductView(proto.Message): + r"""Fields available for query in ``price_insights_product_view`` table. + + `Price + insights `__ + report. + + Values are only set for fields requested explicitly in the request's + search query. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + id (str): + REST ID of the product, in the form of + ``channel~languageCode~feedLabel~offerId``. Can be used to + join data with the ``product_view`` table. + + Required in the ``SELECT`` clause. + + This field is a member of `oneof`_ ``_id``. + offer_id (str): + Merchant-provided id of the product. + + This field is a member of `oneof`_ ``_offer_id``. + title (str): + Title of the product. + + This field is a member of `oneof`_ ``_title``. + brand (str): + Brand of the product. + + This field is a member of `oneof`_ ``_brand``. + category_l1 (str): + Product category (1st level) in `Google's product + taxonomy `__. + + This field is a member of `oneof`_ ``_category_l1``. + category_l2 (str): + Product category (2nd level) in `Google's product + taxonomy `__. + + This field is a member of `oneof`_ ``_category_l2``. + category_l3 (str): + Product category (3rd level) in `Google's product + taxonomy `__. + + This field is a member of `oneof`_ ``_category_l3``. + category_l4 (str): + Product category (4th level) in `Google's product + taxonomy `__. + + This field is a member of `oneof`_ ``_category_l4``. + category_l5 (str): + Product category (5th level) in `Google's product + taxonomy `__. + + This field is a member of `oneof`_ ``_category_l5``. + product_type_l1 (str): + Product type (1st level) in merchant's own `product + taxonomy `__. + + This field is a member of `oneof`_ ``_product_type_l1``. + product_type_l2 (str): + Product type (2nd level) in merchant's own `product + taxonomy `__. + + This field is a member of `oneof`_ ``_product_type_l2``. + product_type_l3 (str): + Product type (3rd level) in merchant's own `product + taxonomy `__. + + This field is a member of `oneof`_ ``_product_type_l3``. + product_type_l4 (str): + Product type (4th level) in merchant's own `product + taxonomy `__. + + This field is a member of `oneof`_ ``_product_type_l4``. + product_type_l5 (str): + Product type (5th level) in merchant's own `product + taxonomy `__. + + This field is a member of `oneof`_ ``_product_type_l5``. + price (google.shopping.type.types.Price): + Current price of the product. + suggested_price (google.shopping.type.types.Price): + Latest suggested price for the product. + predicted_impressions_change_fraction (float): + Predicted change in impressions as a fraction + after introducing the suggested price compared + to current active price. For example, 0.05 is a + 5% predicted increase in impressions. + + This field is a member of `oneof`_ ``_predicted_impressions_change_fraction``. + predicted_clicks_change_fraction (float): + Predicted change in clicks as a fraction + after introducing the suggested price compared + to current active price. For example, 0.05 is a + 5% predicted increase in clicks. + + This field is a member of `oneof`_ ``_predicted_clicks_change_fraction``. + predicted_conversions_change_fraction (float): + Predicted change in conversions as a fraction + after introducing the suggested price compared + to current active price. For example, 0.05 is a + 5% predicted increase in conversions). + + This field is a member of `oneof`_ ``_predicted_conversions_change_fraction``. + effectiveness (google.shopping.merchant_reports_v1beta.types.PriceInsightsProductView.Effectiveness): + The predicted effectiveness of applying the + price suggestion, bucketed. + """ + class Effectiveness(proto.Enum): + r"""Predicted effectiveness bucket. + + Effectiveness indicates which products would benefit most from price + changes. This rating takes into consideration the performance boost + predicted by adjusting the sale price and the difference between + your current price and the suggested price. Price suggestions with + ``HIGH`` effectiveness are predicted to drive the largest increase + in performance. + + Values: + EFFECTIVENESS_UNSPECIFIED (0): + Effectiveness is unknown. + LOW (1): + Effectiveness is low. + MEDIUM (2): + Effectiveness is medium. + HIGH (3): + Effectiveness is high. + """ + EFFECTIVENESS_UNSPECIFIED = 0 + LOW = 1 + MEDIUM = 2 + HIGH = 3 + + id: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + offer_id: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + title: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + brand: str = proto.Field( + proto.STRING, + number=4, + optional=True, + ) + category_l1: str = proto.Field( + proto.STRING, + number=5, + optional=True, + ) + category_l2: str = proto.Field( + proto.STRING, + number=6, + optional=True, + ) + category_l3: str = proto.Field( + proto.STRING, + number=7, + optional=True, + ) + category_l4: str = proto.Field( + proto.STRING, + number=8, + optional=True, + ) + category_l5: str = proto.Field( + proto.STRING, + number=9, + optional=True, + ) + product_type_l1: str = proto.Field( + proto.STRING, + number=10, + optional=True, + ) + product_type_l2: str = proto.Field( + proto.STRING, + number=11, + optional=True, + ) + product_type_l3: str = proto.Field( + proto.STRING, + number=12, + optional=True, + ) + product_type_l4: str = proto.Field( + proto.STRING, + number=13, + optional=True, + ) + product_type_l5: str = proto.Field( + proto.STRING, + number=14, + optional=True, + ) + price: types.Price = proto.Field( + proto.MESSAGE, + number=15, + message=types.Price, + ) + suggested_price: types.Price = proto.Field( + proto.MESSAGE, + number=16, + message=types.Price, + ) + predicted_impressions_change_fraction: float = proto.Field( + proto.DOUBLE, + number=17, + optional=True, + ) + predicted_clicks_change_fraction: float = proto.Field( + proto.DOUBLE, + number=18, + optional=True, + ) + predicted_conversions_change_fraction: float = proto.Field( + proto.DOUBLE, + number=19, + optional=True, + ) + effectiveness: Effectiveness = proto.Field( + proto.ENUM, + number=22, + enum=Effectiveness, + ) + + +class BestSellersProductClusterView(proto.Message): + r"""Fields available for query in ``best_sellers_product_cluster_view`` + table. + + `Best + sellers `__ + report with top product clusters. A product cluster is a grouping + for different offers and variants that represent the same product, + for example, Google Pixel 7. + + Values are only set for fields requested explicitly in the request's + search query. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + report_date (google.type.date_pb2.Date): + Report date. The value of this field can only be one of the + following: + + - The first day of the week (Monday) for weekly reports, + - The first day of the month for monthly reports. + + Required in the ``SELECT`` clause. If a ``WHERE`` condition + on ``report_date`` is not specified in the query, the latest + available weekly or monthly report is returned. + report_granularity (google.shopping.merchant_reports_v1beta.types.ReportGranularity.ReportGranularityEnum): + Granularity of the report. The ranking can be done over a + week or a month timeframe. + + Required in the ``SELECT`` clause. Condition on + ``report_granularity`` is required in the ``WHERE`` clause. + + This field is a member of `oneof`_ ``_report_granularity``. + report_country_code (str): + Country where the ranking is calculated. Represented in the + ISO 3166 format. + + Required in the ``SELECT`` clause. Condition on + ``report_country_code`` is required in the ``WHERE`` clause. + + This field is a member of `oneof`_ ``_report_country_code``. + report_category_id (int): + Google product category ID to calculate the ranking for, + represented in `Google's product + taxonomy `__. + + Required in the ``SELECT`` clause. If a ``WHERE`` condition + on ``report_category_id`` is not specified in the query, + rankings for all top-level categories are returned. + + This field is a member of `oneof`_ ``_report_category_id``. + title (str): + Title of the product cluster. + + This field is a member of `oneof`_ ``_title``. + brand (str): + Brand of the product cluster. + + This field is a member of `oneof`_ ``_brand``. + category_l1 (str): + Product category (1st level) of the product cluster, + represented in `Google's product + taxonomy `__. + + This field is a member of `oneof`_ ``_category_l1``. + category_l2 (str): + Product category (2nd level) of the product cluster, + represented in `Google's product + taxonomy `__. + + This field is a member of `oneof`_ ``_category_l2``. + category_l3 (str): + Product category (3rd level) of the product cluster, + represented in `Google's product + taxonomy `__. + + This field is a member of `oneof`_ ``_category_l3``. + category_l4 (str): + Product category (4th level) of the product cluster, + represented in `Google's product + taxonomy `__. + + This field is a member of `oneof`_ ``_category_l4``. + category_l5 (str): + Product category (5th level) of the product cluster, + represented in `Google's product + taxonomy `__. + + This field is a member of `oneof`_ ``_category_l5``. + variant_gtins (MutableSequence[str]): + GTINs of example variants of the product + cluster. + inventory_status (google.shopping.merchant_reports_v1beta.types.BestSellersProductClusterView.InventoryStatus): + Whether the product cluster is ``IN_STOCK`` in your product + data source in at least one of the countries, + ``OUT_OF_STOCK`` in your product data source in all + countries, or ``NOT_IN_INVENTORY`` at all. + + The field doesn't take the Best sellers report country + filter into account. + + This field is a member of `oneof`_ ``_inventory_status``. + brand_inventory_status (google.shopping.merchant_reports_v1beta.types.BestSellersProductClusterView.InventoryStatus): + Whether there is at least one product of the brand currently + ``IN_STOCK`` in your product data source in at least one of + the countries, all products are ``OUT_OF_STOCK`` in your + product data source in all countries, or + ``NOT_IN_INVENTORY``. + + The field doesn't take the Best sellers report country + filter into account. + + This field is a member of `oneof`_ ``_brand_inventory_status``. + rank (int): + Popularity of the product cluster on Ads and + organic surfaces, in the selected category and + country, based on the estimated number of units + sold. + + This field is a member of `oneof`_ ``_rank``. + previous_rank (int): + Popularity rank in the previous week or + month. + + This field is a member of `oneof`_ ``_previous_rank``. + relative_demand (google.shopping.merchant_reports_v1beta.types.RelativeDemand.RelativeDemandEnum): + Estimated demand in relation to the product + cluster with the highest popularity rank in the + same category and country. + + This field is a member of `oneof`_ ``_relative_demand``. + previous_relative_demand (google.shopping.merchant_reports_v1beta.types.RelativeDemand.RelativeDemandEnum): + Estimated demand in relation to the product + cluster with the highest popularity rank in the + same category and country in the previous week + or month. + + This field is a member of `oneof`_ ``_previous_relative_demand``. + relative_demand_change (google.shopping.merchant_reports_v1beta.types.RelativeDemandChangeType.RelativeDemandChangeTypeEnum): + Change in the estimated demand. Whether it + rose, sank or remained flat. + + This field is a member of `oneof`_ ``_relative_demand_change``. + """ + class InventoryStatus(proto.Enum): + r"""Status of the product cluster or brand in your inventory. + + Values: + INVENTORY_STATUS_UNSPECIFIED (0): + Not specified. + IN_STOCK (1): + You have a product for this product cluster + or brand in stock. + OUT_OF_STOCK (2): + You have a product for this product cluster + or brand in inventory but it is currently out of + stock. + NOT_IN_INVENTORY (3): + You do not have a product for this product + cluster or brand in inventory. + """ + INVENTORY_STATUS_UNSPECIFIED = 0 + IN_STOCK = 1 + OUT_OF_STOCK = 2 + NOT_IN_INVENTORY = 3 + + report_date: date_pb2.Date = proto.Field( + proto.MESSAGE, + number=1, + message=date_pb2.Date, + ) + report_granularity: 'ReportGranularity.ReportGranularityEnum' = proto.Field( + proto.ENUM, + number=2, + optional=True, + enum='ReportGranularity.ReportGranularityEnum', + ) + report_country_code: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + report_category_id: int = proto.Field( + proto.INT64, + number=4, + optional=True, + ) + title: str = proto.Field( + proto.STRING, + number=6, + optional=True, + ) + brand: str = proto.Field( + proto.STRING, + number=7, + optional=True, + ) + category_l1: str = proto.Field( + proto.STRING, + number=8, + optional=True, + ) + category_l2: str = proto.Field( + proto.STRING, + number=9, + optional=True, + ) + category_l3: str = proto.Field( + proto.STRING, + number=10, + optional=True, + ) + category_l4: str = proto.Field( + proto.STRING, + number=11, + optional=True, + ) + category_l5: str = proto.Field( + proto.STRING, + number=12, + optional=True, + ) + variant_gtins: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=13, + ) + inventory_status: InventoryStatus = proto.Field( + proto.ENUM, + number=14, + optional=True, + enum=InventoryStatus, + ) + brand_inventory_status: InventoryStatus = proto.Field( + proto.ENUM, + number=15, + optional=True, + enum=InventoryStatus, + ) + rank: int = proto.Field( + proto.INT64, + number=16, + optional=True, + ) + previous_rank: int = proto.Field( + proto.INT64, + number=17, + optional=True, + ) + relative_demand: 'RelativeDemand.RelativeDemandEnum' = proto.Field( + proto.ENUM, + number=18, + optional=True, + enum='RelativeDemand.RelativeDemandEnum', + ) + previous_relative_demand: 'RelativeDemand.RelativeDemandEnum' = proto.Field( + proto.ENUM, + number=19, + optional=True, + enum='RelativeDemand.RelativeDemandEnum', + ) + relative_demand_change: 'RelativeDemandChangeType.RelativeDemandChangeTypeEnum' = proto.Field( + proto.ENUM, + number=20, + optional=True, + enum='RelativeDemandChangeType.RelativeDemandChangeTypeEnum', + ) + + +class BestSellersBrandView(proto.Message): + r"""Fields available for query in ``best_sellers_brand_view`` table. + + `Best + sellers `__ + report with top brands. + + Values are only set for fields requested explicitly in the request's + search query. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + report_date (google.type.date_pb2.Date): + Report date. The value of this field can only be one of the + following: + + - The first day of the week (Monday) for weekly reports, + - The first day of the month for monthly reports. + + Required in the ``SELECT`` clause. If a ``WHERE`` condition + on ``report_date`` is not specified in the query, the latest + available weekly or monthly report is returned. + report_granularity (google.shopping.merchant_reports_v1beta.types.ReportGranularity.ReportGranularityEnum): + Granularity of the report. The ranking can be done over a + week or a month timeframe. + + Required in the ``SELECT`` clause. Condition on + ``report_granularity`` is required in the ``WHERE`` clause. + + This field is a member of `oneof`_ ``_report_granularity``. + report_country_code (str): + Country where the ranking is calculated. Represented in the + ISO 3166 format. + + Required in the ``SELECT`` clause. Condition on + ``report_country_code`` is required in the ``WHERE`` clause. + + This field is a member of `oneof`_ ``_report_country_code``. + report_category_id (int): + Google product category ID to calculate the ranking for, + represented in `Google's product + taxonomy `__. + + Required in the ``SELECT`` clause. If a ``WHERE`` condition + on ``report_category_id`` is not specified in the query, + rankings for all top-level categories are returned. + + This field is a member of `oneof`_ ``_report_category_id``. + brand (str): + Name of the brand. + + This field is a member of `oneof`_ ``_brand``. + rank (int): + Popularity of the brand on Ads and organic + surfaces, in the selected category and country, + based on the estimated number of units sold. + + This field is a member of `oneof`_ ``_rank``. + previous_rank (int): + Popularity rank in the previous week or + month. + + This field is a member of `oneof`_ ``_previous_rank``. + relative_demand (google.shopping.merchant_reports_v1beta.types.RelativeDemand.RelativeDemandEnum): + Estimated demand in relation to the brand + with the highest popularity rank in the same + category and country. + + This field is a member of `oneof`_ ``_relative_demand``. + previous_relative_demand (google.shopping.merchant_reports_v1beta.types.RelativeDemand.RelativeDemandEnum): + Estimated demand in relation to the brand + with the highest popularity rank in the same + category and country in the previous week or + month. + + This field is a member of `oneof`_ ``_previous_relative_demand``. + relative_demand_change (google.shopping.merchant_reports_v1beta.types.RelativeDemandChangeType.RelativeDemandChangeTypeEnum): + Change in the estimated demand. Whether it + rose, sank or remained flat. + + This field is a member of `oneof`_ ``_relative_demand_change``. + """ + + report_date: date_pb2.Date = proto.Field( + proto.MESSAGE, + number=1, + message=date_pb2.Date, + ) + report_granularity: 'ReportGranularity.ReportGranularityEnum' = proto.Field( + proto.ENUM, + number=2, + optional=True, + enum='ReportGranularity.ReportGranularityEnum', + ) + report_country_code: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + report_category_id: int = proto.Field( + proto.INT64, + number=4, + optional=True, + ) + brand: str = proto.Field( + proto.STRING, + number=6, + optional=True, + ) + rank: int = proto.Field( + proto.INT64, + number=7, + optional=True, + ) + previous_rank: int = proto.Field( + proto.INT64, + number=8, + optional=True, + ) + relative_demand: 'RelativeDemand.RelativeDemandEnum' = proto.Field( + proto.ENUM, + number=9, + optional=True, + enum='RelativeDemand.RelativeDemandEnum', + ) + previous_relative_demand: 'RelativeDemand.RelativeDemandEnum' = proto.Field( + proto.ENUM, + number=10, + optional=True, + enum='RelativeDemand.RelativeDemandEnum', + ) + relative_demand_change: 'RelativeDemandChangeType.RelativeDemandChangeTypeEnum' = proto.Field( + proto.ENUM, + number=11, + optional=True, + enum='RelativeDemandChangeType.RelativeDemandChangeTypeEnum', + ) + + +class NonProductPerformanceView(proto.Message): + r"""Fields available for query in ``non_product_performance_view`` + table. + + Performance data on images and online store links leading to your + non-product pages. This includes performance metrics (for example, + ``clicks``) and dimensions according to which performance metrics + are segmented (for example, ``date``). + + Segment fields cannot be selected in queries without also selecting + at least one metric field. + + Values are only set for fields requested explicitly in the request's + search query. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + date (google.type.date_pb2.Date): + Date in the merchant timezone to which metrics apply. + Segment. + + Condition on ``date`` is required in the ``WHERE`` clause. + week (google.type.date_pb2.Date): + First day of the week (Monday) of the metrics + date in the merchant timezone. Segment. + clicks (int): + Number of clicks on images and online store + links leading to your non-product pages. Metric. + + This field is a member of `oneof`_ ``_clicks``. + impressions (int): + Number of times images and online store links + leading to your non-product pages were shown. + Metric. + + This field is a member of `oneof`_ ``_impressions``. + click_through_rate (float): + Click-through rate - the number of clicks (``clicks``) + divided by the number of impressions (``impressions``) of + images and online store links leading to your non-product + pages. Metric. + + This field is a member of `oneof`_ ``_click_through_rate``. + """ + + date: date_pb2.Date = proto.Field( + proto.MESSAGE, + number=1, + message=date_pb2.Date, + ) + week: date_pb2.Date = proto.Field( + proto.MESSAGE, + number=2, + message=date_pb2.Date, + ) + clicks: int = proto.Field( + proto.INT64, + number=3, + optional=True, + ) + impressions: int = proto.Field( + proto.INT64, + number=4, + optional=True, + ) + click_through_rate: float = proto.Field( + proto.DOUBLE, + number=5, + optional=True, + ) + + +class CompetitiveVisibilityCompetitorView(proto.Message): + r"""Fields available for query in + ``competitive_visibility_competitor_view`` table. + + `Competitive + visibility `__ + report with businesses with similar visibility. + + Values are only set for fields requested explicitly in the request's + search query. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + date (google.type.date_pb2.Date): + Date of this row. + + A condition on ``date`` is required in the ``WHERE`` clause. + domain (str): + Domain of your competitor or your domain, if + 'is_your_domain' is true. + + Required in the ``SELECT`` clause. Cannot be filtered on in + the 'WHERE' clause. + + This field is a member of `oneof`_ ``_domain``. + is_your_domain (bool): + True if this row contains data for your + domain. + Cannot be filtered on in the 'WHERE' clause. + + This field is a member of `oneof`_ ``_is_your_domain``. + report_country_code (str): + Country where impressions appeared. + + Required in the ``SELECT`` clause. A condition on + ``report_country_code`` is required in the ``WHERE`` clause. + + This field is a member of `oneof`_ ``_report_country_code``. + report_category_id (int): + Google product category ID to calculate the report for, + represented in `Google's product + taxonomy `__. + + Required in the ``SELECT`` clause. A condition on + ``report_category_id`` is required in the ``WHERE`` clause. + + This field is a member of `oneof`_ ``_report_category_id``. + traffic_source (google.shopping.merchant_reports_v1beta.types.TrafficSource.TrafficSourceEnum): + Traffic source of impressions. + + Required in the ``SELECT`` clause. + + This field is a member of `oneof`_ ``_traffic_source``. + rank (int): + Position of the domain in the similar businesses ranking for + the selected keys (``date``, ``report_category_id``, + ``report_country_code``, ``traffic_source``) based on + impressions. 1 is the highest. + + Cannot be filtered on in the 'WHERE' clause. + + This field is a member of `oneof`_ ``_rank``. + ads_organic_ratio (float): + [Ads / organic ratio] + (https://support.google.com/merchants/answer/11366442#zippy=%2Cads-free-ratio) + shows how often the domain receives impressions from + Shopping ads compared to organic traffic. The number is + rounded and bucketed. + + Cannot be filtered on in the 'WHERE' clause. + + This field is a member of `oneof`_ ``_ads_organic_ratio``. + page_overlap_rate (float): + [Page overlap rate] + (https://support.google.com/merchants/answer/11366442#zippy=%2Cpage-overlap-rate) + shows how frequently competing retailers’ offers are shown + together with your offers on the same page. + + Cannot be filtered on in the 'WHERE' clause. + + This field is a member of `oneof`_ ``_page_overlap_rate``. + higher_position_rate (float): + [Higher position rate] + (https://support.google.com/merchants/answer/11366442#zippy=%2Chigher-position-rate) + shows how often a competitor’s offer got placed in a higher + position on the page than your offer. + + Cannot be filtered on in the 'WHERE' clause. + + This field is a member of `oneof`_ ``_higher_position_rate``. + relative_visibility (float): + [Relative visibility] + (https://support.google.com/merchants/answer/11366442#zippy=%2Crelative-visibility) + shows how often your competitors’ offers are shown compared + to your offers. In other words, this is the number of + displayed impressions of a competitor retailer divided by + the number of your displayed impressions during a selected + time range for a selected product category and country. + + Cannot be filtered on in the 'WHERE' clause. + + This field is a member of `oneof`_ ``_relative_visibility``. + """ + + date: date_pb2.Date = proto.Field( + proto.MESSAGE, + number=1, + message=date_pb2.Date, + ) + domain: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + is_your_domain: bool = proto.Field( + proto.BOOL, + number=3, + optional=True, + ) + report_country_code: str = proto.Field( + proto.STRING, + number=4, + optional=True, + ) + report_category_id: int = proto.Field( + proto.INT64, + number=5, + optional=True, + ) + traffic_source: 'TrafficSource.TrafficSourceEnum' = proto.Field( + proto.ENUM, + number=6, + optional=True, + enum='TrafficSource.TrafficSourceEnum', + ) + rank: int = proto.Field( + proto.INT64, + number=7, + optional=True, + ) + ads_organic_ratio: float = proto.Field( + proto.DOUBLE, + number=8, + optional=True, + ) + page_overlap_rate: float = proto.Field( + proto.DOUBLE, + number=9, + optional=True, + ) + higher_position_rate: float = proto.Field( + proto.DOUBLE, + number=10, + optional=True, + ) + relative_visibility: float = proto.Field( + proto.DOUBLE, + number=11, + optional=True, + ) + + +class CompetitiveVisibilityTopMerchantView(proto.Message): + r"""Fields available for query in + ``competitive_visibility_top_merchant_view`` table. + + `Competitive + visibility `__ + report with business with highest visibility. + + Values are only set for fields requested explicitly in the request's + search query. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + date (google.type.date_pb2.Date): + Date of this row. + + Cannot be selected in the ``SELECT`` clause. A condition on + ``date`` is required in the ``WHERE`` clause. + domain (str): + Domain of your competitor or your domain, if + 'is_your_domain' is true. + + Required in the ``SELECT`` clause. Cannot be filtered on in + the 'WHERE' clause. + + This field is a member of `oneof`_ ``_domain``. + is_your_domain (bool): + True if this row contains data for your + domain. + Cannot be filtered on in the 'WHERE' clause. + + This field is a member of `oneof`_ ``_is_your_domain``. + report_country_code (str): + Country where impressions appeared. + + Required in the ``SELECT`` clause. A condition on + ``report_country_code`` is required in the ``WHERE`` clause. + + This field is a member of `oneof`_ ``_report_country_code``. + report_category_id (int): + Google product category ID to calculate the report for, + represented in `Google's product + taxonomy `__. + + Required in the ``SELECT`` clause. A condition on + ``report_category_id`` is required in the ``WHERE`` clause. + + This field is a member of `oneof`_ ``_report_category_id``. + traffic_source (google.shopping.merchant_reports_v1beta.types.TrafficSource.TrafficSourceEnum): + Traffic source of impressions. + + Required in the ``SELECT`` clause. + + This field is a member of `oneof`_ ``_traffic_source``. + rank (int): + Position of the domain in the top merchants ranking for the + selected keys (``date``, ``report_category_id``, + ``report_country_code``, ``traffic_source``) based on + impressions. 1 is the highest. + + Cannot be filtered on in the 'WHERE' clause. + + This field is a member of `oneof`_ ``_rank``. + ads_organic_ratio (float): + [Ads / organic ratio] + (https://support.google.com/merchants/answer/11366442#zippy=%2Cads-free-ratio) + shows how often the domain receives impressions from + Shopping ads compared to organic traffic. The number is + rounded and bucketed. + + Cannot be filtered on in the 'WHERE' clause. + + This field is a member of `oneof`_ ``_ads_organic_ratio``. + page_overlap_rate (float): + [Page overlap rate] + (https://support.google.com/merchants/answer/11366442#zippy=%2Cpage-overlap-rate) + shows how frequently competing retailers’ offers are shown + together with your offers on the same page. + + Cannot be filtered on in the 'WHERE' clause. + + This field is a member of `oneof`_ ``_page_overlap_rate``. + higher_position_rate (float): + [Higher position rate] + (https://support.google.com/merchants/answer/11366442#zippy=%2Chigher-position-rate) + shows how often a competitor’s offer got placed in a higher + position on the page than your offer. + + Cannot be filtered on in the 'WHERE' clause. + + This field is a member of `oneof`_ ``_higher_position_rate``. + """ + + date: date_pb2.Date = proto.Field( + proto.MESSAGE, + number=1, + message=date_pb2.Date, + ) + domain: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + is_your_domain: bool = proto.Field( + proto.BOOL, + number=3, + optional=True, + ) + report_country_code: str = proto.Field( + proto.STRING, + number=4, + optional=True, + ) + report_category_id: int = proto.Field( + proto.INT64, + number=5, + optional=True, + ) + traffic_source: 'TrafficSource.TrafficSourceEnum' = proto.Field( + proto.ENUM, + number=6, + optional=True, + enum='TrafficSource.TrafficSourceEnum', + ) + rank: int = proto.Field( + proto.INT64, + number=7, + optional=True, + ) + ads_organic_ratio: float = proto.Field( + proto.DOUBLE, + number=8, + optional=True, + ) + page_overlap_rate: float = proto.Field( + proto.DOUBLE, + number=9, + optional=True, + ) + higher_position_rate: float = proto.Field( + proto.DOUBLE, + number=10, + optional=True, + ) + + +class CompetitiveVisibilityBenchmarkView(proto.Message): + r"""Fields available for query in + ``competitive_visibility_benchmark_view`` table. + + `Competitive + visibility `__ + report with the category benchmark. + + Values are only set for fields requested explicitly in the request's + search query. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + date (google.type.date_pb2.Date): + Date of this row. + + Required in the ``SELECT`` clause. A condition on ``date`` + is required in the ``WHERE`` clause. + report_country_code (str): + Country where impressions appeared. + + Required in the ``SELECT`` clause. A condition on + ``report_country_code`` is required in the ``WHERE`` clause. + + This field is a member of `oneof`_ ``_report_country_code``. + report_category_id (int): + Google product category ID to calculate the report for, + represented in `Google's product + taxonomy `__. + + Required in the ``SELECT`` clause. A condition on + ``report_category_id`` is required in the ``WHERE`` clause. + + This field is a member of `oneof`_ ``_report_category_id``. + traffic_source (google.shopping.merchant_reports_v1beta.types.TrafficSource.TrafficSourceEnum): + Traffic source of impressions. + + Required in the ``SELECT`` clause. + + This field is a member of `oneof`_ ``_traffic_source``. + your_domain_visibility_trend (float): + Change in visibility based on impressions for + your domain with respect to the start of the + selected time range (or first day with non-zero + impressions). + + Cannot be filtered on in the 'WHERE' clause. + + This field is a member of `oneof`_ ``_your_domain_visibility_trend``. + category_benchmark_visibility_trend (float): + Change in visibility based on impressions + with respect to the start of the selected time + range (or first day with non-zero impressions) + for a combined set of merchants with highest + visibility approximating the market. + + Cannot be filtered on in the 'WHERE' clause. + + This field is a member of `oneof`_ ``_category_benchmark_visibility_trend``. + """ + + date: date_pb2.Date = proto.Field( + proto.MESSAGE, + number=1, + message=date_pb2.Date, + ) + report_country_code: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + report_category_id: int = proto.Field( + proto.INT64, + number=3, + optional=True, + ) + traffic_source: 'TrafficSource.TrafficSourceEnum' = proto.Field( + proto.ENUM, + number=4, + optional=True, + enum='TrafficSource.TrafficSourceEnum', + ) + your_domain_visibility_trend: float = proto.Field( + proto.DOUBLE, + number=5, + optional=True, + ) + category_benchmark_visibility_trend: float = proto.Field( + proto.DOUBLE, + number=6, + optional=True, + ) + + +class MarketingMethod(proto.Message): + r"""Marketing method used to promote your products on Google + (organic versus ads). + + """ + class MarketingMethodEnum(proto.Enum): + r"""Marketing method values. + + Values: + MARKETING_METHOD_ENUM_UNSPECIFIED (0): + Not specified. + ORGANIC (1): + Organic marketing. + ADS (2): + Ads-based marketing. + """ + MARKETING_METHOD_ENUM_UNSPECIFIED = 0 + ORGANIC = 1 + ADS = 2 + + +class ReportGranularity(proto.Message): + r"""Granularity of the Best sellers report. Best sellers reports + are computed over a week and a month timeframe. + + """ + class ReportGranularityEnum(proto.Enum): + r"""Report granularity values. + + Values: + REPORT_GRANULARITY_ENUM_UNSPECIFIED (0): + Not specified. + WEEKLY (1): + Report is computed over a week timeframe. + MONTHLY (2): + Report is computed over a month timeframe. + """ + REPORT_GRANULARITY_ENUM_UNSPECIFIED = 0 + WEEKLY = 1 + MONTHLY = 2 + + +class RelativeDemand(proto.Message): + r"""Relative demand of a product cluster or brand in the Best + sellers report. + + """ + class RelativeDemandEnum(proto.Enum): + r"""Relative demand values. + + Values: + RELATIVE_DEMAND_ENUM_UNSPECIFIED (0): + Not specified. + VERY_LOW (10): + Demand is 0-5% of the demand of the highest + ranked product cluster or brand. + LOW (20): + Demand is 6-10% of the demand of the highest + ranked product cluster or brand. + MEDIUM (30): + Demand is 11-20% of the demand of the highest + ranked product cluster or brand. + HIGH (40): + Demand is 21-50% of the demand of the highest + ranked product cluster or brand. + VERY_HIGH (50): + Demand is 51-100% of the demand of the + highest ranked product cluster or brand. + """ + RELATIVE_DEMAND_ENUM_UNSPECIFIED = 0 + VERY_LOW = 10 + LOW = 20 + MEDIUM = 30 + HIGH = 40 + VERY_HIGH = 50 + + +class RelativeDemandChangeType(proto.Message): + r"""Relative demand of a product cluster or brand in the Best + sellers report compared to the previous time period. + + """ + class RelativeDemandChangeTypeEnum(proto.Enum): + r"""Relative demand change type values. + + Values: + RELATIVE_DEMAND_CHANGE_TYPE_ENUM_UNSPECIFIED (0): + Not specified. + SINKER (1): + Relative demand is lower than the previous + time period. + FLAT (2): + Relative demand is equal to the previous time + period. + RISER (3): + Relative demand is higher than the previous + time period. + """ + RELATIVE_DEMAND_CHANGE_TYPE_ENUM_UNSPECIFIED = 0 + SINKER = 1 + FLAT = 2 + RISER = 3 + + +class TrafficSource(proto.Message): + r"""Traffic source of impressions in the Competitive visibility + report. + + """ + class TrafficSourceEnum(proto.Enum): + r"""Traffic source values. + + Values: + TRAFFIC_SOURCE_ENUM_UNSPECIFIED (0): + Not specified. + ORGANIC (1): + Organic traffic. + ADS (2): + Traffic from ads. + ALL (3): + Organic and ads traffic. + """ + TRAFFIC_SOURCE_ENUM_UNSPECIFIED = 0 + ORGANIC = 1 + ADS = 2 + ALL = 3 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/mypy.ini b/owl-bot-staging/google-shopping-merchant-reports/v1beta/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/v1beta/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/noxfile.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/noxfile.py new file mode 100644 index 000000000000..da7084b1cfb2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/v1beta/noxfile.py @@ -0,0 +1,280 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = 'google-shopping-merchant-reports' + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.13" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "prerelease_deps", +] + +@nox.session(python=ALL_PYTHON) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def unit(session, protobuf_implementation): + """Run the unit test suite.""" + + 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+") + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") + + # 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") + + session.run( + 'py.test', + '--quiet', + '--cov=google/shopping/merchant_reports_v1beta/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)), + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + +@nox.session(python=ALL_PYTHON[-1]) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def prerelease_deps(session, protobuf_implementation): + """Run the unit test suite against pre-release versions of dependencies.""" + + 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 test environment dependencies + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + + # Install the package without dependencies + session.install('-e', '.', '--no-deps') + + # We test the minimum dependency versions using the minimum Python + # version so the lowest python runtime that we test has a corresponding constraints + # file, located at `testing/constraints--.txt`, which contains all of the + # 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 + ) + ] + + session.install(*constraints_deps) + + prerel_deps = [ + "googleapis-common-protos", + "google-api-core", + "google-auth", + # Exclude grpcio!=1.67.0rc1 which does not support python 3.13 + "grpcio!=1.67.0rc1", + "grpcio-status", + "protobuf", + "proto-plus", + ] + + for dep in prerel_deps: + session.install("--pre", "--no-deps", "--upgrade", dep) + + # Remaining dependencies + other_deps = [ + "requests", + ] + session.install(*other_deps) + + # Print out prerelease package versions + + session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") + session.run("python", "-c", "import google.auth; print(google.auth.__version__)") + session.run("python", "-c", "import grpc; print(grpc.__version__)") + session.run( + "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" + ) + session.run( + "python", "-c", "import proto; print(proto.__version__)" + ) + + session.run( + 'py.test', + '--quiet', + '--cov=google/shopping/merchant_reports_v1beta/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)), + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + + +@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=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 docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==7.0.1", "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=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", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/samples/generated_samples/merchantapi_v1beta_generated_report_service_search_async.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/samples/generated_samples/merchantapi_v1beta_generated_report_service_search_async.py new file mode 100644 index 000000000000..6fa9200b9512 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/v1beta/samples/generated_samples/merchantapi_v1beta_generated_report_service_search_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Search +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-reports + + +# [START merchantapi_v1beta_generated_ReportService_Search_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_reports_v1beta + + +async def sample_search(): + # Create a client + client = merchant_reports_v1beta.ReportServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_reports_v1beta.SearchRequest( + parent="parent_value", + query="query_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_ReportService_Search_async] diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/samples/generated_samples/merchantapi_v1beta_generated_report_service_search_sync.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/samples/generated_samples/merchantapi_v1beta_generated_report_service_search_sync.py new file mode 100644 index 000000000000..11f591230812 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/v1beta/samples/generated_samples/merchantapi_v1beta_generated_report_service_search_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Search +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-reports + + +# [START merchantapi_v1beta_generated_ReportService_Search_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_reports_v1beta + + +def sample_search(): + # Create a client + client = merchant_reports_v1beta.ReportServiceClient() + + # Initialize request argument(s) + request = merchant_reports_v1beta.SearchRequest( + parent="parent_value", + query="query_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_ReportService_Search_sync] diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.reports.v1beta.json b/owl-bot-staging/google-shopping-merchant-reports/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.reports.v1beta.json new file mode 100644 index 000000000000..145fa5b7eb46 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.reports.v1beta.json @@ -0,0 +1,176 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.shopping.merchant.reports.v1beta", + "version": "v1beta" + } + ], + "language": "PYTHON", + "name": "google-shopping-merchant-reports", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_reports_v1beta.ReportServiceAsyncClient", + "shortName": "ReportServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_reports_v1beta.ReportServiceAsyncClient.search", + "method": { + "fullName": "google.shopping.merchant.reports.v1beta.ReportService.Search", + "service": { + "fullName": "google.shopping.merchant.reports.v1beta.ReportService", + "shortName": "ReportService" + }, + "shortName": "Search" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_reports_v1beta.types.SearchRequest" + }, + { + "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_reports_v1beta.services.report_service.pagers.SearchAsyncPager", + "shortName": "search" + }, + "description": "Sample for Search", + "file": "merchantapi_v1beta_generated_report_service_search_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_ReportService_Search_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "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": 54, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_report_service_search_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_reports_v1beta.ReportServiceClient", + "shortName": "ReportServiceClient" + }, + "fullName": "google.shopping.merchant_reports_v1beta.ReportServiceClient.search", + "method": { + "fullName": "google.shopping.merchant.reports.v1beta.ReportService.Search", + "service": { + "fullName": "google.shopping.merchant.reports.v1beta.ReportService", + "shortName": "ReportService" + }, + "shortName": "Search" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_reports_v1beta.types.SearchRequest" + }, + { + "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_reports_v1beta.services.report_service.pagers.SearchPager", + "shortName": "search" + }, + "description": "Sample for Search", + "file": "merchantapi_v1beta_generated_report_service_search_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_ReportService_Search_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "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": 54, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_report_service_search_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/scripts/fixup_merchant_reports_v1beta_keywords.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/scripts/fixup_merchant_reports_v1beta_keywords.py new file mode 100644 index 000000000000..83db92c96848 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/v1beta/scripts/fixup_merchant_reports_v1beta_keywords.py @@ -0,0 +1,176 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_reportsCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'search': ('parent', 'query', 'page_size', 'page_token', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=merchant_reportsCallTransformer(), +): + """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_reports 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-reports/v1beta/setup.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/setup.py new file mode 100644 index 000000000000..434b659ca76d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/v1beta/setup.py @@ -0,0 +1,99 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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-reports' + + +description = "Google Shopping Merchant Reports API client library" + +version = None + +with open(os.path.join(package_root, 'google/shopping/merchant_reports/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.0dev,!=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.0dev,!=2.24.0,!=2.25.0", + "proto-plus >= 1.22.3, <2.0.0dev", + "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'", + "protobuf>=3.20.2,<6.0.0dev,!=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.0dev", +] +extras = { +} +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-reports" + +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-reports/v1beta/testing/constraints-3.10.txt b/owl-bot-staging/google-shopping-merchant-reports/v1beta/testing/constraints-3.10.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/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-reports/v1beta/testing/constraints-3.11.txt b/owl-bot-staging/google-shopping-merchant-reports/v1beta/testing/constraints-3.11.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/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-reports/v1beta/testing/constraints-3.12.txt b/owl-bot-staging/google-shopping-merchant-reports/v1beta/testing/constraints-3.12.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/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-reports/v1beta/testing/constraints-3.13.txt b/owl-bot-staging/google-shopping-merchant-reports/v1beta/testing/constraints-3.13.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/v1beta/testing/constraints-3.13.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-reports/v1beta/testing/constraints-3.7.txt b/owl-bot-staging/google-shopping-merchant-reports/v1beta/testing/constraints-3.7.txt new file mode 100644 index 000000000000..130a0c0f80ab --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/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.0dev", +# 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-reports/v1beta/testing/constraints-3.8.txt b/owl-bot-staging/google-shopping-merchant-reports/v1beta/testing/constraints-3.8.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/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-reports/v1beta/testing/constraints-3.9.txt b/owl-bot-staging/google-shopping-merchant-reports/v1beta/testing/constraints-3.9.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/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-reports/v1beta/tests/__init__.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/v1beta/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-reports/v1beta/tests/unit/__init__.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/v1beta/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-reports/v1beta/tests/unit/gapic/__init__.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/v1beta/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-reports/v1beta/tests/unit/gapic/merchant_reports_v1beta/__init__.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/tests/unit/gapic/merchant_reports_v1beta/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/v1beta/tests/unit/gapic/merchant_reports_v1beta/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-reports/v1beta/tests/unit/gapic/merchant_reports_v1beta/test_report_service.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/tests/unit/gapic/merchant_reports_v1beta/test_report_service.py new file mode 100644 index 000000000000..8d6c1d186125 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-reports/v1beta/tests/unit/gapic/merchant_reports_v1beta/test_report_service.py @@ -0,0 +1,2333 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_reports_v1beta.services.report_service import ReportServiceAsyncClient +from google.shopping.merchant_reports_v1beta.services.report_service import ReportServiceClient +from google.shopping.merchant_reports_v1beta.services.report_service import pagers +from google.shopping.merchant_reports_v1beta.services.report_service import transports +from google.shopping.merchant_reports_v1beta.types import reports +import google.auth + + +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 ReportServiceClient._get_default_mtls_endpoint(None) is None + assert ReportServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ReportServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ReportServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ReportServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ReportServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert ReportServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert ReportServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert ReportServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + ReportServiceClient._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 ReportServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert ReportServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert ReportServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + ReportServiceClient._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 ReportServiceClient._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 ReportServiceClient._get_client_cert_source(None, False) is None + assert ReportServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert ReportServiceClient._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 ReportServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert ReportServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(ReportServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReportServiceClient)) +@mock.patch.object(ReportServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReportServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = ReportServiceClient._DEFAULT_UNIVERSE + default_endpoint = ReportServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = ReportServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert ReportServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert ReportServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == ReportServiceClient.DEFAULT_MTLS_ENDPOINT + assert ReportServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert ReportServiceClient._get_api_endpoint(None, None, default_universe, "always") == ReportServiceClient.DEFAULT_MTLS_ENDPOINT + assert ReportServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == ReportServiceClient.DEFAULT_MTLS_ENDPOINT + assert ReportServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert ReportServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + ReportServiceClient._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 ReportServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert ReportServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert ReportServiceClient._get_universe_domain(None, None) == ReportServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + ReportServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize("client_class,transport_name", [ + (ReportServiceClient, "grpc"), + (ReportServiceAsyncClient, "grpc_asyncio"), + (ReportServiceClient, "rest"), +]) +def test_report_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.ReportServiceGrpcTransport, "grpc"), + (transports.ReportServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.ReportServiceRestTransport, "rest"), +]) +def test_report_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", [ + (ReportServiceClient, "grpc"), + (ReportServiceAsyncClient, "grpc_asyncio"), + (ReportServiceClient, "rest"), +]) +def test_report_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_report_service_client_get_transport_class(): + transport = ReportServiceClient.get_transport_class() + available_transports = [ + transports.ReportServiceGrpcTransport, + transports.ReportServiceRestTransport, + ] + assert transport in available_transports + + transport = ReportServiceClient.get_transport_class("grpc") + assert transport == transports.ReportServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ReportServiceClient, transports.ReportServiceGrpcTransport, "grpc"), + (ReportServiceAsyncClient, transports.ReportServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (ReportServiceClient, transports.ReportServiceRestTransport, "rest"), +]) +@mock.patch.object(ReportServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReportServiceClient)) +@mock.patch.object(ReportServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReportServiceAsyncClient)) +def test_report_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(ReportServiceClient, '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(ReportServiceClient, '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", [ + (ReportServiceClient, transports.ReportServiceGrpcTransport, "grpc", "true"), + (ReportServiceAsyncClient, transports.ReportServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ReportServiceClient, transports.ReportServiceGrpcTransport, "grpc", "false"), + (ReportServiceAsyncClient, transports.ReportServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (ReportServiceClient, transports.ReportServiceRestTransport, "rest", "true"), + (ReportServiceClient, transports.ReportServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(ReportServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReportServiceClient)) +@mock.patch.object(ReportServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReportServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_report_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", [ + ReportServiceClient, ReportServiceAsyncClient +]) +@mock.patch.object(ReportServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ReportServiceClient)) +@mock.patch.object(ReportServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ReportServiceAsyncClient)) +def test_report_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", [ + ReportServiceClient, ReportServiceAsyncClient +]) +@mock.patch.object(ReportServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReportServiceClient)) +@mock.patch.object(ReportServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReportServiceAsyncClient)) +def test_report_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = ReportServiceClient._DEFAULT_UNIVERSE + default_endpoint = ReportServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = ReportServiceClient._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", [ + (ReportServiceClient, transports.ReportServiceGrpcTransport, "grpc"), + (ReportServiceAsyncClient, transports.ReportServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (ReportServiceClient, transports.ReportServiceRestTransport, "rest"), +]) +def test_report_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", [ + (ReportServiceClient, transports.ReportServiceGrpcTransport, "grpc", grpc_helpers), + (ReportServiceAsyncClient, transports.ReportServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (ReportServiceClient, transports.ReportServiceRestTransport, "rest", None), +]) +def test_report_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_report_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_reports_v1beta.services.report_service.transports.ReportServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ReportServiceClient( + 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", [ + (ReportServiceClient, transports.ReportServiceGrpcTransport, "grpc", grpc_helpers), + (ReportServiceAsyncClient, transports.ReportServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_report_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", [ + reports.SearchRequest, + dict, +]) +def test_search(request_type, transport: str = 'grpc'): + client = ReportServiceClient( + 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.search), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = reports.SearchResponse( + next_page_token='next_page_token_value', + ) + response = client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = reports.SearchRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_search_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 = ReportServiceClient( + 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 = reports.SearchRequest( + parent='parent_value', + query='query_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.search), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.search(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == reports.SearchRequest( + parent='parent_value', + query='query_value', + page_token='page_token_value', + ) + +def test_search_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ReportServiceClient( + 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.search in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.search] = mock_rpc + request = {} + client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.search(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_search_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = ReportServiceAsyncClient( + 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.search in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.search] = mock_rpc + + request = {} + await client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.search(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_search_async(transport: str = 'grpc_asyncio', request_type=reports.SearchRequest): + client = ReportServiceAsyncClient( + 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.search), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(reports.SearchResponse( + next_page_token='next_page_token_value', + )) + response = await client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = reports.SearchRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_search_async_from_dict(): + await test_search_async(request_type=dict) + +def test_search_field_headers(): + client = ReportServiceClient( + 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 = reports.SearchRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + call.return_value = reports.SearchResponse() + client.search(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_search_field_headers_async(): + client = ReportServiceAsyncClient( + 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 = reports.SearchRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(reports.SearchResponse()) + await client.search(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_search_flattened(): + client = ReportServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = reports.SearchResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.search( + 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_search_flattened_error(): + client = ReportServiceClient( + 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.search( + reports.SearchRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_search_flattened_async(): + client = ReportServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = reports.SearchResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(reports.SearchResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.search( + 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_search_flattened_error_async(): + client = ReportServiceAsyncClient( + 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.search( + reports.SearchRequest(), + parent='parent_value', + ) + + +def test_search_pager(transport_name: str = "grpc"): + client = ReportServiceClient( + 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.search), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + reports.SearchResponse( + results=[ + reports.ReportRow(), + reports.ReportRow(), + reports.ReportRow(), + ], + next_page_token='abc', + ), + reports.SearchResponse( + results=[], + next_page_token='def', + ), + reports.SearchResponse( + results=[ + reports.ReportRow(), + ], + next_page_token='ghi', + ), + reports.SearchResponse( + results=[ + reports.ReportRow(), + reports.ReportRow(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.search(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, reports.ReportRow) + for i in results) +def test_search_pages(transport_name: str = "grpc"): + client = ReportServiceClient( + 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.search), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + reports.SearchResponse( + results=[ + reports.ReportRow(), + reports.ReportRow(), + reports.ReportRow(), + ], + next_page_token='abc', + ), + reports.SearchResponse( + results=[], + next_page_token='def', + ), + reports.SearchResponse( + results=[ + reports.ReportRow(), + ], + next_page_token='ghi', + ), + reports.SearchResponse( + results=[ + reports.ReportRow(), + reports.ReportRow(), + ], + ), + RuntimeError, + ) + pages = list(client.search(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_search_async_pager(): + client = ReportServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + reports.SearchResponse( + results=[ + reports.ReportRow(), + reports.ReportRow(), + reports.ReportRow(), + ], + next_page_token='abc', + ), + reports.SearchResponse( + results=[], + next_page_token='def', + ), + reports.SearchResponse( + results=[ + reports.ReportRow(), + ], + next_page_token='ghi', + ), + reports.SearchResponse( + results=[ + reports.ReportRow(), + reports.ReportRow(), + ], + ), + RuntimeError, + ) + async_pager = await client.search(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, reports.ReportRow) + for i in responses) + + +@pytest.mark.asyncio +async def test_search_async_pages(): + client = ReportServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + reports.SearchResponse( + results=[ + reports.ReportRow(), + reports.ReportRow(), + reports.ReportRow(), + ], + next_page_token='abc', + ), + reports.SearchResponse( + results=[], + next_page_token='def', + ), + reports.SearchResponse( + results=[ + reports.ReportRow(), + ], + next_page_token='ghi', + ), + reports.SearchResponse( + results=[ + reports.ReportRow(), + reports.ReportRow(), + ], + ), + 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.search(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_search_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 = ReportServiceClient( + 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.search in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.search] = mock_rpc + + request = {} + client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.search(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_search_rest_required_fields(request_type=reports.SearchRequest): + transport_class = transports.ReportServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["query"] = "" + request = 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()).search._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["query"] = 'query_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).search._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 "query" in jsonified_request + assert jsonified_request["query"] == 'query_value' + + client = ReportServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = reports.SearchResponse() + # 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 = reports.SearchResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.search(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_search_rest_unset_required_fields(): + transport = transports.ReportServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.search._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "query", ))) + + +def test_search_rest_flattened(): + client = ReportServiceClient( + 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 = reports.SearchResponse() + + # 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 = reports.SearchResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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.search(**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/reports/v1beta/{parent=accounts/*}/reports:search" % client.transport._host, args[1]) + + +def test_search_rest_flattened_error(transport: str = 'rest'): + client = ReportServiceClient( + 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.search( + reports.SearchRequest(), + parent='parent_value', + ) + + +def test_search_rest_pager(transport: str = 'rest'): + client = ReportServiceClient( + 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 = ( + reports.SearchResponse( + results=[ + reports.ReportRow(), + reports.ReportRow(), + reports.ReportRow(), + ], + next_page_token='abc', + ), + reports.SearchResponse( + results=[], + next_page_token='def', + ), + reports.SearchResponse( + results=[ + reports.ReportRow(), + ], + next_page_token='ghi', + ), + reports.SearchResponse( + results=[ + reports.ReportRow(), + reports.ReportRow(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(reports.SearchResponse.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.search(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, reports.ReportRow) + for i in results) + + pages = list(client.search(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.ReportServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ReportServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ReportServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ReportServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ReportServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ReportServiceClient( + 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 = ReportServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ReportServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ReportServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ReportServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ReportServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ReportServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ReportServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ReportServiceGrpcTransport, + transports.ReportServiceGrpcAsyncIOTransport, + transports.ReportServiceRestTransport, +]) +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 = ReportServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = ReportServiceClient( + 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_search_empty_call_grpc(): + client = ReportServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + call.return_value = reports.SearchResponse() + client.search(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reports.SearchRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = ReportServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = ReportServiceAsyncClient( + 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_search_empty_call_grpc_asyncio(): + client = ReportServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(reports.SearchResponse( + next_page_token='next_page_token_value', + )) + await client.search(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reports.SearchRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = ReportServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_search_rest_bad_request(request_type=reports.SearchRequest): + client = ReportServiceClient( + 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.search(request) + + +@pytest.mark.parametrize("request_type", [ + reports.SearchRequest, + dict, +]) +def test_search_rest_call_success(request_type): + client = ReportServiceClient( + 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 = reports.SearchResponse( + 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 = reports.SearchResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.search(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_search_rest_interceptors(null_interceptor): + transport = transports.ReportServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ReportServiceRestInterceptor(), + ) + client = ReportServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ReportServiceRestInterceptor, "post_search") as post, \ + mock.patch.object(transports.ReportServiceRestInterceptor, "pre_search") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = reports.SearchRequest.pb(reports.SearchRequest()) + 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 = reports.SearchResponse.to_json(reports.SearchResponse()) + req.return_value.content = return_value + + request = reports.SearchRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = reports.SearchResponse() + + client.search(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + +def test_initialize_client_w_rest(): + client = ReportServiceClient( + 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_search_empty_call_rest(): + client = ReportServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + client.search(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reports.SearchRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = ReportServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ReportServiceGrpcTransport, + ) + +def test_report_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ReportServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_report_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_reports_v1beta.services.report_service.transports.ReportServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ReportServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'search', + ) + 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_report_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_reports_v1beta.services.report_service.transports.ReportServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ReportServiceTransport( + 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_report_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_reports_v1beta.services.report_service.transports.ReportServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ReportServiceTransport() + adc.assert_called_once() + + +def test_report_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) + ReportServiceClient() + 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.ReportServiceGrpcTransport, + transports.ReportServiceGrpcAsyncIOTransport, + ], +) +def test_report_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.ReportServiceGrpcTransport, + transports.ReportServiceGrpcAsyncIOTransport, + transports.ReportServiceRestTransport, + ], +) +def test_report_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.ReportServiceGrpcTransport, grpc_helpers), + (transports.ReportServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_report_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.ReportServiceGrpcTransport, transports.ReportServiceGrpcAsyncIOTransport]) +def test_report_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_report_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.ReportServiceRestTransport ( + 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_report_service_host_no_port(transport_name): + client = ReportServiceClient( + 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_report_service_host_with_port(transport_name): + client = ReportServiceClient( + 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_report_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = ReportServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = ReportServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.search._session + session2 = client2.transport.search._session + assert session1 != session2 +def test_report_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ReportServiceGrpcTransport( + 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_report_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ReportServiceGrpcAsyncIOTransport( + 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.ReportServiceGrpcTransport, transports.ReportServiceGrpcAsyncIOTransport]) +def test_report_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.ReportServiceGrpcTransport, transports.ReportServiceGrpcAsyncIOTransport]) +def test_report_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_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ReportServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = ReportServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ReportServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = ReportServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = ReportServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ReportServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ReportServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = ReportServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ReportServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = ReportServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = ReportServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ReportServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = ReportServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = ReportServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ReportServiceClient.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.ReportServiceTransport, '_prep_wrapped_messages') as prep: + client = ReportServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ReportServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = ReportServiceClient.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 = ReportServiceClient( + 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 = ReportServiceAsyncClient( + 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 = ReportServiceClient( + 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 = ReportServiceClient( + 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", [ + (ReportServiceClient, transports.ReportServiceGrpcTransport), + (ReportServiceAsyncClient, transports.ReportServiceGrpcAsyncIOTransport), +]) +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/grafeas/v1/.coveragerc b/owl-bot-staging/grafeas/v1/.coveragerc new file mode 100644 index 000000000000..4e55acc51c44 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + grafeas/grafeas/__init__.py + grafeas/grafeas/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/grafeas/v1/.flake8 b/owl-bot-staging/grafeas/v1/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/grafeas/v1/MANIFEST.in b/owl-bot-staging/grafeas/v1/MANIFEST.in new file mode 100644 index 000000000000..075904e53516 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include grafeas/grafeas *.py +recursive-include grafeas/grafeas_v1 *.py diff --git a/owl-bot-staging/grafeas/v1/README.rst b/owl-bot-staging/grafeas/v1/README.rst new file mode 100644 index 000000000000..0f879492ca1d --- /dev/null +++ b/owl-bot-staging/grafeas/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Grafeas Grafeas 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 Grafeas Grafeas 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 diff --git a/owl-bot-staging/grafeas/v1/docs/_static/custom.css b/owl-bot-staging/grafeas/v1/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/grafeas/v1/docs/conf.py b/owl-bot-staging/grafeas/v1/docs/conf.py new file mode 100644 index 000000000000..e43817cf2e74 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# grafeas 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("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# 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.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +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"grafeas" +copyright = u"2023, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# 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 = 'en' + +# 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"] + +# 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": "Grafeas Client Libraries for Python", + "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 = "grafeas-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, + "grafeas.tex", + u"grafeas 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, + "grafeas", + u"Grafeas Grafeas 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, + "grafeas", + u"grafeas Documentation", + author, + "grafeas", + "GAPIC library for Grafeas Grafeas API", + "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": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", 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/grafeas/v1/docs/grafeas_v1/grafeas.rst b/owl-bot-staging/grafeas/v1/docs/grafeas_v1/grafeas.rst new file mode 100644 index 000000000000..7339fabecaee --- /dev/null +++ b/owl-bot-staging/grafeas/v1/docs/grafeas_v1/grafeas.rst @@ -0,0 +1,10 @@ +Grafeas +------------------------- + +.. automodule:: grafeas.grafeas_v1.services.grafeas + :members: + :inherited-members: + +.. automodule:: grafeas.grafeas_v1.services.grafeas.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/grafeas/v1/docs/grafeas_v1/services_.rst b/owl-bot-staging/grafeas/v1/docs/grafeas_v1/services_.rst new file mode 100644 index 000000000000..ca38222018ff --- /dev/null +++ b/owl-bot-staging/grafeas/v1/docs/grafeas_v1/services_.rst @@ -0,0 +1,6 @@ +Services for Grafeas Grafeas v1 API +=================================== +.. toctree:: + :maxdepth: 2 + + grafeas diff --git a/owl-bot-staging/grafeas/v1/docs/grafeas_v1/types_.rst b/owl-bot-staging/grafeas/v1/docs/grafeas_v1/types_.rst new file mode 100644 index 000000000000..5808795e6eb1 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/docs/grafeas_v1/types_.rst @@ -0,0 +1,6 @@ +Types for Grafeas Grafeas v1 API +================================ + +.. automodule:: grafeas.grafeas_v1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/grafeas/v1/docs/index.rst b/owl-bot-staging/grafeas/v1/docs/index.rst new file mode 100644 index 000000000000..35750509477c --- /dev/null +++ b/owl-bot-staging/grafeas/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + grafeas_v1/services_ + grafeas_v1/types_ diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas/__init__.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas/__init__.py new file mode 100644 index 000000000000..f2282fa0cc79 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/grafeas/grafeas/__init__.py @@ -0,0 +1,211 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from grafeas.grafeas import gapic_version as package_version + +__version__ = package_version.__version__ + + +from grafeas.grafeas_v1.services.grafeas.client import GrafeasClient +from grafeas.grafeas_v1.services.grafeas.async_client import GrafeasAsyncClient + +from grafeas.grafeas_v1.types.attestation import AttestationNote +from grafeas.grafeas_v1.types.attestation import AttestationOccurrence +from grafeas.grafeas_v1.types.attestation import Jwt +from grafeas.grafeas_v1.types.build import BuildNote +from grafeas.grafeas_v1.types.build import BuildOccurrence +from grafeas.grafeas_v1.types.common import Digest +from grafeas.grafeas_v1.types.common import Envelope +from grafeas.grafeas_v1.types.common import EnvelopeSignature +from grafeas.grafeas_v1.types.common import FileLocation +from grafeas.grafeas_v1.types.common import License +from grafeas.grafeas_v1.types.common import RelatedUrl +from grafeas.grafeas_v1.types.common import Signature +from grafeas.grafeas_v1.types.common import NoteKind +from grafeas.grafeas_v1.types.compliance import ComplianceNote +from grafeas.grafeas_v1.types.compliance import ComplianceOccurrence +from grafeas.grafeas_v1.types.compliance import ComplianceVersion +from grafeas.grafeas_v1.types.compliance import NonCompliantFile +from grafeas.grafeas_v1.types.cvss import CVSS +from grafeas.grafeas_v1.types.cvss import CVSSv3 +from grafeas.grafeas_v1.types.cvss import CVSSVersion +from grafeas.grafeas_v1.types.deployment import DeploymentNote +from grafeas.grafeas_v1.types.deployment import DeploymentOccurrence +from grafeas.grafeas_v1.types.discovery import DiscoveryNote +from grafeas.grafeas_v1.types.discovery import DiscoveryOccurrence +from grafeas.grafeas_v1.types.dsse_attestation import DSSEAttestationNote +from grafeas.grafeas_v1.types.dsse_attestation import DSSEAttestationOccurrence +from grafeas.grafeas_v1.types.grafeas import BatchCreateNotesRequest +from grafeas.grafeas_v1.types.grafeas import BatchCreateNotesResponse +from grafeas.grafeas_v1.types.grafeas import BatchCreateOccurrencesRequest +from grafeas.grafeas_v1.types.grafeas import BatchCreateOccurrencesResponse +from grafeas.grafeas_v1.types.grafeas import CreateNoteRequest +from grafeas.grafeas_v1.types.grafeas import CreateOccurrenceRequest +from grafeas.grafeas_v1.types.grafeas import DeleteNoteRequest +from grafeas.grafeas_v1.types.grafeas import DeleteOccurrenceRequest +from grafeas.grafeas_v1.types.grafeas import GetNoteRequest +from grafeas.grafeas_v1.types.grafeas import GetOccurrenceNoteRequest +from grafeas.grafeas_v1.types.grafeas import GetOccurrenceRequest +from grafeas.grafeas_v1.types.grafeas import ListNoteOccurrencesRequest +from grafeas.grafeas_v1.types.grafeas import ListNoteOccurrencesResponse +from grafeas.grafeas_v1.types.grafeas import ListNotesRequest +from grafeas.grafeas_v1.types.grafeas import ListNotesResponse +from grafeas.grafeas_v1.types.grafeas import ListOccurrencesRequest +from grafeas.grafeas_v1.types.grafeas import ListOccurrencesResponse +from grafeas.grafeas_v1.types.grafeas import Note +from grafeas.grafeas_v1.types.grafeas import Occurrence +from grafeas.grafeas_v1.types.grafeas import UpdateNoteRequest +from grafeas.grafeas_v1.types.grafeas import UpdateOccurrenceRequest +from grafeas.grafeas_v1.types.image import Fingerprint +from grafeas.grafeas_v1.types.image import ImageNote +from grafeas.grafeas_v1.types.image import ImageOccurrence +from grafeas.grafeas_v1.types.image import Layer +from grafeas.grafeas_v1.types.intoto_provenance import BuilderConfig +from grafeas.grafeas_v1.types.intoto_provenance import Completeness +from grafeas.grafeas_v1.types.intoto_provenance import InTotoProvenance +from grafeas.grafeas_v1.types.intoto_provenance import Metadata +from grafeas.grafeas_v1.types.intoto_provenance import Recipe +from grafeas.grafeas_v1.types.intoto_statement import InTotoSlsaProvenanceV1 +from grafeas.grafeas_v1.types.intoto_statement import InTotoStatement +from grafeas.grafeas_v1.types.intoto_statement import Subject +from grafeas.grafeas_v1.types.package import Distribution +from grafeas.grafeas_v1.types.package import Location +from grafeas.grafeas_v1.types.package import PackageNote +from grafeas.grafeas_v1.types.package import PackageOccurrence +from grafeas.grafeas_v1.types.package import Version +from grafeas.grafeas_v1.types.package import Architecture +from grafeas.grafeas_v1.types.provenance import AliasContext +from grafeas.grafeas_v1.types.provenance import Artifact +from grafeas.grafeas_v1.types.provenance import BuildProvenance +from grafeas.grafeas_v1.types.provenance import CloudRepoSourceContext +from grafeas.grafeas_v1.types.provenance import Command +from grafeas.grafeas_v1.types.provenance import FileHashes +from grafeas.grafeas_v1.types.provenance import GerritSourceContext +from grafeas.grafeas_v1.types.provenance import GitSourceContext +from grafeas.grafeas_v1.types.provenance import Hash +from grafeas.grafeas_v1.types.provenance import ProjectRepoId +from grafeas.grafeas_v1.types.provenance import RepoId +from grafeas.grafeas_v1.types.provenance import Source +from grafeas.grafeas_v1.types.provenance import SourceContext +from grafeas.grafeas_v1.types.sbom import SbomReferenceIntotoPayload +from grafeas.grafeas_v1.types.sbom import SbomReferenceIntotoPredicate +from grafeas.grafeas_v1.types.sbom import SBOMReferenceNote +from grafeas.grafeas_v1.types.sbom import SBOMReferenceOccurrence +from grafeas.grafeas_v1.types.severity import Severity +from grafeas.grafeas_v1.types.slsa_provenance import SlsaProvenance +from grafeas.grafeas_v1.types.slsa_provenance_zero_two import SlsaProvenanceZeroTwo +from grafeas.grafeas_v1.types.upgrade import UpgradeDistribution +from grafeas.grafeas_v1.types.upgrade import UpgradeNote +from grafeas.grafeas_v1.types.upgrade import UpgradeOccurrence +from grafeas.grafeas_v1.types.upgrade import WindowsUpdate +from grafeas.grafeas_v1.types.vex import VulnerabilityAssessmentNote +from grafeas.grafeas_v1.types.vulnerability import VulnerabilityNote +from grafeas.grafeas_v1.types.vulnerability import VulnerabilityOccurrence + +__all__ = ('GrafeasClient', + 'GrafeasAsyncClient', + 'AttestationNote', + 'AttestationOccurrence', + 'Jwt', + 'BuildNote', + 'BuildOccurrence', + 'Digest', + 'Envelope', + 'EnvelopeSignature', + 'FileLocation', + 'License', + 'RelatedUrl', + 'Signature', + 'NoteKind', + 'ComplianceNote', + 'ComplianceOccurrence', + 'ComplianceVersion', + 'NonCompliantFile', + 'CVSS', + 'CVSSv3', + 'CVSSVersion', + 'DeploymentNote', + 'DeploymentOccurrence', + 'DiscoveryNote', + 'DiscoveryOccurrence', + 'DSSEAttestationNote', + 'DSSEAttestationOccurrence', + 'BatchCreateNotesRequest', + 'BatchCreateNotesResponse', + 'BatchCreateOccurrencesRequest', + 'BatchCreateOccurrencesResponse', + 'CreateNoteRequest', + 'CreateOccurrenceRequest', + 'DeleteNoteRequest', + 'DeleteOccurrenceRequest', + 'GetNoteRequest', + 'GetOccurrenceNoteRequest', + 'GetOccurrenceRequest', + 'ListNoteOccurrencesRequest', + 'ListNoteOccurrencesResponse', + 'ListNotesRequest', + 'ListNotesResponse', + 'ListOccurrencesRequest', + 'ListOccurrencesResponse', + 'Note', + 'Occurrence', + 'UpdateNoteRequest', + 'UpdateOccurrenceRequest', + 'Fingerprint', + 'ImageNote', + 'ImageOccurrence', + 'Layer', + 'BuilderConfig', + 'Completeness', + 'InTotoProvenance', + 'Metadata', + 'Recipe', + 'InTotoSlsaProvenanceV1', + 'InTotoStatement', + 'Subject', + 'Distribution', + 'Location', + 'PackageNote', + 'PackageOccurrence', + 'Version', + 'Architecture', + 'AliasContext', + 'Artifact', + 'BuildProvenance', + 'CloudRepoSourceContext', + 'Command', + 'FileHashes', + 'GerritSourceContext', + 'GitSourceContext', + 'Hash', + 'ProjectRepoId', + 'RepoId', + 'Source', + 'SourceContext', + 'SbomReferenceIntotoPayload', + 'SbomReferenceIntotoPredicate', + 'SBOMReferenceNote', + 'SBOMReferenceOccurrence', + 'Severity', + 'SlsaProvenance', + 'SlsaProvenanceZeroTwo', + 'UpgradeDistribution', + 'UpgradeNote', + 'UpgradeOccurrence', + 'WindowsUpdate', + 'VulnerabilityAssessmentNote', + 'VulnerabilityNote', + 'VulnerabilityOccurrence', +) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas/gapic_version.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/grafeas/grafeas/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/grafeas/v1/grafeas/grafeas/py.typed b/owl-bot-staging/grafeas/v1/grafeas/grafeas/py.typed new file mode 100644 index 000000000000..49e8f71d60b7 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/grafeas/grafeas/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The grafeas package uses inline types. diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/__init__.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/__init__.py new file mode 100644 index 000000000000..7a4f4fa690fd --- /dev/null +++ b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/__init__.py @@ -0,0 +1,212 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from grafeas.grafeas_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.grafeas import GrafeasClient +from .services.grafeas import GrafeasAsyncClient + +from .types.attestation import AttestationNote +from .types.attestation import AttestationOccurrence +from .types.attestation import Jwt +from .types.build import BuildNote +from .types.build import BuildOccurrence +from .types.common import Digest +from .types.common import Envelope +from .types.common import EnvelopeSignature +from .types.common import FileLocation +from .types.common import License +from .types.common import RelatedUrl +from .types.common import Signature +from .types.common import NoteKind +from .types.compliance import ComplianceNote +from .types.compliance import ComplianceOccurrence +from .types.compliance import ComplianceVersion +from .types.compliance import NonCompliantFile +from .types.cvss import CVSS +from .types.cvss import CVSSv3 +from .types.cvss import CVSSVersion +from .types.deployment import DeploymentNote +from .types.deployment import DeploymentOccurrence +from .types.discovery import DiscoveryNote +from .types.discovery import DiscoveryOccurrence +from .types.dsse_attestation import DSSEAttestationNote +from .types.dsse_attestation import DSSEAttestationOccurrence +from .types.grafeas import BatchCreateNotesRequest +from .types.grafeas import BatchCreateNotesResponse +from .types.grafeas import BatchCreateOccurrencesRequest +from .types.grafeas import BatchCreateOccurrencesResponse +from .types.grafeas import CreateNoteRequest +from .types.grafeas import CreateOccurrenceRequest +from .types.grafeas import DeleteNoteRequest +from .types.grafeas import DeleteOccurrenceRequest +from .types.grafeas import GetNoteRequest +from .types.grafeas import GetOccurrenceNoteRequest +from .types.grafeas import GetOccurrenceRequest +from .types.grafeas import ListNoteOccurrencesRequest +from .types.grafeas import ListNoteOccurrencesResponse +from .types.grafeas import ListNotesRequest +from .types.grafeas import ListNotesResponse +from .types.grafeas import ListOccurrencesRequest +from .types.grafeas import ListOccurrencesResponse +from .types.grafeas import Note +from .types.grafeas import Occurrence +from .types.grafeas import UpdateNoteRequest +from .types.grafeas import UpdateOccurrenceRequest +from .types.image import Fingerprint +from .types.image import ImageNote +from .types.image import ImageOccurrence +from .types.image import Layer +from .types.intoto_provenance import BuilderConfig +from .types.intoto_provenance import Completeness +from .types.intoto_provenance import InTotoProvenance +from .types.intoto_provenance import Metadata +from .types.intoto_provenance import Recipe +from .types.intoto_statement import InTotoSlsaProvenanceV1 +from .types.intoto_statement import InTotoStatement +from .types.intoto_statement import Subject +from .types.package import Distribution +from .types.package import Location +from .types.package import PackageNote +from .types.package import PackageOccurrence +from .types.package import Version +from .types.package import Architecture +from .types.provenance import AliasContext +from .types.provenance import Artifact +from .types.provenance import BuildProvenance +from .types.provenance import CloudRepoSourceContext +from .types.provenance import Command +from .types.provenance import FileHashes +from .types.provenance import GerritSourceContext +from .types.provenance import GitSourceContext +from .types.provenance import Hash +from .types.provenance import ProjectRepoId +from .types.provenance import RepoId +from .types.provenance import Source +from .types.provenance import SourceContext +from .types.sbom import SbomReferenceIntotoPayload +from .types.sbom import SbomReferenceIntotoPredicate +from .types.sbom import SBOMReferenceNote +from .types.sbom import SBOMReferenceOccurrence +from .types.severity import Severity +from .types.slsa_provenance import SlsaProvenance +from .types.slsa_provenance_zero_two import SlsaProvenanceZeroTwo +from .types.upgrade import UpgradeDistribution +from .types.upgrade import UpgradeNote +from .types.upgrade import UpgradeOccurrence +from .types.upgrade import WindowsUpdate +from .types.vex import VulnerabilityAssessmentNote +from .types.vulnerability import VulnerabilityNote +from .types.vulnerability import VulnerabilityOccurrence + +__all__ = ( + 'GrafeasAsyncClient', +'AliasContext', +'Architecture', +'Artifact', +'AttestationNote', +'AttestationOccurrence', +'BatchCreateNotesRequest', +'BatchCreateNotesResponse', +'BatchCreateOccurrencesRequest', +'BatchCreateOccurrencesResponse', +'BuildNote', +'BuildOccurrence', +'BuildProvenance', +'BuilderConfig', +'CVSS', +'CVSSVersion', +'CVSSv3', +'CloudRepoSourceContext', +'Command', +'Completeness', +'ComplianceNote', +'ComplianceOccurrence', +'ComplianceVersion', +'CreateNoteRequest', +'CreateOccurrenceRequest', +'DSSEAttestationNote', +'DSSEAttestationOccurrence', +'DeleteNoteRequest', +'DeleteOccurrenceRequest', +'DeploymentNote', +'DeploymentOccurrence', +'Digest', +'DiscoveryNote', +'DiscoveryOccurrence', +'Distribution', +'Envelope', +'EnvelopeSignature', +'FileHashes', +'FileLocation', +'Fingerprint', +'GerritSourceContext', +'GetNoteRequest', +'GetOccurrenceNoteRequest', +'GetOccurrenceRequest', +'GitSourceContext', +'GrafeasClient', +'Hash', +'ImageNote', +'ImageOccurrence', +'InTotoProvenance', +'InTotoSlsaProvenanceV1', +'InTotoStatement', +'Jwt', +'Layer', +'License', +'ListNoteOccurrencesRequest', +'ListNoteOccurrencesResponse', +'ListNotesRequest', +'ListNotesResponse', +'ListOccurrencesRequest', +'ListOccurrencesResponse', +'Location', +'Metadata', +'NonCompliantFile', +'Note', +'NoteKind', +'Occurrence', +'PackageNote', +'PackageOccurrence', +'ProjectRepoId', +'Recipe', +'RelatedUrl', +'RepoId', +'SBOMReferenceNote', +'SBOMReferenceOccurrence', +'SbomReferenceIntotoPayload', +'SbomReferenceIntotoPredicate', +'Severity', +'Signature', +'SlsaProvenance', +'SlsaProvenanceZeroTwo', +'Source', +'SourceContext', +'Subject', +'UpdateNoteRequest', +'UpdateOccurrenceRequest', +'UpgradeDistribution', +'UpgradeNote', +'UpgradeOccurrence', +'Version', +'VulnerabilityAssessmentNote', +'VulnerabilityNote', +'VulnerabilityOccurrence', +'WindowsUpdate', +) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/gapic_metadata.json b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/gapic_metadata.json new file mode 100644 index 000000000000..ec505dda48a9 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/gapic_metadata.json @@ -0,0 +1,238 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "grafeas.grafeas_v1", + "protoPackage": "grafeas.v1", + "schema": "1.0", + "services": { + "Grafeas": { + "clients": { + "grpc": { + "libraryClient": "GrafeasClient", + "rpcs": { + "BatchCreateNotes": { + "methods": [ + "batch_create_notes" + ] + }, + "BatchCreateOccurrences": { + "methods": [ + "batch_create_occurrences" + ] + }, + "CreateNote": { + "methods": [ + "create_note" + ] + }, + "CreateOccurrence": { + "methods": [ + "create_occurrence" + ] + }, + "DeleteNote": { + "methods": [ + "delete_note" + ] + }, + "DeleteOccurrence": { + "methods": [ + "delete_occurrence" + ] + }, + "GetNote": { + "methods": [ + "get_note" + ] + }, + "GetOccurrence": { + "methods": [ + "get_occurrence" + ] + }, + "GetOccurrenceNote": { + "methods": [ + "get_occurrence_note" + ] + }, + "ListNoteOccurrences": { + "methods": [ + "list_note_occurrences" + ] + }, + "ListNotes": { + "methods": [ + "list_notes" + ] + }, + "ListOccurrences": { + "methods": [ + "list_occurrences" + ] + }, + "UpdateNote": { + "methods": [ + "update_note" + ] + }, + "UpdateOccurrence": { + "methods": [ + "update_occurrence" + ] + } + } + }, + "grpc-async": { + "libraryClient": "GrafeasAsyncClient", + "rpcs": { + "BatchCreateNotes": { + "methods": [ + "batch_create_notes" + ] + }, + "BatchCreateOccurrences": { + "methods": [ + "batch_create_occurrences" + ] + }, + "CreateNote": { + "methods": [ + "create_note" + ] + }, + "CreateOccurrence": { + "methods": [ + "create_occurrence" + ] + }, + "DeleteNote": { + "methods": [ + "delete_note" + ] + }, + "DeleteOccurrence": { + "methods": [ + "delete_occurrence" + ] + }, + "GetNote": { + "methods": [ + "get_note" + ] + }, + "GetOccurrence": { + "methods": [ + "get_occurrence" + ] + }, + "GetOccurrenceNote": { + "methods": [ + "get_occurrence_note" + ] + }, + "ListNoteOccurrences": { + "methods": [ + "list_note_occurrences" + ] + }, + "ListNotes": { + "methods": [ + "list_notes" + ] + }, + "ListOccurrences": { + "methods": [ + "list_occurrences" + ] + }, + "UpdateNote": { + "methods": [ + "update_note" + ] + }, + "UpdateOccurrence": { + "methods": [ + "update_occurrence" + ] + } + } + }, + "rest": { + "libraryClient": "GrafeasClient", + "rpcs": { + "BatchCreateNotes": { + "methods": [ + "batch_create_notes" + ] + }, + "BatchCreateOccurrences": { + "methods": [ + "batch_create_occurrences" + ] + }, + "CreateNote": { + "methods": [ + "create_note" + ] + }, + "CreateOccurrence": { + "methods": [ + "create_occurrence" + ] + }, + "DeleteNote": { + "methods": [ + "delete_note" + ] + }, + "DeleteOccurrence": { + "methods": [ + "delete_occurrence" + ] + }, + "GetNote": { + "methods": [ + "get_note" + ] + }, + "GetOccurrence": { + "methods": [ + "get_occurrence" + ] + }, + "GetOccurrenceNote": { + "methods": [ + "get_occurrence_note" + ] + }, + "ListNoteOccurrences": { + "methods": [ + "list_note_occurrences" + ] + }, + "ListNotes": { + "methods": [ + "list_notes" + ] + }, + "ListOccurrences": { + "methods": [ + "list_occurrences" + ] + }, + "UpdateNote": { + "methods": [ + "update_note" + ] + }, + "UpdateOccurrence": { + "methods": [ + "update_occurrence" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/gapic_version.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/grafeas/v1/grafeas/grafeas_v1/py.typed b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/py.typed new file mode 100644 index 000000000000..49e8f71d60b7 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The grafeas package uses inline types. diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/__init__.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/grafeas/v1/grafeas/grafeas_v1/services/grafeas/__init__.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/__init__.py new file mode 100644 index 000000000000..b1d682230d78 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 GrafeasClient +from .async_client import GrafeasAsyncClient + +__all__ = ( + 'GrafeasClient', + 'GrafeasAsyncClient', +) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/async_client.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/async_client.py new file mode 100644 index 000000000000..764b1ddf1932 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/async_client.py @@ -0,0 +1,1886 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 grafeas.grafeas_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 + + +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 timestamp_pb2 # type: ignore +from grafeas.grafeas_v1.services.grafeas import pagers +from grafeas.grafeas_v1.types import attestation +from grafeas.grafeas_v1.types import build +from grafeas.grafeas_v1.types import common +from grafeas.grafeas_v1.types import compliance +from grafeas.grafeas_v1.types import deployment +from grafeas.grafeas_v1.types import discovery +from grafeas.grafeas_v1.types import dsse_attestation +from grafeas.grafeas_v1.types import grafeas +from grafeas.grafeas_v1.types import image +from grafeas.grafeas_v1.types import package +from grafeas.grafeas_v1.types import sbom +from grafeas.grafeas_v1.types import upgrade +from grafeas.grafeas_v1.types import vex +from grafeas.grafeas_v1.types import vulnerability +from .transports.base import GrafeasTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import GrafeasGrpcAsyncIOTransport +from .client import GrafeasClient + +try: + from google.api_core import client_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 GrafeasAsyncClient: + """`Grafeas `__ API. + + Retrieves analysis results of Cloud components such as Docker + container images. + + Analysis results are stored as a series of occurrences. An + ``Occurrence`` contains information about a specific analysis + instance on a resource. An occurrence refers to a ``Note``. A note + contains details describing the analysis and is generally stored in + a separate project, called a ``Provider``. Multiple occurrences can + refer to the same note. + + For example, an SSL vulnerability could affect multiple images. In + this case, there would be one note for the vulnerability and an + occurrence for each image with the vulnerability referring to that + note. + """ + + _client: GrafeasClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = GrafeasClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = GrafeasClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = GrafeasClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = GrafeasClient._DEFAULT_UNIVERSE + + note_path = staticmethod(GrafeasClient.note_path) + parse_note_path = staticmethod(GrafeasClient.parse_note_path) + occurrence_path = staticmethod(GrafeasClient.occurrence_path) + parse_occurrence_path = staticmethod(GrafeasClient.parse_occurrence_path) + project_path = staticmethod(GrafeasClient.project_path) + parse_project_path = staticmethod(GrafeasClient.parse_project_path) + common_billing_account_path = staticmethod(GrafeasClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(GrafeasClient.parse_common_billing_account_path) + common_folder_path = staticmethod(GrafeasClient.common_folder_path) + parse_common_folder_path = staticmethod(GrafeasClient.parse_common_folder_path) + common_organization_path = staticmethod(GrafeasClient.common_organization_path) + parse_common_organization_path = staticmethod(GrafeasClient.parse_common_organization_path) + common_project_path = staticmethod(GrafeasClient.common_project_path) + parse_common_project_path = staticmethod(GrafeasClient.parse_common_project_path) + common_location_path = staticmethod(GrafeasClient.common_location_path) + parse_common_location_path = staticmethod(GrafeasClient.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: + GrafeasAsyncClient: The constructed client. + """ + return GrafeasClient.from_service_account_info.__func__(GrafeasAsyncClient, 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: + GrafeasAsyncClient: The constructed client. + """ + return GrafeasClient.from_service_account_file.__func__(GrafeasAsyncClient, 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 GrafeasClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> GrafeasTransport: + """Returns the transport used by the client instance. + + Returns: + GrafeasTransport: 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 = GrafeasClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, GrafeasTransport, Callable[..., GrafeasTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the grafeas 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,GrafeasTransport,Callable[..., GrafeasTransport]]]): + 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 GrafeasTransport 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 = GrafeasClient( + 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 `grafeas_v1.GrafeasAsyncClient`.", + extra = { + "serviceName": "grafeas.v1.Grafeas", + "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": "grafeas.v1.Grafeas", + "credentialsType": None, + } + ) + + async def get_occurrence(self, + request: Optional[Union[grafeas.GetOccurrenceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> grafeas.Occurrence: + r"""Gets the specified occurrence. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + async def sample_get_occurrence(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.GetOccurrenceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_occurrence(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[grafeas.grafeas_v1.types.GetOccurrenceRequest, dict]]): + The request object. Request to get an occurrence. + name (:class:`str`): + The name of the occurrence in the form of + ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_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: + grafeas.grafeas_v1.types.Occurrence: + An instance of an analysis type that + has been found on a 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.GetOccurrenceRequest): + request = grafeas.GetOccurrenceRequest(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_occurrence] + + # Certain 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_occurrences(self, + request: Optional[Union[grafeas.ListOccurrencesRequest, dict]] = None, + *, + parent: Optional[str] = None, + filter: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListOccurrencesAsyncPager: + r"""Lists occurrences for the specified project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + async def sample_list_occurrences(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.ListOccurrencesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_occurrences(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[grafeas.grafeas_v1.types.ListOccurrencesRequest, dict]]): + The request object. Request to list occurrences. + parent (:class:`str`): + The name of the project to list occurrences for in the + form of ``projects/[PROJECT_ID]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (:class:`str`): + The filter expression. + This corresponds to the ``filter`` 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: + grafeas.grafeas_v1.services.grafeas.pagers.ListOccurrencesAsyncPager: + Response for listing occurrences. + + 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. + has_flattened_params = any([parent, filter]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.ListOccurrencesRequest): + request = grafeas.ListOccurrencesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_occurrences] + + # Certain 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.ListOccurrencesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_occurrence(self, + request: Optional[Union[grafeas.DeleteOccurrenceRequest, dict]] = None, + *, + name: Optional[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 occurrence. For example, use + this method to delete an occurrence when the occurrence + is no longer applicable for the given resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + async def sample_delete_occurrence(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.DeleteOccurrenceRequest( + name="name_value", + ) + + # Make the request + await client.delete_occurrence(request=request) + + Args: + request (Optional[Union[grafeas.grafeas_v1.types.DeleteOccurrenceRequest, dict]]): + The request object. Request to delete an occurrence. + name (:class:`str`): + The name of the occurrence in the form of + ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_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`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.DeleteOccurrenceRequest): + request = grafeas.DeleteOccurrenceRequest(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_occurrence] + + # Certain 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 create_occurrence(self, + request: Optional[Union[grafeas.CreateOccurrenceRequest, dict]] = None, + *, + parent: Optional[str] = None, + occurrence: Optional[grafeas.Occurrence] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> grafeas.Occurrence: + r"""Creates a new occurrence. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + async def sample_create_occurrence(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.CreateOccurrenceRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_occurrence(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[grafeas.grafeas_v1.types.CreateOccurrenceRequest, dict]]): + The request object. Request to create a new occurrence. + parent (:class:`str`): + The name of the project in the form of + ``projects/[PROJECT_ID]``, under which the occurrence is + to be created. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + occurrence (:class:`grafeas.grafeas_v1.types.Occurrence`): + The occurrence to create. + This corresponds to the ``occurrence`` 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: + grafeas.grafeas_v1.types.Occurrence: + An instance of an analysis type that + has been found on a 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. + has_flattened_params = any([parent, occurrence]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.CreateOccurrenceRequest): + request = grafeas.CreateOccurrenceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if occurrence is not None: + request.occurrence = occurrence + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_occurrence] + + # Certain 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 batch_create_occurrences(self, + request: Optional[Union[grafeas.BatchCreateOccurrencesRequest, dict]] = None, + *, + parent: Optional[str] = None, + occurrences: Optional[MutableSequence[grafeas.Occurrence]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> grafeas.BatchCreateOccurrencesResponse: + r"""Creates new occurrences in batch. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + async def sample_batch_create_occurrences(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.BatchCreateOccurrencesRequest( + parent="parent_value", + ) + + # Make the request + response = await client.batch_create_occurrences(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[grafeas.grafeas_v1.types.BatchCreateOccurrencesRequest, dict]]): + The request object. Request to create occurrences in + batch. + parent (:class:`str`): + The name of the project in the form of + ``projects/[PROJECT_ID]``, under which the occurrences + are to be created. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + occurrences (:class:`MutableSequence[grafeas.grafeas_v1.types.Occurrence]`): + The occurrences to create. Max + allowed length is 1000. + + This corresponds to the ``occurrences`` 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: + grafeas.grafeas_v1.types.BatchCreateOccurrencesResponse: + Response for creating occurrences in + batch. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, occurrences]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.BatchCreateOccurrencesRequest): + request = grafeas.BatchCreateOccurrencesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if occurrences: + request.occurrences.extend(occurrences) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.batch_create_occurrences] + + # Certain 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_occurrence(self, + request: Optional[Union[grafeas.UpdateOccurrenceRequest, dict]] = None, + *, + name: Optional[str] = None, + occurrence: Optional[grafeas.Occurrence] = 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]]] = (), + ) -> grafeas.Occurrence: + r"""Updates the specified occurrence. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + async def sample_update_occurrence(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.UpdateOccurrenceRequest( + name="name_value", + ) + + # Make the request + response = await client.update_occurrence(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[grafeas.grafeas_v1.types.UpdateOccurrenceRequest, dict]]): + The request object. Request to update an occurrence. + name (:class:`str`): + The name of the occurrence in the form of + ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + occurrence (:class:`grafeas.grafeas_v1.types.Occurrence`): + The updated occurrence. + This corresponds to the ``occurrence`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The fields to update. + 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: + grafeas.grafeas_v1.types.Occurrence: + An instance of an analysis type that + has been found on a 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. + has_flattened_params = any([name, occurrence, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.UpdateOccurrenceRequest): + request = grafeas.UpdateOccurrenceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if occurrence is not None: + request.occurrence = occurrence + 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_occurrence] + + # Certain 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_occurrence_note(self, + request: Optional[Union[grafeas.GetOccurrenceNoteRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> grafeas.Note: + r"""Gets the note attached to the specified occurrence. + Consumer projects can use this method to get a note that + belongs to a provider project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + async def sample_get_occurrence_note(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.GetOccurrenceNoteRequest( + name="name_value", + ) + + # Make the request + response = await client.get_occurrence_note(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[grafeas.grafeas_v1.types.GetOccurrenceNoteRequest, dict]]): + The request object. Request to get the note to which the + specified occurrence is attached. + name (:class:`str`): + The name of the occurrence in the form of + ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_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: + grafeas.grafeas_v1.types.Note: + A type of analysis that can be done + for a 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.GetOccurrenceNoteRequest): + request = grafeas.GetOccurrenceNoteRequest(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_occurrence_note] + + # Certain 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_note(self, + request: Optional[Union[grafeas.GetNoteRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> grafeas.Note: + r"""Gets the specified note. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + async def sample_get_note(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.GetNoteRequest( + name="name_value", + ) + + # Make the request + response = await client.get_note(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[grafeas.grafeas_v1.types.GetNoteRequest, dict]]): + The request object. Request to get a note. + name (:class:`str`): + The name of the note in the form of + ``projects/[PROVIDER_ID]/notes/[NOTE_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: + grafeas.grafeas_v1.types.Note: + A type of analysis that can be done + for a 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.GetNoteRequest): + request = grafeas.GetNoteRequest(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_note] + + # Certain 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_notes(self, + request: Optional[Union[grafeas.ListNotesRequest, dict]] = None, + *, + parent: Optional[str] = None, + filter: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListNotesAsyncPager: + r"""Lists notes for the specified project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + async def sample_list_notes(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.ListNotesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_notes(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[grafeas.grafeas_v1.types.ListNotesRequest, dict]]): + The request object. Request to list notes. + parent (:class:`str`): + The name of the project to list notes for in the form of + ``projects/[PROJECT_ID]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (:class:`str`): + The filter expression. + This corresponds to the ``filter`` 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: + grafeas.grafeas_v1.services.grafeas.pagers.ListNotesAsyncPager: + Response for listing notes. + + 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. + has_flattened_params = any([parent, filter]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.ListNotesRequest): + request = grafeas.ListNotesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_notes] + + # Certain 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.ListNotesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_note(self, + request: Optional[Union[grafeas.DeleteNoteRequest, dict]] = None, + *, + name: Optional[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 note. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + async def sample_delete_note(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.DeleteNoteRequest( + name="name_value", + ) + + # Make the request + await client.delete_note(request=request) + + Args: + request (Optional[Union[grafeas.grafeas_v1.types.DeleteNoteRequest, dict]]): + The request object. Request to delete a note. + name (:class:`str`): + The name of the note in the form of + ``projects/[PROVIDER_ID]/notes/[NOTE_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`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.DeleteNoteRequest): + request = grafeas.DeleteNoteRequest(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_note] + + # Certain 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 create_note(self, + request: Optional[Union[grafeas.CreateNoteRequest, dict]] = None, + *, + parent: Optional[str] = None, + note_id: Optional[str] = None, + note: Optional[grafeas.Note] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> grafeas.Note: + r"""Creates a new note. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + async def sample_create_note(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.CreateNoteRequest( + parent="parent_value", + note_id="note_id_value", + ) + + # Make the request + response = await client.create_note(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[grafeas.grafeas_v1.types.CreateNoteRequest, dict]]): + The request object. Request to create a new note. + parent (:class:`str`): + The name of the project in the form of + ``projects/[PROJECT_ID]``, under which the note is to be + created. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + note_id (:class:`str`): + The ID to use for this note. + This corresponds to the ``note_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + note (:class:`grafeas.grafeas_v1.types.Note`): + The note to create. + This corresponds to the ``note`` 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: + grafeas.grafeas_v1.types.Note: + A type of analysis that can be done + for a 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. + has_flattened_params = any([parent, note_id, note]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.CreateNoteRequest): + request = grafeas.CreateNoteRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if note_id is not None: + request.note_id = note_id + if note is not None: + request.note = note + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_note] + + # Certain 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 batch_create_notes(self, + request: Optional[Union[grafeas.BatchCreateNotesRequest, dict]] = None, + *, + parent: Optional[str] = None, + notes: Optional[MutableMapping[str, grafeas.Note]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> grafeas.BatchCreateNotesResponse: + r"""Creates new notes in batch. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + async def sample_batch_create_notes(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.BatchCreateNotesRequest( + parent="parent_value", + ) + + # Make the request + response = await client.batch_create_notes(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[grafeas.grafeas_v1.types.BatchCreateNotesRequest, dict]]): + The request object. Request to create notes in batch. + parent (:class:`str`): + The name of the project in the form of + ``projects/[PROJECT_ID]``, under which the notes are to + be created. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + notes (:class:`MutableMapping[str, grafeas.grafeas_v1.types.Note]`): + The notes to create. Max allowed + length is 1000. + + This corresponds to the ``notes`` 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: + grafeas.grafeas_v1.types.BatchCreateNotesResponse: + Response for creating notes in batch. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, notes]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.BatchCreateNotesRequest): + request = grafeas.BatchCreateNotesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + if notes: + request.notes.update(notes) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.batch_create_notes] + + # Certain 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_note(self, + request: Optional[Union[grafeas.UpdateNoteRequest, dict]] = None, + *, + name: Optional[str] = None, + note: Optional[grafeas.Note] = 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]]] = (), + ) -> grafeas.Note: + r"""Updates the specified note. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + async def sample_update_note(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.UpdateNoteRequest( + name="name_value", + ) + + # Make the request + response = await client.update_note(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[grafeas.grafeas_v1.types.UpdateNoteRequest, dict]]): + The request object. Request to update a note. + name (:class:`str`): + The name of the note in the form of + ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + note (:class:`grafeas.grafeas_v1.types.Note`): + The updated note. + This corresponds to the ``note`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The fields to update. + 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: + grafeas.grafeas_v1.types.Note: + A type of analysis that can be done + for a 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. + has_flattened_params = any([name, note, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.UpdateNoteRequest): + request = grafeas.UpdateNoteRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if note is not None: + request.note = note + 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_note] + + # Certain 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_note_occurrences(self, + request: Optional[Union[grafeas.ListNoteOccurrencesRequest, dict]] = None, + *, + name: Optional[str] = None, + filter: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListNoteOccurrencesAsyncPager: + r"""Lists occurrences referencing the specified note. + Provider projects can use this method to get all + occurrences across consumer projects referencing the + specified note. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + async def sample_list_note_occurrences(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.ListNoteOccurrencesRequest( + name="name_value", + ) + + # Make the request + page_result = client.list_note_occurrences(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[grafeas.grafeas_v1.types.ListNoteOccurrencesRequest, dict]]): + The request object. Request to list occurrences for a + note. + name (:class:`str`): + The name of the note to list occurrences for in the form + of ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (:class:`str`): + The filter expression. + This corresponds to the ``filter`` 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: + grafeas.grafeas_v1.services.grafeas.pagers.ListNoteOccurrencesAsyncPager: + Response for listing occurrences for + a note. + 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. + has_flattened_params = any([name, filter]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.ListNoteOccurrencesRequest): + request = grafeas.ListNoteOccurrencesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if filter is not None: + request.filter = filter + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_note_occurrences] + + # Certain 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, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListNoteOccurrencesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "GrafeasAsyncClient": + 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__) + + +__all__ = ( + "GrafeasAsyncClient", +) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/client.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/client.py new file mode 100644 index 000000000000..b8987a77daf1 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/client.py @@ -0,0 +1,2225 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +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 grafeas.grafeas_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 + +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 timestamp_pb2 # type: ignore +from grafeas.grafeas_v1.services.grafeas import pagers +from grafeas.grafeas_v1.types import attestation +from grafeas.grafeas_v1.types import build +from grafeas.grafeas_v1.types import common +from grafeas.grafeas_v1.types import compliance +from grafeas.grafeas_v1.types import deployment +from grafeas.grafeas_v1.types import discovery +from grafeas.grafeas_v1.types import dsse_attestation +from grafeas.grafeas_v1.types import grafeas +from grafeas.grafeas_v1.types import image +from grafeas.grafeas_v1.types import package +from grafeas.grafeas_v1.types import sbom +from grafeas.grafeas_v1.types import upgrade +from grafeas.grafeas_v1.types import vex +from grafeas.grafeas_v1.types import vulnerability +from .transports.base import GrafeasTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import GrafeasGrpcTransport +from .transports.grpc_asyncio import GrafeasGrpcAsyncIOTransport +from .transports.rest import GrafeasRestTransport + + +class GrafeasClientMeta(type): + """Metaclass for the Grafeas 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[GrafeasTransport]] + _transport_registry["grpc"] = GrafeasGrpcTransport + _transport_registry["grpc_asyncio"] = GrafeasGrpcAsyncIOTransport + _transport_registry["rest"] = GrafeasRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[GrafeasTransport]: + """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 GrafeasClient(metaclass=GrafeasClientMeta): + """`Grafeas `__ API. + + Retrieves analysis results of Cloud components such as Docker + container images. + + Analysis results are stored as a series of occurrences. An + ``Occurrence`` contains information about a specific analysis + instance on a resource. An occurrence refers to a ``Note``. A note + contains details describing the analysis and is generally stored in + a separate project, called a ``Provider``. Multiple occurrences can + refer to the same note. + + For example, an SSL vulnerability could affect multiple images. In + this case, there would be one note for the vulnerability and an + occurrence for each image with the vulnerability referring to that + note. + """ + + @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 = "containeranalysis.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "containeranalysis.{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: + GrafeasClient: 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: + GrafeasClient: 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) -> GrafeasTransport: + """Returns the transport used by the client instance. + + Returns: + GrafeasTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def note_path(project: str,note: str,) -> str: + """Returns a fully-qualified note string.""" + return "projects/{project}/notes/{note}".format(project=project, note=note, ) + + @staticmethod + def parse_note_path(path: str) -> Dict[str,str]: + """Parses a note path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/notes/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def occurrence_path(project: str,occurrence: str,) -> str: + """Returns a fully-qualified occurrence string.""" + return "projects/{project}/occurrences/{occurrence}".format(project=project, occurrence=occurrence, ) + + @staticmethod + def parse_occurrence_path(path: str) -> Dict[str,str]: + """Parses a occurrence path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/occurrences/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def project_path(project: str,) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_project_path(path: str) -> Dict[str,str]: + """Parses a project path into its component segments.""" + m = re.match(r"^projects/(?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 = GrafeasClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = GrafeasClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = GrafeasClient._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 = GrafeasClient._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 + + @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, GrafeasTransport, Callable[..., GrafeasTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the grafeas 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,GrafeasTransport,Callable[..., GrafeasTransport]]]): + 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 GrafeasTransport 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 = GrafeasClient._read_environment_variables() + self._client_cert_source = GrafeasClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = GrafeasClient._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, GrafeasTransport) + if transport_provided: + # transport is a GrafeasTransport 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(GrafeasTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + GrafeasClient._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[GrafeasTransport], Callable[..., GrafeasTransport]] = ( + GrafeasClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., GrafeasTransport], 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 `grafeas_v1.GrafeasClient`.", + extra = { + "serviceName": "grafeas.v1.Grafeas", + "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": "grafeas.v1.Grafeas", + "credentialsType": None, + } + ) + + def get_occurrence(self, + request: Optional[Union[grafeas.GetOccurrenceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> grafeas.Occurrence: + r"""Gets the specified occurrence. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + def sample_get_occurrence(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.GetOccurrenceRequest( + name="name_value", + ) + + # Make the request + response = client.get_occurrence(request=request) + + # Handle the response + print(response) + + Args: + request (Union[grafeas.grafeas_v1.types.GetOccurrenceRequest, dict]): + The request object. Request to get an occurrence. + name (str): + The name of the occurrence in the form of + ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_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: + grafeas.grafeas_v1.types.Occurrence: + An instance of an analysis type that + has been found on a 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.GetOccurrenceRequest): + request = grafeas.GetOccurrenceRequest(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_occurrence] + + # Certain 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_occurrences(self, + request: Optional[Union[grafeas.ListOccurrencesRequest, dict]] = None, + *, + parent: Optional[str] = None, + filter: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListOccurrencesPager: + r"""Lists occurrences for the specified project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + def sample_list_occurrences(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.ListOccurrencesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_occurrences(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[grafeas.grafeas_v1.types.ListOccurrencesRequest, dict]): + The request object. Request to list occurrences. + parent (str): + The name of the project to list occurrences for in the + form of ``projects/[PROJECT_ID]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (str): + The filter expression. + This corresponds to the ``filter`` 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: + grafeas.grafeas_v1.services.grafeas.pagers.ListOccurrencesPager: + Response for listing occurrences. + + 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. + has_flattened_params = any([parent, filter]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.ListOccurrencesRequest): + request = grafeas.ListOccurrencesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_occurrences] + + # Certain 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.ListOccurrencesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_occurrence(self, + request: Optional[Union[grafeas.DeleteOccurrenceRequest, dict]] = None, + *, + name: Optional[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 occurrence. For example, use + this method to delete an occurrence when the occurrence + is no longer applicable for the given resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + def sample_delete_occurrence(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.DeleteOccurrenceRequest( + name="name_value", + ) + + # Make the request + client.delete_occurrence(request=request) + + Args: + request (Union[grafeas.grafeas_v1.types.DeleteOccurrenceRequest, dict]): + The request object. Request to delete an occurrence. + name (str): + The name of the occurrence in the form of + ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_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`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.DeleteOccurrenceRequest): + request = grafeas.DeleteOccurrenceRequest(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_occurrence] + + # Certain 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 create_occurrence(self, + request: Optional[Union[grafeas.CreateOccurrenceRequest, dict]] = None, + *, + parent: Optional[str] = None, + occurrence: Optional[grafeas.Occurrence] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> grafeas.Occurrence: + r"""Creates a new occurrence. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + def sample_create_occurrence(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.CreateOccurrenceRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_occurrence(request=request) + + # Handle the response + print(response) + + Args: + request (Union[grafeas.grafeas_v1.types.CreateOccurrenceRequest, dict]): + The request object. Request to create a new occurrence. + parent (str): + The name of the project in the form of + ``projects/[PROJECT_ID]``, under which the occurrence is + to be created. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + occurrence (grafeas.grafeas_v1.types.Occurrence): + The occurrence to create. + This corresponds to the ``occurrence`` 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: + grafeas.grafeas_v1.types.Occurrence: + An instance of an analysis type that + has been found on a 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. + has_flattened_params = any([parent, occurrence]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.CreateOccurrenceRequest): + request = grafeas.CreateOccurrenceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if occurrence is not None: + request.occurrence = occurrence + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_occurrence] + + # Certain 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 batch_create_occurrences(self, + request: Optional[Union[grafeas.BatchCreateOccurrencesRequest, dict]] = None, + *, + parent: Optional[str] = None, + occurrences: Optional[MutableSequence[grafeas.Occurrence]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> grafeas.BatchCreateOccurrencesResponse: + r"""Creates new occurrences in batch. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + def sample_batch_create_occurrences(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.BatchCreateOccurrencesRequest( + parent="parent_value", + ) + + # Make the request + response = client.batch_create_occurrences(request=request) + + # Handle the response + print(response) + + Args: + request (Union[grafeas.grafeas_v1.types.BatchCreateOccurrencesRequest, dict]): + The request object. Request to create occurrences in + batch. + parent (str): + The name of the project in the form of + ``projects/[PROJECT_ID]``, under which the occurrences + are to be created. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + occurrences (MutableSequence[grafeas.grafeas_v1.types.Occurrence]): + The occurrences to create. Max + allowed length is 1000. + + This corresponds to the ``occurrences`` 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: + grafeas.grafeas_v1.types.BatchCreateOccurrencesResponse: + Response for creating occurrences in + batch. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, occurrences]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.BatchCreateOccurrencesRequest): + request = grafeas.BatchCreateOccurrencesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if occurrences is not None: + request.occurrences = occurrences + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_create_occurrences] + + # Certain 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_occurrence(self, + request: Optional[Union[grafeas.UpdateOccurrenceRequest, dict]] = None, + *, + name: Optional[str] = None, + occurrence: Optional[grafeas.Occurrence] = 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]]] = (), + ) -> grafeas.Occurrence: + r"""Updates the specified occurrence. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + def sample_update_occurrence(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.UpdateOccurrenceRequest( + name="name_value", + ) + + # Make the request + response = client.update_occurrence(request=request) + + # Handle the response + print(response) + + Args: + request (Union[grafeas.grafeas_v1.types.UpdateOccurrenceRequest, dict]): + The request object. Request to update an occurrence. + name (str): + The name of the occurrence in the form of + ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + occurrence (grafeas.grafeas_v1.types.Occurrence): + The updated occurrence. + This corresponds to the ``occurrence`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The fields to update. + 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: + grafeas.grafeas_v1.types.Occurrence: + An instance of an analysis type that + has been found on a 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. + has_flattened_params = any([name, occurrence, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.UpdateOccurrenceRequest): + request = grafeas.UpdateOccurrenceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if occurrence is not None: + request.occurrence = occurrence + 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_occurrence] + + # Certain 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_occurrence_note(self, + request: Optional[Union[grafeas.GetOccurrenceNoteRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> grafeas.Note: + r"""Gets the note attached to the specified occurrence. + Consumer projects can use this method to get a note that + belongs to a provider project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + def sample_get_occurrence_note(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.GetOccurrenceNoteRequest( + name="name_value", + ) + + # Make the request + response = client.get_occurrence_note(request=request) + + # Handle the response + print(response) + + Args: + request (Union[grafeas.grafeas_v1.types.GetOccurrenceNoteRequest, dict]): + The request object. Request to get the note to which the + specified occurrence is attached. + name (str): + The name of the occurrence in the form of + ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_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: + grafeas.grafeas_v1.types.Note: + A type of analysis that can be done + for a 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.GetOccurrenceNoteRequest): + request = grafeas.GetOccurrenceNoteRequest(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_occurrence_note] + + # Certain 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_note(self, + request: Optional[Union[grafeas.GetNoteRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> grafeas.Note: + r"""Gets the specified note. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + def sample_get_note(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.GetNoteRequest( + name="name_value", + ) + + # Make the request + response = client.get_note(request=request) + + # Handle the response + print(response) + + Args: + request (Union[grafeas.grafeas_v1.types.GetNoteRequest, dict]): + The request object. Request to get a note. + name (str): + The name of the note in the form of + ``projects/[PROVIDER_ID]/notes/[NOTE_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: + grafeas.grafeas_v1.types.Note: + A type of analysis that can be done + for a 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.GetNoteRequest): + request = grafeas.GetNoteRequest(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_note] + + # Certain 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_notes(self, + request: Optional[Union[grafeas.ListNotesRequest, dict]] = None, + *, + parent: Optional[str] = None, + filter: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListNotesPager: + r"""Lists notes for the specified project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + def sample_list_notes(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.ListNotesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_notes(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[grafeas.grafeas_v1.types.ListNotesRequest, dict]): + The request object. Request to list notes. + parent (str): + The name of the project to list notes for in the form of + ``projects/[PROJECT_ID]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (str): + The filter expression. + This corresponds to the ``filter`` 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: + grafeas.grafeas_v1.services.grafeas.pagers.ListNotesPager: + Response for listing notes. + + 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. + has_flattened_params = any([parent, filter]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.ListNotesRequest): + request = grafeas.ListNotesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_notes] + + # Certain 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.ListNotesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_note(self, + request: Optional[Union[grafeas.DeleteNoteRequest, dict]] = None, + *, + name: Optional[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 note. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + def sample_delete_note(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.DeleteNoteRequest( + name="name_value", + ) + + # Make the request + client.delete_note(request=request) + + Args: + request (Union[grafeas.grafeas_v1.types.DeleteNoteRequest, dict]): + The request object. Request to delete a note. + name (str): + The name of the note in the form of + ``projects/[PROVIDER_ID]/notes/[NOTE_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`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.DeleteNoteRequest): + request = grafeas.DeleteNoteRequest(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_note] + + # Certain 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 create_note(self, + request: Optional[Union[grafeas.CreateNoteRequest, dict]] = None, + *, + parent: Optional[str] = None, + note_id: Optional[str] = None, + note: Optional[grafeas.Note] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> grafeas.Note: + r"""Creates a new note. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + def sample_create_note(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.CreateNoteRequest( + parent="parent_value", + note_id="note_id_value", + ) + + # Make the request + response = client.create_note(request=request) + + # Handle the response + print(response) + + Args: + request (Union[grafeas.grafeas_v1.types.CreateNoteRequest, dict]): + The request object. Request to create a new note. + parent (str): + The name of the project in the form of + ``projects/[PROJECT_ID]``, under which the note is to be + created. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + note_id (str): + The ID to use for this note. + This corresponds to the ``note_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + note (grafeas.grafeas_v1.types.Note): + The note to create. + This corresponds to the ``note`` 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: + grafeas.grafeas_v1.types.Note: + A type of analysis that can be done + for a 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. + has_flattened_params = any([parent, note_id, note]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.CreateNoteRequest): + request = grafeas.CreateNoteRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if note_id is not None: + request.note_id = note_id + if note is not None: + request.note = note + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_note] + + # Certain 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 batch_create_notes(self, + request: Optional[Union[grafeas.BatchCreateNotesRequest, dict]] = None, + *, + parent: Optional[str] = None, + notes: Optional[MutableMapping[str, grafeas.Note]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> grafeas.BatchCreateNotesResponse: + r"""Creates new notes in batch. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + def sample_batch_create_notes(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.BatchCreateNotesRequest( + parent="parent_value", + ) + + # Make the request + response = client.batch_create_notes(request=request) + + # Handle the response + print(response) + + Args: + request (Union[grafeas.grafeas_v1.types.BatchCreateNotesRequest, dict]): + The request object. Request to create notes in batch. + parent (str): + The name of the project in the form of + ``projects/[PROJECT_ID]``, under which the notes are to + be created. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + notes (MutableMapping[str, grafeas.grafeas_v1.types.Note]): + The notes to create. Max allowed + length is 1000. + + This corresponds to the ``notes`` 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: + grafeas.grafeas_v1.types.BatchCreateNotesResponse: + Response for creating notes in batch. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, notes]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.BatchCreateNotesRequest): + request = grafeas.BatchCreateNotesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if notes is not None: + request.notes = notes + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_create_notes] + + # Certain 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_note(self, + request: Optional[Union[grafeas.UpdateNoteRequest, dict]] = None, + *, + name: Optional[str] = None, + note: Optional[grafeas.Note] = 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]]] = (), + ) -> grafeas.Note: + r"""Updates the specified note. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + def sample_update_note(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.UpdateNoteRequest( + name="name_value", + ) + + # Make the request + response = client.update_note(request=request) + + # Handle the response + print(response) + + Args: + request (Union[grafeas.grafeas_v1.types.UpdateNoteRequest, dict]): + The request object. Request to update a note. + name (str): + The name of the note in the form of + ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + note (grafeas.grafeas_v1.types.Note): + The updated note. + This corresponds to the ``note`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The fields to update. + 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: + grafeas.grafeas_v1.types.Note: + A type of analysis that can be done + for a 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. + has_flattened_params = any([name, note, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.UpdateNoteRequest): + request = grafeas.UpdateNoteRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if note is not None: + request.note = note + 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_note] + + # Certain 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_note_occurrences(self, + request: Optional[Union[grafeas.ListNoteOccurrencesRequest, dict]] = None, + *, + name: Optional[str] = None, + filter: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListNoteOccurrencesPager: + r"""Lists occurrences referencing the specified note. + Provider projects can use this method to get all + occurrences across consumer projects referencing the + specified note. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + def sample_list_note_occurrences(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.ListNoteOccurrencesRequest( + name="name_value", + ) + + # Make the request + page_result = client.list_note_occurrences(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[grafeas.grafeas_v1.types.ListNoteOccurrencesRequest, dict]): + The request object. Request to list occurrences for a + note. + name (str): + The name of the note to list occurrences for in the form + of ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (str): + The filter expression. + This corresponds to the ``filter`` 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: + grafeas.grafeas_v1.services.grafeas.pagers.ListNoteOccurrencesPager: + Response for listing occurrences for + a note. + 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. + has_flattened_params = any([name, filter]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.ListNoteOccurrencesRequest): + request = grafeas.ListNoteOccurrencesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if filter is not None: + request.filter = filter + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_note_occurrences] + + # Certain 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, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListNoteOccurrencesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "GrafeasClient": + 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__) + + +__all__ = ( + "GrafeasClient", +) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/pagers.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/pagers.py new file mode 100644 index 000000000000..e568551ef27e --- /dev/null +++ b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/pagers.py @@ -0,0 +1,444 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 grafeas.grafeas_v1.types import grafeas + + +class ListOccurrencesPager: + """A pager for iterating through ``list_occurrences`` requests. + + This class thinly wraps an initial + :class:`grafeas.grafeas_v1.types.ListOccurrencesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``occurrences`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListOccurrences`` requests and continue to iterate + through the ``occurrences`` field on the + corresponding responses. + + All the usual :class:`grafeas.grafeas_v1.types.ListOccurrencesResponse` + 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[..., grafeas.ListOccurrencesResponse], + request: grafeas.ListOccurrencesRequest, + response: grafeas.ListOccurrencesResponse, + *, + 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 (grafeas.grafeas_v1.types.ListOccurrencesRequest): + The initial request object. + response (grafeas.grafeas_v1.types.ListOccurrencesResponse): + 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 = grafeas.ListOccurrencesRequest(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[grafeas.ListOccurrencesResponse]: + 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[grafeas.Occurrence]: + for page in self.pages: + yield from page.occurrences + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListOccurrencesAsyncPager: + """A pager for iterating through ``list_occurrences`` requests. + + This class thinly wraps an initial + :class:`grafeas.grafeas_v1.types.ListOccurrencesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``occurrences`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListOccurrences`` requests and continue to iterate + through the ``occurrences`` field on the + corresponding responses. + + All the usual :class:`grafeas.grafeas_v1.types.ListOccurrencesResponse` + 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[grafeas.ListOccurrencesResponse]], + request: grafeas.ListOccurrencesRequest, + response: grafeas.ListOccurrencesResponse, + *, + 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 (grafeas.grafeas_v1.types.ListOccurrencesRequest): + The initial request object. + response (grafeas.grafeas_v1.types.ListOccurrencesResponse): + 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 = grafeas.ListOccurrencesRequest(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[grafeas.ListOccurrencesResponse]: + 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[grafeas.Occurrence]: + async def async_generator(): + async for page in self.pages: + for response in page.occurrences: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListNotesPager: + """A pager for iterating through ``list_notes`` requests. + + This class thinly wraps an initial + :class:`grafeas.grafeas_v1.types.ListNotesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``notes`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListNotes`` requests and continue to iterate + through the ``notes`` field on the + corresponding responses. + + All the usual :class:`grafeas.grafeas_v1.types.ListNotesResponse` + 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[..., grafeas.ListNotesResponse], + request: grafeas.ListNotesRequest, + response: grafeas.ListNotesResponse, + *, + 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 (grafeas.grafeas_v1.types.ListNotesRequest): + The initial request object. + response (grafeas.grafeas_v1.types.ListNotesResponse): + 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 = grafeas.ListNotesRequest(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[grafeas.ListNotesResponse]: + 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[grafeas.Note]: + for page in self.pages: + yield from page.notes + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListNotesAsyncPager: + """A pager for iterating through ``list_notes`` requests. + + This class thinly wraps an initial + :class:`grafeas.grafeas_v1.types.ListNotesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``notes`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListNotes`` requests and continue to iterate + through the ``notes`` field on the + corresponding responses. + + All the usual :class:`grafeas.grafeas_v1.types.ListNotesResponse` + 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[grafeas.ListNotesResponse]], + request: grafeas.ListNotesRequest, + response: grafeas.ListNotesResponse, + *, + 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 (grafeas.grafeas_v1.types.ListNotesRequest): + The initial request object. + response (grafeas.grafeas_v1.types.ListNotesResponse): + 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 = grafeas.ListNotesRequest(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[grafeas.ListNotesResponse]: + 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[grafeas.Note]: + async def async_generator(): + async for page in self.pages: + for response in page.notes: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListNoteOccurrencesPager: + """A pager for iterating through ``list_note_occurrences`` requests. + + This class thinly wraps an initial + :class:`grafeas.grafeas_v1.types.ListNoteOccurrencesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``occurrences`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListNoteOccurrences`` requests and continue to iterate + through the ``occurrences`` field on the + corresponding responses. + + All the usual :class:`grafeas.grafeas_v1.types.ListNoteOccurrencesResponse` + 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[..., grafeas.ListNoteOccurrencesResponse], + request: grafeas.ListNoteOccurrencesRequest, + response: grafeas.ListNoteOccurrencesResponse, + *, + 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 (grafeas.grafeas_v1.types.ListNoteOccurrencesRequest): + The initial request object. + response (grafeas.grafeas_v1.types.ListNoteOccurrencesResponse): + 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 = grafeas.ListNoteOccurrencesRequest(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[grafeas.ListNoteOccurrencesResponse]: + 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[grafeas.Occurrence]: + for page in self.pages: + yield from page.occurrences + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListNoteOccurrencesAsyncPager: + """A pager for iterating through ``list_note_occurrences`` requests. + + This class thinly wraps an initial + :class:`grafeas.grafeas_v1.types.ListNoteOccurrencesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``occurrences`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListNoteOccurrences`` requests and continue to iterate + through the ``occurrences`` field on the + corresponding responses. + + All the usual :class:`grafeas.grafeas_v1.types.ListNoteOccurrencesResponse` + 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[grafeas.ListNoteOccurrencesResponse]], + request: grafeas.ListNoteOccurrencesRequest, + response: grafeas.ListNoteOccurrencesResponse, + *, + 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 (grafeas.grafeas_v1.types.ListNoteOccurrencesRequest): + The initial request object. + response (grafeas.grafeas_v1.types.ListNoteOccurrencesResponse): + 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 = grafeas.ListNoteOccurrencesRequest(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[grafeas.ListNoteOccurrencesResponse]: + 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[grafeas.Occurrence]: + async def async_generator(): + async for page in self.pages: + for response in page.occurrences: + 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/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/README.rst b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/README.rst new file mode 100644 index 000000000000..1085202fe2c8 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`GrafeasTransport` is the ABC for all transports. +- public child `GrafeasGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `GrafeasGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseGrafeasRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `GrafeasRestTransport` 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/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/__init__.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/__init__.py new file mode 100644 index 000000000000..af77bbdd97ec --- /dev/null +++ b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 GrafeasTransport +from .grpc import GrafeasGrpcTransport +from .grpc_asyncio import GrafeasGrpcAsyncIOTransport +from .rest import GrafeasRestTransport +from .rest import GrafeasRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[GrafeasTransport]] +_transport_registry['grpc'] = GrafeasGrpcTransport +_transport_registry['grpc_asyncio'] = GrafeasGrpcAsyncIOTransport +_transport_registry['rest'] = GrafeasRestTransport + +__all__ = ( + 'GrafeasTransport', + 'GrafeasGrpcTransport', + 'GrafeasGrpcAsyncIOTransport', + 'GrafeasRestTransport', + 'GrafeasRestInterceptor', +) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/base.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/base.py new file mode 100644 index 000000000000..6fbf36ad7b3d --- /dev/null +++ b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/base.py @@ -0,0 +1,416 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 grafeas.grafeas_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 + +from google.protobuf import empty_pb2 # type: ignore +from grafeas.grafeas_v1.types import grafeas + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class GrafeasTransport(abc.ABC): + """Abstract transport class for Grafeas.""" + + AUTH_SCOPES = ( + ) + + DEFAULT_HOST: str = 'containeranalysis.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: 'containeranalysis.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to 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_occurrence: gapic_v1.method.wrap_method( + self.get_occurrence, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.list_occurrences: gapic_v1.method.wrap_method( + self.list_occurrences, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.delete_occurrence: gapic_v1.method.wrap_method( + self.delete_occurrence, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.create_occurrence: gapic_v1.method.wrap_method( + self.create_occurrence, + default_timeout=30.0, + client_info=client_info, + ), + self.batch_create_occurrences: gapic_v1.method.wrap_method( + self.batch_create_occurrences, + default_timeout=30.0, + client_info=client_info, + ), + self.update_occurrence: gapic_v1.method.wrap_method( + self.update_occurrence, + default_timeout=30.0, + client_info=client_info, + ), + self.get_occurrence_note: gapic_v1.method.wrap_method( + self.get_occurrence_note, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.get_note: gapic_v1.method.wrap_method( + self.get_note, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.list_notes: gapic_v1.method.wrap_method( + self.list_notes, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.delete_note: gapic_v1.method.wrap_method( + self.delete_note, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.create_note: gapic_v1.method.wrap_method( + self.create_note, + default_timeout=30.0, + client_info=client_info, + ), + self.batch_create_notes: gapic_v1.method.wrap_method( + self.batch_create_notes, + default_timeout=30.0, + client_info=client_info, + ), + self.update_note: gapic_v1.method.wrap_method( + self.update_note, + default_timeout=30.0, + client_info=client_info, + ), + self.list_note_occurrences: gapic_v1.method.wrap_method( + self.list_note_occurrences, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def get_occurrence(self) -> Callable[ + [grafeas.GetOccurrenceRequest], + Union[ + grafeas.Occurrence, + Awaitable[grafeas.Occurrence] + ]]: + raise NotImplementedError() + + @property + def list_occurrences(self) -> Callable[ + [grafeas.ListOccurrencesRequest], + Union[ + grafeas.ListOccurrencesResponse, + Awaitable[grafeas.ListOccurrencesResponse] + ]]: + raise NotImplementedError() + + @property + def delete_occurrence(self) -> Callable[ + [grafeas.DeleteOccurrenceRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def create_occurrence(self) -> Callable[ + [grafeas.CreateOccurrenceRequest], + Union[ + grafeas.Occurrence, + Awaitable[grafeas.Occurrence] + ]]: + raise NotImplementedError() + + @property + def batch_create_occurrences(self) -> Callable[ + [grafeas.BatchCreateOccurrencesRequest], + Union[ + grafeas.BatchCreateOccurrencesResponse, + Awaitable[grafeas.BatchCreateOccurrencesResponse] + ]]: + raise NotImplementedError() + + @property + def update_occurrence(self) -> Callable[ + [grafeas.UpdateOccurrenceRequest], + Union[ + grafeas.Occurrence, + Awaitable[grafeas.Occurrence] + ]]: + raise NotImplementedError() + + @property + def get_occurrence_note(self) -> Callable[ + [grafeas.GetOccurrenceNoteRequest], + Union[ + grafeas.Note, + Awaitable[grafeas.Note] + ]]: + raise NotImplementedError() + + @property + def get_note(self) -> Callable[ + [grafeas.GetNoteRequest], + Union[ + grafeas.Note, + Awaitable[grafeas.Note] + ]]: + raise NotImplementedError() + + @property + def list_notes(self) -> Callable[ + [grafeas.ListNotesRequest], + Union[ + grafeas.ListNotesResponse, + Awaitable[grafeas.ListNotesResponse] + ]]: + raise NotImplementedError() + + @property + def delete_note(self) -> Callable[ + [grafeas.DeleteNoteRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def create_note(self) -> Callable[ + [grafeas.CreateNoteRequest], + Union[ + grafeas.Note, + Awaitable[grafeas.Note] + ]]: + raise NotImplementedError() + + @property + def batch_create_notes(self) -> Callable[ + [grafeas.BatchCreateNotesRequest], + Union[ + grafeas.BatchCreateNotesResponse, + Awaitable[grafeas.BatchCreateNotesResponse] + ]]: + raise NotImplementedError() + + @property + def update_note(self) -> Callable[ + [grafeas.UpdateNoteRequest], + Union[ + grafeas.Note, + Awaitable[grafeas.Note] + ]]: + raise NotImplementedError() + + @property + def list_note_occurrences(self) -> Callable[ + [grafeas.ListNoteOccurrencesRequest], + Union[ + grafeas.ListNoteOccurrencesResponse, + Awaitable[grafeas.ListNoteOccurrencesResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'GrafeasTransport', +) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/grpc.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/grpc.py new file mode 100644 index 000000000000..04285daa7edd --- /dev/null +++ b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/grpc.py @@ -0,0 +1,708 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 grafeas.grafeas_v1.types import grafeas +from .base import GrafeasTransport, 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": "grafeas.v1.Grafeas", + "rpcName": 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": "grafeas.v1.Grafeas", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class GrafeasGrpcTransport(GrafeasTransport): + """gRPC backend transport for Grafeas. + + `Grafeas `__ API. + + Retrieves analysis results of Cloud components such as Docker + container images. + + Analysis results are stored as a series of occurrences. An + ``Occurrence`` contains information about a specific analysis + instance on a resource. An occurrence refers to a ``Note``. A note + contains details describing the analysis and is generally stored in + a separate project, called a ``Provider``. Multiple occurrences can + refer to the same note. + + For example, an SSL vulnerability could affect multiple images. In + this case, there would be one note for the vulnerability and an + occurrence for each image with the vulnerability referring to that + note. + + This 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 = 'containeranalysis.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: 'containeranalysis.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to 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 = 'containeranalysis.googleapis.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_occurrence(self) -> Callable[ + [grafeas.GetOccurrenceRequest], + grafeas.Occurrence]: + r"""Return a callable for the get occurrence method over gRPC. + + Gets the specified occurrence. + + Returns: + Callable[[~.GetOccurrenceRequest], + ~.Occurrence]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_occurrence' not in self._stubs: + self._stubs['get_occurrence'] = self._logged_channel.unary_unary( + '/grafeas.v1.Grafeas/GetOccurrence', + request_serializer=grafeas.GetOccurrenceRequest.serialize, + response_deserializer=grafeas.Occurrence.deserialize, + ) + return self._stubs['get_occurrence'] + + @property + def list_occurrences(self) -> Callable[ + [grafeas.ListOccurrencesRequest], + grafeas.ListOccurrencesResponse]: + r"""Return a callable for the list occurrences method over gRPC. + + Lists occurrences for the specified project. + + Returns: + Callable[[~.ListOccurrencesRequest], + ~.ListOccurrencesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_occurrences' not in self._stubs: + self._stubs['list_occurrences'] = self._logged_channel.unary_unary( + '/grafeas.v1.Grafeas/ListOccurrences', + request_serializer=grafeas.ListOccurrencesRequest.serialize, + response_deserializer=grafeas.ListOccurrencesResponse.deserialize, + ) + return self._stubs['list_occurrences'] + + @property + def delete_occurrence(self) -> Callable[ + [grafeas.DeleteOccurrenceRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete occurrence method over gRPC. + + Deletes the specified occurrence. For example, use + this method to delete an occurrence when the occurrence + is no longer applicable for the given resource. + + Returns: + Callable[[~.DeleteOccurrenceRequest], + ~.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_occurrence' not in self._stubs: + self._stubs['delete_occurrence'] = self._logged_channel.unary_unary( + '/grafeas.v1.Grafeas/DeleteOccurrence', + request_serializer=grafeas.DeleteOccurrenceRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_occurrence'] + + @property + def create_occurrence(self) -> Callable[ + [grafeas.CreateOccurrenceRequest], + grafeas.Occurrence]: + r"""Return a callable for the create occurrence method over gRPC. + + Creates a new occurrence. + + Returns: + Callable[[~.CreateOccurrenceRequest], + ~.Occurrence]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_occurrence' not in self._stubs: + self._stubs['create_occurrence'] = self._logged_channel.unary_unary( + '/grafeas.v1.Grafeas/CreateOccurrence', + request_serializer=grafeas.CreateOccurrenceRequest.serialize, + response_deserializer=grafeas.Occurrence.deserialize, + ) + return self._stubs['create_occurrence'] + + @property + def batch_create_occurrences(self) -> Callable[ + [grafeas.BatchCreateOccurrencesRequest], + grafeas.BatchCreateOccurrencesResponse]: + r"""Return a callable for the batch create occurrences method over gRPC. + + Creates new occurrences in batch. + + Returns: + Callable[[~.BatchCreateOccurrencesRequest], + ~.BatchCreateOccurrencesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_create_occurrences' not in self._stubs: + self._stubs['batch_create_occurrences'] = self._logged_channel.unary_unary( + '/grafeas.v1.Grafeas/BatchCreateOccurrences', + request_serializer=grafeas.BatchCreateOccurrencesRequest.serialize, + response_deserializer=grafeas.BatchCreateOccurrencesResponse.deserialize, + ) + return self._stubs['batch_create_occurrences'] + + @property + def update_occurrence(self) -> Callable[ + [grafeas.UpdateOccurrenceRequest], + grafeas.Occurrence]: + r"""Return a callable for the update occurrence method over gRPC. + + Updates the specified occurrence. + + Returns: + Callable[[~.UpdateOccurrenceRequest], + ~.Occurrence]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_occurrence' not in self._stubs: + self._stubs['update_occurrence'] = self._logged_channel.unary_unary( + '/grafeas.v1.Grafeas/UpdateOccurrence', + request_serializer=grafeas.UpdateOccurrenceRequest.serialize, + response_deserializer=grafeas.Occurrence.deserialize, + ) + return self._stubs['update_occurrence'] + + @property + def get_occurrence_note(self) -> Callable[ + [grafeas.GetOccurrenceNoteRequest], + grafeas.Note]: + r"""Return a callable for the get occurrence note method over gRPC. + + Gets the note attached to the specified occurrence. + Consumer projects can use this method to get a note that + belongs to a provider project. + + Returns: + Callable[[~.GetOccurrenceNoteRequest], + ~.Note]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_occurrence_note' not in self._stubs: + self._stubs['get_occurrence_note'] = self._logged_channel.unary_unary( + '/grafeas.v1.Grafeas/GetOccurrenceNote', + request_serializer=grafeas.GetOccurrenceNoteRequest.serialize, + response_deserializer=grafeas.Note.deserialize, + ) + return self._stubs['get_occurrence_note'] + + @property + def get_note(self) -> Callable[ + [grafeas.GetNoteRequest], + grafeas.Note]: + r"""Return a callable for the get note method over gRPC. + + Gets the specified note. + + Returns: + Callable[[~.GetNoteRequest], + ~.Note]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_note' not in self._stubs: + self._stubs['get_note'] = self._logged_channel.unary_unary( + '/grafeas.v1.Grafeas/GetNote', + request_serializer=grafeas.GetNoteRequest.serialize, + response_deserializer=grafeas.Note.deserialize, + ) + return self._stubs['get_note'] + + @property + def list_notes(self) -> Callable[ + [grafeas.ListNotesRequest], + grafeas.ListNotesResponse]: + r"""Return a callable for the list notes method over gRPC. + + Lists notes for the specified project. + + Returns: + Callable[[~.ListNotesRequest], + ~.ListNotesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_notes' not in self._stubs: + self._stubs['list_notes'] = self._logged_channel.unary_unary( + '/grafeas.v1.Grafeas/ListNotes', + request_serializer=grafeas.ListNotesRequest.serialize, + response_deserializer=grafeas.ListNotesResponse.deserialize, + ) + return self._stubs['list_notes'] + + @property + def delete_note(self) -> Callable[ + [grafeas.DeleteNoteRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete note method over gRPC. + + Deletes the specified note. + + Returns: + Callable[[~.DeleteNoteRequest], + ~.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_note' not in self._stubs: + self._stubs['delete_note'] = self._logged_channel.unary_unary( + '/grafeas.v1.Grafeas/DeleteNote', + request_serializer=grafeas.DeleteNoteRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_note'] + + @property + def create_note(self) -> Callable[ + [grafeas.CreateNoteRequest], + grafeas.Note]: + r"""Return a callable for the create note method over gRPC. + + Creates a new note. + + Returns: + Callable[[~.CreateNoteRequest], + ~.Note]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_note' not in self._stubs: + self._stubs['create_note'] = self._logged_channel.unary_unary( + '/grafeas.v1.Grafeas/CreateNote', + request_serializer=grafeas.CreateNoteRequest.serialize, + response_deserializer=grafeas.Note.deserialize, + ) + return self._stubs['create_note'] + + @property + def batch_create_notes(self) -> Callable[ + [grafeas.BatchCreateNotesRequest], + grafeas.BatchCreateNotesResponse]: + r"""Return a callable for the batch create notes method over gRPC. + + Creates new notes in batch. + + Returns: + Callable[[~.BatchCreateNotesRequest], + ~.BatchCreateNotesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_create_notes' not in self._stubs: + self._stubs['batch_create_notes'] = self._logged_channel.unary_unary( + '/grafeas.v1.Grafeas/BatchCreateNotes', + request_serializer=grafeas.BatchCreateNotesRequest.serialize, + response_deserializer=grafeas.BatchCreateNotesResponse.deserialize, + ) + return self._stubs['batch_create_notes'] + + @property + def update_note(self) -> Callable[ + [grafeas.UpdateNoteRequest], + grafeas.Note]: + r"""Return a callable for the update note method over gRPC. + + Updates the specified note. + + Returns: + Callable[[~.UpdateNoteRequest], + ~.Note]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_note' not in self._stubs: + self._stubs['update_note'] = self._logged_channel.unary_unary( + '/grafeas.v1.Grafeas/UpdateNote', + request_serializer=grafeas.UpdateNoteRequest.serialize, + response_deserializer=grafeas.Note.deserialize, + ) + return self._stubs['update_note'] + + @property + def list_note_occurrences(self) -> Callable[ + [grafeas.ListNoteOccurrencesRequest], + grafeas.ListNoteOccurrencesResponse]: + r"""Return a callable for the list note occurrences method over gRPC. + + Lists occurrences referencing the specified note. + Provider projects can use this method to get all + occurrences across consumer projects referencing the + specified note. + + Returns: + Callable[[~.ListNoteOccurrencesRequest], + ~.ListNoteOccurrencesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_note_occurrences' not in self._stubs: + self._stubs['list_note_occurrences'] = self._logged_channel.unary_unary( + '/grafeas.v1.Grafeas/ListNoteOccurrences', + request_serializer=grafeas.ListNoteOccurrencesRequest.serialize, + response_deserializer=grafeas.ListNoteOccurrencesResponse.deserialize, + ) + return self._stubs['list_note_occurrences'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'GrafeasGrpcTransport', +) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/grpc_asyncio.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/grpc_asyncio.py new file mode 100644 index 000000000000..3f476b208ac4 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/grpc_asyncio.py @@ -0,0 +1,873 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 grafeas.grafeas_v1.types import grafeas +from .base import GrafeasTransport, DEFAULT_CLIENT_INFO +from .grpc import GrafeasGrpcTransport + +try: + from google.api_core import client_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": "grafeas.v1.Grafeas", + "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": "grafeas.v1.Grafeas", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class GrafeasGrpcAsyncIOTransport(GrafeasTransport): + """gRPC AsyncIO backend transport for Grafeas. + + `Grafeas `__ API. + + Retrieves analysis results of Cloud components such as Docker + container images. + + Analysis results are stored as a series of occurrences. An + ``Occurrence`` contains information about a specific analysis + instance on a resource. An occurrence refers to a ``Note``. A note + contains details describing the analysis and is generally stored in + a separate project, called a ``Provider``. Multiple occurrences can + refer to the same note. + + For example, an SSL vulnerability could affect multiple images. In + this case, there would be one note for the vulnerability and an + occurrence for each image with the vulnerability referring to that + note. + + This 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 = 'containeranalysis.googleapis.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 = 'containeranalysis.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: 'containeranalysis.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to 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_occurrence(self) -> Callable[ + [grafeas.GetOccurrenceRequest], + Awaitable[grafeas.Occurrence]]: + r"""Return a callable for the get occurrence method over gRPC. + + Gets the specified occurrence. + + Returns: + Callable[[~.GetOccurrenceRequest], + Awaitable[~.Occurrence]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_occurrence' not in self._stubs: + self._stubs['get_occurrence'] = self._logged_channel.unary_unary( + '/grafeas.v1.Grafeas/GetOccurrence', + request_serializer=grafeas.GetOccurrenceRequest.serialize, + response_deserializer=grafeas.Occurrence.deserialize, + ) + return self._stubs['get_occurrence'] + + @property + def list_occurrences(self) -> Callable[ + [grafeas.ListOccurrencesRequest], + Awaitable[grafeas.ListOccurrencesResponse]]: + r"""Return a callable for the list occurrences method over gRPC. + + Lists occurrences for the specified project. + + Returns: + Callable[[~.ListOccurrencesRequest], + Awaitable[~.ListOccurrencesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_occurrences' not in self._stubs: + self._stubs['list_occurrences'] = self._logged_channel.unary_unary( + '/grafeas.v1.Grafeas/ListOccurrences', + request_serializer=grafeas.ListOccurrencesRequest.serialize, + response_deserializer=grafeas.ListOccurrencesResponse.deserialize, + ) + return self._stubs['list_occurrences'] + + @property + def delete_occurrence(self) -> Callable[ + [grafeas.DeleteOccurrenceRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete occurrence method over gRPC. + + Deletes the specified occurrence. For example, use + this method to delete an occurrence when the occurrence + is no longer applicable for the given resource. + + Returns: + Callable[[~.DeleteOccurrenceRequest], + 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_occurrence' not in self._stubs: + self._stubs['delete_occurrence'] = self._logged_channel.unary_unary( + '/grafeas.v1.Grafeas/DeleteOccurrence', + request_serializer=grafeas.DeleteOccurrenceRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_occurrence'] + + @property + def create_occurrence(self) -> Callable[ + [grafeas.CreateOccurrenceRequest], + Awaitable[grafeas.Occurrence]]: + r"""Return a callable for the create occurrence method over gRPC. + + Creates a new occurrence. + + Returns: + Callable[[~.CreateOccurrenceRequest], + Awaitable[~.Occurrence]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_occurrence' not in self._stubs: + self._stubs['create_occurrence'] = self._logged_channel.unary_unary( + '/grafeas.v1.Grafeas/CreateOccurrence', + request_serializer=grafeas.CreateOccurrenceRequest.serialize, + response_deserializer=grafeas.Occurrence.deserialize, + ) + return self._stubs['create_occurrence'] + + @property + def batch_create_occurrences(self) -> Callable[ + [grafeas.BatchCreateOccurrencesRequest], + Awaitable[grafeas.BatchCreateOccurrencesResponse]]: + r"""Return a callable for the batch create occurrences method over gRPC. + + Creates new occurrences in batch. + + Returns: + Callable[[~.BatchCreateOccurrencesRequest], + Awaitable[~.BatchCreateOccurrencesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_create_occurrences' not in self._stubs: + self._stubs['batch_create_occurrences'] = self._logged_channel.unary_unary( + '/grafeas.v1.Grafeas/BatchCreateOccurrences', + request_serializer=grafeas.BatchCreateOccurrencesRequest.serialize, + response_deserializer=grafeas.BatchCreateOccurrencesResponse.deserialize, + ) + return self._stubs['batch_create_occurrences'] + + @property + def update_occurrence(self) -> Callable[ + [grafeas.UpdateOccurrenceRequest], + Awaitable[grafeas.Occurrence]]: + r"""Return a callable for the update occurrence method over gRPC. + + Updates the specified occurrence. + + Returns: + Callable[[~.UpdateOccurrenceRequest], + Awaitable[~.Occurrence]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_occurrence' not in self._stubs: + self._stubs['update_occurrence'] = self._logged_channel.unary_unary( + '/grafeas.v1.Grafeas/UpdateOccurrence', + request_serializer=grafeas.UpdateOccurrenceRequest.serialize, + response_deserializer=grafeas.Occurrence.deserialize, + ) + return self._stubs['update_occurrence'] + + @property + def get_occurrence_note(self) -> Callable[ + [grafeas.GetOccurrenceNoteRequest], + Awaitable[grafeas.Note]]: + r"""Return a callable for the get occurrence note method over gRPC. + + Gets the note attached to the specified occurrence. + Consumer projects can use this method to get a note that + belongs to a provider project. + + Returns: + Callable[[~.GetOccurrenceNoteRequest], + Awaitable[~.Note]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_occurrence_note' not in self._stubs: + self._stubs['get_occurrence_note'] = self._logged_channel.unary_unary( + '/grafeas.v1.Grafeas/GetOccurrenceNote', + request_serializer=grafeas.GetOccurrenceNoteRequest.serialize, + response_deserializer=grafeas.Note.deserialize, + ) + return self._stubs['get_occurrence_note'] + + @property + def get_note(self) -> Callable[ + [grafeas.GetNoteRequest], + Awaitable[grafeas.Note]]: + r"""Return a callable for the get note method over gRPC. + + Gets the specified note. + + Returns: + Callable[[~.GetNoteRequest], + Awaitable[~.Note]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_note' not in self._stubs: + self._stubs['get_note'] = self._logged_channel.unary_unary( + '/grafeas.v1.Grafeas/GetNote', + request_serializer=grafeas.GetNoteRequest.serialize, + response_deserializer=grafeas.Note.deserialize, + ) + return self._stubs['get_note'] + + @property + def list_notes(self) -> Callable[ + [grafeas.ListNotesRequest], + Awaitable[grafeas.ListNotesResponse]]: + r"""Return a callable for the list notes method over gRPC. + + Lists notes for the specified project. + + Returns: + Callable[[~.ListNotesRequest], + Awaitable[~.ListNotesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_notes' not in self._stubs: + self._stubs['list_notes'] = self._logged_channel.unary_unary( + '/grafeas.v1.Grafeas/ListNotes', + request_serializer=grafeas.ListNotesRequest.serialize, + response_deserializer=grafeas.ListNotesResponse.deserialize, + ) + return self._stubs['list_notes'] + + @property + def delete_note(self) -> Callable[ + [grafeas.DeleteNoteRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete note method over gRPC. + + Deletes the specified note. + + Returns: + Callable[[~.DeleteNoteRequest], + 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_note' not in self._stubs: + self._stubs['delete_note'] = self._logged_channel.unary_unary( + '/grafeas.v1.Grafeas/DeleteNote', + request_serializer=grafeas.DeleteNoteRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_note'] + + @property + def create_note(self) -> Callable[ + [grafeas.CreateNoteRequest], + Awaitable[grafeas.Note]]: + r"""Return a callable for the create note method over gRPC. + + Creates a new note. + + Returns: + Callable[[~.CreateNoteRequest], + Awaitable[~.Note]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_note' not in self._stubs: + self._stubs['create_note'] = self._logged_channel.unary_unary( + '/grafeas.v1.Grafeas/CreateNote', + request_serializer=grafeas.CreateNoteRequest.serialize, + response_deserializer=grafeas.Note.deserialize, + ) + return self._stubs['create_note'] + + @property + def batch_create_notes(self) -> Callable[ + [grafeas.BatchCreateNotesRequest], + Awaitable[grafeas.BatchCreateNotesResponse]]: + r"""Return a callable for the batch create notes method over gRPC. + + Creates new notes in batch. + + Returns: + Callable[[~.BatchCreateNotesRequest], + Awaitable[~.BatchCreateNotesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_create_notes' not in self._stubs: + self._stubs['batch_create_notes'] = self._logged_channel.unary_unary( + '/grafeas.v1.Grafeas/BatchCreateNotes', + request_serializer=grafeas.BatchCreateNotesRequest.serialize, + response_deserializer=grafeas.BatchCreateNotesResponse.deserialize, + ) + return self._stubs['batch_create_notes'] + + @property + def update_note(self) -> Callable[ + [grafeas.UpdateNoteRequest], + Awaitable[grafeas.Note]]: + r"""Return a callable for the update note method over gRPC. + + Updates the specified note. + + Returns: + Callable[[~.UpdateNoteRequest], + Awaitable[~.Note]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_note' not in self._stubs: + self._stubs['update_note'] = self._logged_channel.unary_unary( + '/grafeas.v1.Grafeas/UpdateNote', + request_serializer=grafeas.UpdateNoteRequest.serialize, + response_deserializer=grafeas.Note.deserialize, + ) + return self._stubs['update_note'] + + @property + def list_note_occurrences(self) -> Callable[ + [grafeas.ListNoteOccurrencesRequest], + Awaitable[grafeas.ListNoteOccurrencesResponse]]: + r"""Return a callable for the list note occurrences method over gRPC. + + Lists occurrences referencing the specified note. + Provider projects can use this method to get all + occurrences across consumer projects referencing the + specified note. + + Returns: + Callable[[~.ListNoteOccurrencesRequest], + Awaitable[~.ListNoteOccurrencesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_note_occurrences' not in self._stubs: + self._stubs['list_note_occurrences'] = self._logged_channel.unary_unary( + '/grafeas.v1.Grafeas/ListNoteOccurrences', + request_serializer=grafeas.ListNoteOccurrencesRequest.serialize, + response_deserializer=grafeas.ListNoteOccurrencesResponse.deserialize, + ) + return self._stubs['list_note_occurrences'] + + 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_occurrence: self._wrap_method( + self.get_occurrence, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.list_occurrences: self._wrap_method( + self.list_occurrences, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.delete_occurrence: self._wrap_method( + self.delete_occurrence, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.create_occurrence: self._wrap_method( + self.create_occurrence, + default_timeout=30.0, + client_info=client_info, + ), + self.batch_create_occurrences: self._wrap_method( + self.batch_create_occurrences, + default_timeout=30.0, + client_info=client_info, + ), + self.update_occurrence: self._wrap_method( + self.update_occurrence, + default_timeout=30.0, + client_info=client_info, + ), + self.get_occurrence_note: self._wrap_method( + self.get_occurrence_note, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.get_note: self._wrap_method( + self.get_note, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.list_notes: self._wrap_method( + self.list_notes, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.delete_note: self._wrap_method( + self.delete_note, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.create_note: self._wrap_method( + self.create_note, + default_timeout=30.0, + client_info=client_info, + ), + self.batch_create_notes: self._wrap_method( + self.batch_create_notes, + default_timeout=30.0, + client_info=client_info, + ), + self.update_note: self._wrap_method( + self.update_note, + default_timeout=30.0, + client_info=client_info, + ), + self.list_note_occurrences: self._wrap_method( + self.list_note_occurrences, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + 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__ = ( + 'GrafeasGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/rest.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/rest.py new file mode 100644 index 000000000000..6733a8041d21 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/rest.py @@ -0,0 +1,2241 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +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 grafeas.grafeas_v1.types import grafeas + + +from .rest_base import _BaseGrafeasRestTransport +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}", +) + + +class GrafeasRestInterceptor: + """Interceptor for Grafeas. + + 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 GrafeasRestTransport. + + .. code-block:: python + class MyCustomGrafeasInterceptor(GrafeasRestInterceptor): + def pre_batch_create_notes(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_create_notes(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_batch_create_occurrences(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_create_occurrences(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_note(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_note(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_occurrence(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_occurrence(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_note(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_occurrence(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_note(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_note(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_occurrence(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_occurrence(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_occurrence_note(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_occurrence_note(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_note_occurrences(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_note_occurrences(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_notes(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_notes(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_occurrences(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_occurrences(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_note(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_note(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_occurrence(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_occurrence(self, response): + logging.log(f"Received response: {response}") + return response + + transport = GrafeasRestTransport(interceptor=MyCustomGrafeasInterceptor()) + client = GrafeasClient(transport=transport) + + + """ + def pre_batch_create_notes(self, request: grafeas.BatchCreateNotesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[grafeas.BatchCreateNotesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for batch_create_notes + + Override in a subclass to manipulate the request or metadata + before they are sent to the Grafeas server. + """ + return request, metadata + + def post_batch_create_notes(self, response: grafeas.BatchCreateNotesResponse) -> grafeas.BatchCreateNotesResponse: + """Post-rpc interceptor for batch_create_notes + + Override in a subclass to manipulate the response + after it is returned by the Grafeas server but before + it is returned to user code. + """ + return response + + def pre_batch_create_occurrences(self, request: grafeas.BatchCreateOccurrencesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[grafeas.BatchCreateOccurrencesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for batch_create_occurrences + + Override in a subclass to manipulate the request or metadata + before they are sent to the Grafeas server. + """ + return request, metadata + + def post_batch_create_occurrences(self, response: grafeas.BatchCreateOccurrencesResponse) -> grafeas.BatchCreateOccurrencesResponse: + """Post-rpc interceptor for batch_create_occurrences + + Override in a subclass to manipulate the response + after it is returned by the Grafeas server but before + it is returned to user code. + """ + return response + + def pre_create_note(self, request: grafeas.CreateNoteRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[grafeas.CreateNoteRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_note + + Override in a subclass to manipulate the request or metadata + before they are sent to the Grafeas server. + """ + return request, metadata + + def post_create_note(self, response: grafeas.Note) -> grafeas.Note: + """Post-rpc interceptor for create_note + + Override in a subclass to manipulate the response + after it is returned by the Grafeas server but before + it is returned to user code. + """ + return response + + def pre_create_occurrence(self, request: grafeas.CreateOccurrenceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[grafeas.CreateOccurrenceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_occurrence + + Override in a subclass to manipulate the request or metadata + before they are sent to the Grafeas server. + """ + return request, metadata + + def post_create_occurrence(self, response: grafeas.Occurrence) -> grafeas.Occurrence: + """Post-rpc interceptor for create_occurrence + + Override in a subclass to manipulate the response + after it is returned by the Grafeas server but before + it is returned to user code. + """ + return response + + def pre_delete_note(self, request: grafeas.DeleteNoteRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[grafeas.DeleteNoteRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_note + + Override in a subclass to manipulate the request or metadata + before they are sent to the Grafeas server. + """ + return request, metadata + + def pre_delete_occurrence(self, request: grafeas.DeleteOccurrenceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[grafeas.DeleteOccurrenceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_occurrence + + Override in a subclass to manipulate the request or metadata + before they are sent to the Grafeas server. + """ + return request, metadata + + def pre_get_note(self, request: grafeas.GetNoteRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[grafeas.GetNoteRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_note + + Override in a subclass to manipulate the request or metadata + before they are sent to the Grafeas server. + """ + return request, metadata + + def post_get_note(self, response: grafeas.Note) -> grafeas.Note: + """Post-rpc interceptor for get_note + + Override in a subclass to manipulate the response + after it is returned by the Grafeas server but before + it is returned to user code. + """ + return response + + def pre_get_occurrence(self, request: grafeas.GetOccurrenceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[grafeas.GetOccurrenceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_occurrence + + Override in a subclass to manipulate the request or metadata + before they are sent to the Grafeas server. + """ + return request, metadata + + def post_get_occurrence(self, response: grafeas.Occurrence) -> grafeas.Occurrence: + """Post-rpc interceptor for get_occurrence + + Override in a subclass to manipulate the response + after it is returned by the Grafeas server but before + it is returned to user code. + """ + return response + + def pre_get_occurrence_note(self, request: grafeas.GetOccurrenceNoteRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[grafeas.GetOccurrenceNoteRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_occurrence_note + + Override in a subclass to manipulate the request or metadata + before they are sent to the Grafeas server. + """ + return request, metadata + + def post_get_occurrence_note(self, response: grafeas.Note) -> grafeas.Note: + """Post-rpc interceptor for get_occurrence_note + + Override in a subclass to manipulate the response + after it is returned by the Grafeas server but before + it is returned to user code. + """ + return response + + def pre_list_note_occurrences(self, request: grafeas.ListNoteOccurrencesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[grafeas.ListNoteOccurrencesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_note_occurrences + + Override in a subclass to manipulate the request or metadata + before they are sent to the Grafeas server. + """ + return request, metadata + + def post_list_note_occurrences(self, response: grafeas.ListNoteOccurrencesResponse) -> grafeas.ListNoteOccurrencesResponse: + """Post-rpc interceptor for list_note_occurrences + + Override in a subclass to manipulate the response + after it is returned by the Grafeas server but before + it is returned to user code. + """ + return response + + def pre_list_notes(self, request: grafeas.ListNotesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[grafeas.ListNotesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_notes + + Override in a subclass to manipulate the request or metadata + before they are sent to the Grafeas server. + """ + return request, metadata + + def post_list_notes(self, response: grafeas.ListNotesResponse) -> grafeas.ListNotesResponse: + """Post-rpc interceptor for list_notes + + Override in a subclass to manipulate the response + after it is returned by the Grafeas server but before + it is returned to user code. + """ + return response + + def pre_list_occurrences(self, request: grafeas.ListOccurrencesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[grafeas.ListOccurrencesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_occurrences + + Override in a subclass to manipulate the request or metadata + before they are sent to the Grafeas server. + """ + return request, metadata + + def post_list_occurrences(self, response: grafeas.ListOccurrencesResponse) -> grafeas.ListOccurrencesResponse: + """Post-rpc interceptor for list_occurrences + + Override in a subclass to manipulate the response + after it is returned by the Grafeas server but before + it is returned to user code. + """ + return response + + def pre_update_note(self, request: grafeas.UpdateNoteRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[grafeas.UpdateNoteRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_note + + Override in a subclass to manipulate the request or metadata + before they are sent to the Grafeas server. + """ + return request, metadata + + def post_update_note(self, response: grafeas.Note) -> grafeas.Note: + """Post-rpc interceptor for update_note + + Override in a subclass to manipulate the response + after it is returned by the Grafeas server but before + it is returned to user code. + """ + return response + + def pre_update_occurrence(self, request: grafeas.UpdateOccurrenceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[grafeas.UpdateOccurrenceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_occurrence + + Override in a subclass to manipulate the request or metadata + before they are sent to the Grafeas server. + """ + return request, metadata + + def post_update_occurrence(self, response: grafeas.Occurrence) -> grafeas.Occurrence: + """Post-rpc interceptor for update_occurrence + + Override in a subclass to manipulate the response + after it is returned by the Grafeas server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class GrafeasRestStub: + _session: AuthorizedSession + _host: str + _interceptor: GrafeasRestInterceptor + + +class GrafeasRestTransport(_BaseGrafeasRestTransport): + """REST backend synchronous transport for Grafeas. + + `Grafeas `__ API. + + Retrieves analysis results of Cloud components such as Docker + container images. + + Analysis results are stored as a series of occurrences. An + ``Occurrence`` contains information about a specific analysis + instance on a resource. An occurrence refers to a ``Note``. A note + contains details describing the analysis and is generally stored in + a separate project, called a ``Provider``. Multiple occurrences can + refer to the same note. + + For example, an SSL vulnerability could affect multiple images. In + this case, there would be one note for the vulnerability and an + occurrence for each image with the vulnerability referring to that + note. + + This 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 = 'containeranalysis.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[GrafeasRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'containeranalysis.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to 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 GrafeasRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _BatchCreateNotes(_BaseGrafeasRestTransport._BaseBatchCreateNotes, GrafeasRestStub): + def __hash__(self): + return hash("GrafeasRestTransport.BatchCreateNotes") + + @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: grafeas.BatchCreateNotesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> grafeas.BatchCreateNotesResponse: + r"""Call the batch create notes method over HTTP. + + Args: + request (~.grafeas.BatchCreateNotesRequest): + The request object. Request to create notes in batch. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.grafeas.BatchCreateNotesResponse: + Response for creating notes in batch. + """ + + http_options = _BaseGrafeasRestTransport._BaseBatchCreateNotes._get_http_options() + + request, metadata = self._interceptor.pre_batch_create_notes(request, metadata) + transcoded_request = _BaseGrafeasRestTransport._BaseBatchCreateNotes._get_transcoded_request(http_options, request) + + body = _BaseGrafeasRestTransport._BaseBatchCreateNotes._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseGrafeasRestTransport._BaseBatchCreateNotes._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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 grafeas_v1.GrafeasClient.BatchCreateNotes", + extra = { + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "BatchCreateNotes", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GrafeasRestTransport._BatchCreateNotes._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 = grafeas.BatchCreateNotesResponse() + pb_resp = grafeas.BatchCreateNotesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_batch_create_notes(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = grafeas.BatchCreateNotesResponse.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 grafeas_v1.GrafeasClient.batch_create_notes", + extra = { + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "BatchCreateNotes", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _BatchCreateOccurrences(_BaseGrafeasRestTransport._BaseBatchCreateOccurrences, GrafeasRestStub): + def __hash__(self): + return hash("GrafeasRestTransport.BatchCreateOccurrences") + + @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: grafeas.BatchCreateOccurrencesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> grafeas.BatchCreateOccurrencesResponse: + r"""Call the batch create occurrences method over HTTP. + + Args: + request (~.grafeas.BatchCreateOccurrencesRequest): + The request object. Request to create occurrences in + batch. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.grafeas.BatchCreateOccurrencesResponse: + Response for creating occurrences in + batch. + + """ + + http_options = _BaseGrafeasRestTransport._BaseBatchCreateOccurrences._get_http_options() + + request, metadata = self._interceptor.pre_batch_create_occurrences(request, metadata) + transcoded_request = _BaseGrafeasRestTransport._BaseBatchCreateOccurrences._get_transcoded_request(http_options, request) + + body = _BaseGrafeasRestTransport._BaseBatchCreateOccurrences._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseGrafeasRestTransport._BaseBatchCreateOccurrences._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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 grafeas_v1.GrafeasClient.BatchCreateOccurrences", + extra = { + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "BatchCreateOccurrences", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GrafeasRestTransport._BatchCreateOccurrences._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 = grafeas.BatchCreateOccurrencesResponse() + pb_resp = grafeas.BatchCreateOccurrencesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_batch_create_occurrences(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = grafeas.BatchCreateOccurrencesResponse.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 grafeas_v1.GrafeasClient.batch_create_occurrences", + extra = { + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "BatchCreateOccurrences", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateNote(_BaseGrafeasRestTransport._BaseCreateNote, GrafeasRestStub): + def __hash__(self): + return hash("GrafeasRestTransport.CreateNote") + + @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: grafeas.CreateNoteRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> grafeas.Note: + r"""Call the create note method over HTTP. + + Args: + request (~.grafeas.CreateNoteRequest): + The request object. Request to create a new note. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.grafeas.Note: + A type of analysis that can be done + for a resource. + + """ + + http_options = _BaseGrafeasRestTransport._BaseCreateNote._get_http_options() + + request, metadata = self._interceptor.pre_create_note(request, metadata) + transcoded_request = _BaseGrafeasRestTransport._BaseCreateNote._get_transcoded_request(http_options, request) + + body = _BaseGrafeasRestTransport._BaseCreateNote._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseGrafeasRestTransport._BaseCreateNote._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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 grafeas_v1.GrafeasClient.CreateNote", + extra = { + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "CreateNote", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GrafeasRestTransport._CreateNote._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 = grafeas.Note() + pb_resp = grafeas.Note.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_note(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = grafeas.Note.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 grafeas_v1.GrafeasClient.create_note", + extra = { + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "CreateNote", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateOccurrence(_BaseGrafeasRestTransport._BaseCreateOccurrence, GrafeasRestStub): + def __hash__(self): + return hash("GrafeasRestTransport.CreateOccurrence") + + @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: grafeas.CreateOccurrenceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> grafeas.Occurrence: + r"""Call the create occurrence method over HTTP. + + Args: + request (~.grafeas.CreateOccurrenceRequest): + The request object. Request to create a new occurrence. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.grafeas.Occurrence: + An instance of an analysis type that + has been found on a resource. + + """ + + http_options = _BaseGrafeasRestTransport._BaseCreateOccurrence._get_http_options() + + request, metadata = self._interceptor.pre_create_occurrence(request, metadata) + transcoded_request = _BaseGrafeasRestTransport._BaseCreateOccurrence._get_transcoded_request(http_options, request) + + body = _BaseGrafeasRestTransport._BaseCreateOccurrence._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseGrafeasRestTransport._BaseCreateOccurrence._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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 grafeas_v1.GrafeasClient.CreateOccurrence", + extra = { + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "CreateOccurrence", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GrafeasRestTransport._CreateOccurrence._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 = grafeas.Occurrence() + pb_resp = grafeas.Occurrence.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_occurrence(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = grafeas.Occurrence.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 grafeas_v1.GrafeasClient.create_occurrence", + extra = { + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "CreateOccurrence", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteNote(_BaseGrafeasRestTransport._BaseDeleteNote, GrafeasRestStub): + def __hash__(self): + return hash("GrafeasRestTransport.DeleteNote") + + @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: grafeas.DeleteNoteRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): + r"""Call the delete note method over HTTP. + + Args: + request (~.grafeas.DeleteNoteRequest): + The request object. Request to delete a note. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 = _BaseGrafeasRestTransport._BaseDeleteNote._get_http_options() + + request, metadata = self._interceptor.pre_delete_note(request, metadata) + transcoded_request = _BaseGrafeasRestTransport._BaseDeleteNote._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseGrafeasRestTransport._BaseDeleteNote._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(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 grafeas_v1.GrafeasClient.DeleteNote", + extra = { + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "DeleteNote", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GrafeasRestTransport._DeleteNote._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 _DeleteOccurrence(_BaseGrafeasRestTransport._BaseDeleteOccurrence, GrafeasRestStub): + def __hash__(self): + return hash("GrafeasRestTransport.DeleteOccurrence") + + @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: grafeas.DeleteOccurrenceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): + r"""Call the delete occurrence method over HTTP. + + Args: + request (~.grafeas.DeleteOccurrenceRequest): + The request object. Request to delete an occurrence. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 = _BaseGrafeasRestTransport._BaseDeleteOccurrence._get_http_options() + + request, metadata = self._interceptor.pre_delete_occurrence(request, metadata) + transcoded_request = _BaseGrafeasRestTransport._BaseDeleteOccurrence._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseGrafeasRestTransport._BaseDeleteOccurrence._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(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 grafeas_v1.GrafeasClient.DeleteOccurrence", + extra = { + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "DeleteOccurrence", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GrafeasRestTransport._DeleteOccurrence._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 _GetNote(_BaseGrafeasRestTransport._BaseGetNote, GrafeasRestStub): + def __hash__(self): + return hash("GrafeasRestTransport.GetNote") + + @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: grafeas.GetNoteRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> grafeas.Note: + r"""Call the get note method over HTTP. + + Args: + request (~.grafeas.GetNoteRequest): + The request object. Request to get a note. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.grafeas.Note: + A type of analysis that can be done + for a resource. + + """ + + http_options = _BaseGrafeasRestTransport._BaseGetNote._get_http_options() + + request, metadata = self._interceptor.pre_get_note(request, metadata) + transcoded_request = _BaseGrafeasRestTransport._BaseGetNote._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseGrafeasRestTransport._BaseGetNote._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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 grafeas_v1.GrafeasClient.GetNote", + extra = { + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "GetNote", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GrafeasRestTransport._GetNote._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 = grafeas.Note() + pb_resp = grafeas.Note.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_note(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = grafeas.Note.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 grafeas_v1.GrafeasClient.get_note", + extra = { + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "GetNote", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetOccurrence(_BaseGrafeasRestTransport._BaseGetOccurrence, GrafeasRestStub): + def __hash__(self): + return hash("GrafeasRestTransport.GetOccurrence") + + @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: grafeas.GetOccurrenceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> grafeas.Occurrence: + r"""Call the get occurrence method over HTTP. + + Args: + request (~.grafeas.GetOccurrenceRequest): + The request object. Request to get an occurrence. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.grafeas.Occurrence: + An instance of an analysis type that + has been found on a resource. + + """ + + http_options = _BaseGrafeasRestTransport._BaseGetOccurrence._get_http_options() + + request, metadata = self._interceptor.pre_get_occurrence(request, metadata) + transcoded_request = _BaseGrafeasRestTransport._BaseGetOccurrence._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseGrafeasRestTransport._BaseGetOccurrence._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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 grafeas_v1.GrafeasClient.GetOccurrence", + extra = { + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "GetOccurrence", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GrafeasRestTransport._GetOccurrence._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 = grafeas.Occurrence() + pb_resp = grafeas.Occurrence.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_occurrence(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = grafeas.Occurrence.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 grafeas_v1.GrafeasClient.get_occurrence", + extra = { + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "GetOccurrence", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetOccurrenceNote(_BaseGrafeasRestTransport._BaseGetOccurrenceNote, GrafeasRestStub): + def __hash__(self): + return hash("GrafeasRestTransport.GetOccurrenceNote") + + @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: grafeas.GetOccurrenceNoteRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> grafeas.Note: + r"""Call the get occurrence note method over HTTP. + + Args: + request (~.grafeas.GetOccurrenceNoteRequest): + The request object. Request to get the note to which the + specified occurrence is attached. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.grafeas.Note: + A type of analysis that can be done + for a resource. + + """ + + http_options = _BaseGrafeasRestTransport._BaseGetOccurrenceNote._get_http_options() + + request, metadata = self._interceptor.pre_get_occurrence_note(request, metadata) + transcoded_request = _BaseGrafeasRestTransport._BaseGetOccurrenceNote._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseGrafeasRestTransport._BaseGetOccurrenceNote._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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 grafeas_v1.GrafeasClient.GetOccurrenceNote", + extra = { + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "GetOccurrenceNote", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GrafeasRestTransport._GetOccurrenceNote._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 = grafeas.Note() + pb_resp = grafeas.Note.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_occurrence_note(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = grafeas.Note.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 grafeas_v1.GrafeasClient.get_occurrence_note", + extra = { + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "GetOccurrenceNote", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListNoteOccurrences(_BaseGrafeasRestTransport._BaseListNoteOccurrences, GrafeasRestStub): + def __hash__(self): + return hash("GrafeasRestTransport.ListNoteOccurrences") + + @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: grafeas.ListNoteOccurrencesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> grafeas.ListNoteOccurrencesResponse: + r"""Call the list note occurrences method over HTTP. + + Args: + request (~.grafeas.ListNoteOccurrencesRequest): + The request object. Request to list occurrences for a + note. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.grafeas.ListNoteOccurrencesResponse: + Response for listing occurrences for + a note. + + """ + + http_options = _BaseGrafeasRestTransport._BaseListNoteOccurrences._get_http_options() + + request, metadata = self._interceptor.pre_list_note_occurrences(request, metadata) + transcoded_request = _BaseGrafeasRestTransport._BaseListNoteOccurrences._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseGrafeasRestTransport._BaseListNoteOccurrences._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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 grafeas_v1.GrafeasClient.ListNoteOccurrences", + extra = { + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "ListNoteOccurrences", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GrafeasRestTransport._ListNoteOccurrences._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 = grafeas.ListNoteOccurrencesResponse() + pb_resp = grafeas.ListNoteOccurrencesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_note_occurrences(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = grafeas.ListNoteOccurrencesResponse.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 grafeas_v1.GrafeasClient.list_note_occurrences", + extra = { + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "ListNoteOccurrences", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListNotes(_BaseGrafeasRestTransport._BaseListNotes, GrafeasRestStub): + def __hash__(self): + return hash("GrafeasRestTransport.ListNotes") + + @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: grafeas.ListNotesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> grafeas.ListNotesResponse: + r"""Call the list notes method over HTTP. + + Args: + request (~.grafeas.ListNotesRequest): + The request object. Request to list notes. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.grafeas.ListNotesResponse: + Response for listing notes. + """ + + http_options = _BaseGrafeasRestTransport._BaseListNotes._get_http_options() + + request, metadata = self._interceptor.pre_list_notes(request, metadata) + transcoded_request = _BaseGrafeasRestTransport._BaseListNotes._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseGrafeasRestTransport._BaseListNotes._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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 grafeas_v1.GrafeasClient.ListNotes", + extra = { + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "ListNotes", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GrafeasRestTransport._ListNotes._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 = grafeas.ListNotesResponse() + pb_resp = grafeas.ListNotesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_notes(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = grafeas.ListNotesResponse.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 grafeas_v1.GrafeasClient.list_notes", + extra = { + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "ListNotes", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListOccurrences(_BaseGrafeasRestTransport._BaseListOccurrences, GrafeasRestStub): + def __hash__(self): + return hash("GrafeasRestTransport.ListOccurrences") + + @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: grafeas.ListOccurrencesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> grafeas.ListOccurrencesResponse: + r"""Call the list occurrences method over HTTP. + + Args: + request (~.grafeas.ListOccurrencesRequest): + The request object. Request to list occurrences. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.grafeas.ListOccurrencesResponse: + Response for listing occurrences. + """ + + http_options = _BaseGrafeasRestTransport._BaseListOccurrences._get_http_options() + + request, metadata = self._interceptor.pre_list_occurrences(request, metadata) + transcoded_request = _BaseGrafeasRestTransport._BaseListOccurrences._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseGrafeasRestTransport._BaseListOccurrences._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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 grafeas_v1.GrafeasClient.ListOccurrences", + extra = { + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "ListOccurrences", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GrafeasRestTransport._ListOccurrences._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 = grafeas.ListOccurrencesResponse() + pb_resp = grafeas.ListOccurrencesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_occurrences(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = grafeas.ListOccurrencesResponse.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 grafeas_v1.GrafeasClient.list_occurrences", + extra = { + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "ListOccurrences", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateNote(_BaseGrafeasRestTransport._BaseUpdateNote, GrafeasRestStub): + def __hash__(self): + return hash("GrafeasRestTransport.UpdateNote") + + @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: grafeas.UpdateNoteRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> grafeas.Note: + r"""Call the update note method over HTTP. + + Args: + request (~.grafeas.UpdateNoteRequest): + The request object. Request to update a note. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.grafeas.Note: + A type of analysis that can be done + for a resource. + + """ + + http_options = _BaseGrafeasRestTransport._BaseUpdateNote._get_http_options() + + request, metadata = self._interceptor.pre_update_note(request, metadata) + transcoded_request = _BaseGrafeasRestTransport._BaseUpdateNote._get_transcoded_request(http_options, request) + + body = _BaseGrafeasRestTransport._BaseUpdateNote._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseGrafeasRestTransport._BaseUpdateNote._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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 grafeas_v1.GrafeasClient.UpdateNote", + extra = { + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "UpdateNote", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GrafeasRestTransport._UpdateNote._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 = grafeas.Note() + pb_resp = grafeas.Note.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_note(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = grafeas.Note.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 grafeas_v1.GrafeasClient.update_note", + extra = { + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "UpdateNote", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateOccurrence(_BaseGrafeasRestTransport._BaseUpdateOccurrence, GrafeasRestStub): + def __hash__(self): + return hash("GrafeasRestTransport.UpdateOccurrence") + + @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: grafeas.UpdateOccurrenceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> grafeas.Occurrence: + r"""Call the update occurrence method over HTTP. + + Args: + request (~.grafeas.UpdateOccurrenceRequest): + The request object. Request to update an occurrence. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.grafeas.Occurrence: + An instance of an analysis type that + has been found on a resource. + + """ + + http_options = _BaseGrafeasRestTransport._BaseUpdateOccurrence._get_http_options() + + request, metadata = self._interceptor.pre_update_occurrence(request, metadata) + transcoded_request = _BaseGrafeasRestTransport._BaseUpdateOccurrence._get_transcoded_request(http_options, request) + + body = _BaseGrafeasRestTransport._BaseUpdateOccurrence._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseGrafeasRestTransport._BaseUpdateOccurrence._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + 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 grafeas_v1.GrafeasClient.UpdateOccurrence", + extra = { + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "UpdateOccurrence", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GrafeasRestTransport._UpdateOccurrence._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 = grafeas.Occurrence() + pb_resp = grafeas.Occurrence.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_occurrence(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = grafeas.Occurrence.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 grafeas_v1.GrafeasClient.update_occurrence", + extra = { + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "UpdateOccurrence", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def batch_create_notes(self) -> Callable[ + [grafeas.BatchCreateNotesRequest], + grafeas.BatchCreateNotesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchCreateNotes(self._session, self._host, self._interceptor) # type: ignore + + @property + def batch_create_occurrences(self) -> Callable[ + [grafeas.BatchCreateOccurrencesRequest], + grafeas.BatchCreateOccurrencesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchCreateOccurrences(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_note(self) -> Callable[ + [grafeas.CreateNoteRequest], + grafeas.Note]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateNote(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_occurrence(self) -> Callable[ + [grafeas.CreateOccurrenceRequest], + grafeas.Occurrence]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateOccurrence(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_note(self) -> Callable[ + [grafeas.DeleteNoteRequest], + 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._DeleteNote(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_occurrence(self) -> Callable[ + [grafeas.DeleteOccurrenceRequest], + 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._DeleteOccurrence(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_note(self) -> Callable[ + [grafeas.GetNoteRequest], + grafeas.Note]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetNote(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_occurrence(self) -> Callable[ + [grafeas.GetOccurrenceRequest], + grafeas.Occurrence]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetOccurrence(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_occurrence_note(self) -> Callable[ + [grafeas.GetOccurrenceNoteRequest], + grafeas.Note]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetOccurrenceNote(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_note_occurrences(self) -> Callable[ + [grafeas.ListNoteOccurrencesRequest], + grafeas.ListNoteOccurrencesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListNoteOccurrences(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_notes(self) -> Callable[ + [grafeas.ListNotesRequest], + grafeas.ListNotesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListNotes(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_occurrences(self) -> Callable[ + [grafeas.ListOccurrencesRequest], + grafeas.ListOccurrencesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListOccurrences(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_note(self) -> Callable[ + [grafeas.UpdateNoteRequest], + grafeas.Note]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateNote(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_occurrence(self) -> Callable[ + [grafeas.UpdateOccurrenceRequest], + grafeas.Occurrence]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateOccurrence(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'GrafeasRestTransport', +) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/rest_base.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/rest_base.py new file mode 100644 index 000000000000..64f998e72c3e --- /dev/null +++ b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/rest_base.py @@ -0,0 +1,732 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 GrafeasTransport, 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 grafeas.grafeas_v1.types import grafeas + + +class _BaseGrafeasRestTransport(GrafeasTransport): + """Base REST backend transport for Grafeas. + + 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 = 'containeranalysis.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: 'containeranalysis.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 _BaseBatchCreateNotes: + 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': '/v1/{parent=projects/*}/notes:batchCreate', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/notes:batchCreate', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = grafeas.BatchCreateNotesRequest.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(_BaseGrafeasRestTransport._BaseBatchCreateNotes._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseBatchCreateOccurrences: + 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': '/v1/{parent=projects/*}/occurrences:batchCreate', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/occurrences:batchCreate', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = grafeas.BatchCreateOccurrencesRequest.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(_BaseGrafeasRestTransport._BaseBatchCreateOccurrences._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateNote: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "noteId" : "", } + + @classmethod + def _get_unset_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': '/v1/{parent=projects/*}/notes', + 'body': 'note', + }, + { + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/notes', + 'body': 'note', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = grafeas.CreateNoteRequest.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(_BaseGrafeasRestTransport._BaseCreateNote._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateOccurrence: + 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': '/v1/{parent=projects/*}/occurrences', + 'body': 'occurrence', + }, + { + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/occurrences', + 'body': 'occurrence', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = grafeas.CreateOccurrenceRequest.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(_BaseGrafeasRestTransport._BaseCreateOccurrence._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteNote: + 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': '/v1/{name=projects/*/notes/*}', + }, + { + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/notes/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = grafeas.DeleteNoteRequest.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(_BaseGrafeasRestTransport._BaseDeleteNote._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteOccurrence: + 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': '/v1/{name=projects/*/occurrences/*}', + }, + { + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/occurrences/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = grafeas.DeleteOccurrenceRequest.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(_BaseGrafeasRestTransport._BaseDeleteOccurrence._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetNote: + 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': '/v1/{name=projects/*/notes/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/notes/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = grafeas.GetNoteRequest.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(_BaseGrafeasRestTransport._BaseGetNote._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOccurrence: + 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': '/v1/{name=projects/*/occurrences/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/occurrences/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = grafeas.GetOccurrenceRequest.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(_BaseGrafeasRestTransport._BaseGetOccurrence._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOccurrenceNote: + 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': '/v1/{name=projects/*/occurrences/*}/notes', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/occurrences/*}/notes', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = grafeas.GetOccurrenceNoteRequest.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(_BaseGrafeasRestTransport._BaseGetOccurrenceNote._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListNoteOccurrences: + 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': '/v1/{name=projects/*/notes/*}/occurrences', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/notes/*}/occurrences', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = grafeas.ListNoteOccurrencesRequest.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(_BaseGrafeasRestTransport._BaseListNoteOccurrences._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListNotes: + 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': '/v1/{parent=projects/*}/notes', + }, + { + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/notes', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = grafeas.ListNotesRequest.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(_BaseGrafeasRestTransport._BaseListNotes._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListOccurrences: + 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': '/v1/{parent=projects/*}/occurrences', + }, + { + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/occurrences', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = grafeas.ListOccurrencesRequest.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(_BaseGrafeasRestTransport._BaseListOccurrences._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateNote: + 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': '/v1/{name=projects/*/notes/*}', + 'body': 'note', + }, + { + 'method': 'patch', + 'uri': '/v1/{name=projects/*/locations/*/notes/*}', + 'body': 'note', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = grafeas.UpdateNoteRequest.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(_BaseGrafeasRestTransport._BaseUpdateNote._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateOccurrence: + 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': '/v1/{name=projects/*/occurrences/*}', + 'body': 'occurrence', + }, + { + 'method': 'patch', + 'uri': '/v1/{name=projects/*/locations/*/occurrences/*}', + 'body': 'occurrence', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = grafeas.UpdateOccurrenceRequest.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(_BaseGrafeasRestTransport._BaseUpdateOccurrence._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseGrafeasRestTransport', +) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/__init__.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/__init__.py new file mode 100644 index 000000000000..76e667190447 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/__init__.py @@ -0,0 +1,244 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .attestation import ( + AttestationNote, + AttestationOccurrence, + Jwt, +) +from .build import ( + BuildNote, + BuildOccurrence, +) +from .common import ( + Digest, + Envelope, + EnvelopeSignature, + FileLocation, + License, + RelatedUrl, + Signature, + NoteKind, +) +from .compliance import ( + ComplianceNote, + ComplianceOccurrence, + ComplianceVersion, + NonCompliantFile, +) +from .cvss import ( + CVSS, + CVSSv3, + CVSSVersion, +) +from .deployment import ( + DeploymentNote, + DeploymentOccurrence, +) +from .discovery import ( + DiscoveryNote, + DiscoveryOccurrence, +) +from .dsse_attestation import ( + DSSEAttestationNote, + DSSEAttestationOccurrence, +) +from .grafeas import ( + BatchCreateNotesRequest, + BatchCreateNotesResponse, + BatchCreateOccurrencesRequest, + BatchCreateOccurrencesResponse, + CreateNoteRequest, + CreateOccurrenceRequest, + DeleteNoteRequest, + DeleteOccurrenceRequest, + GetNoteRequest, + GetOccurrenceNoteRequest, + GetOccurrenceRequest, + ListNoteOccurrencesRequest, + ListNoteOccurrencesResponse, + ListNotesRequest, + ListNotesResponse, + ListOccurrencesRequest, + ListOccurrencesResponse, + Note, + Occurrence, + UpdateNoteRequest, + UpdateOccurrenceRequest, +) +from .image import ( + Fingerprint, + ImageNote, + ImageOccurrence, + Layer, +) +from .intoto_provenance import ( + BuilderConfig, + Completeness, + InTotoProvenance, + Metadata, + Recipe, +) +from .intoto_statement import ( + InTotoSlsaProvenanceV1, + InTotoStatement, + Subject, +) +from .package import ( + Distribution, + Location, + PackageNote, + PackageOccurrence, + Version, + Architecture, +) +from .provenance import ( + AliasContext, + Artifact, + BuildProvenance, + CloudRepoSourceContext, + Command, + FileHashes, + GerritSourceContext, + GitSourceContext, + Hash, + ProjectRepoId, + RepoId, + Source, + SourceContext, +) +from .sbom import ( + SbomReferenceIntotoPayload, + SbomReferenceIntotoPredicate, + SBOMReferenceNote, + SBOMReferenceOccurrence, +) +from .severity import ( + Severity, +) +from .slsa_provenance import ( + SlsaProvenance, +) +from .slsa_provenance_zero_two import ( + SlsaProvenanceZeroTwo, +) +from .upgrade import ( + UpgradeDistribution, + UpgradeNote, + UpgradeOccurrence, + WindowsUpdate, +) +from .vex import ( + VulnerabilityAssessmentNote, +) +from .vulnerability import ( + VulnerabilityNote, + VulnerabilityOccurrence, +) + +__all__ = ( + 'AttestationNote', + 'AttestationOccurrence', + 'Jwt', + 'BuildNote', + 'BuildOccurrence', + 'Digest', + 'Envelope', + 'EnvelopeSignature', + 'FileLocation', + 'License', + 'RelatedUrl', + 'Signature', + 'NoteKind', + 'ComplianceNote', + 'ComplianceOccurrence', + 'ComplianceVersion', + 'NonCompliantFile', + 'CVSS', + 'CVSSv3', + 'CVSSVersion', + 'DeploymentNote', + 'DeploymentOccurrence', + 'DiscoveryNote', + 'DiscoveryOccurrence', + 'DSSEAttestationNote', + 'DSSEAttestationOccurrence', + 'BatchCreateNotesRequest', + 'BatchCreateNotesResponse', + 'BatchCreateOccurrencesRequest', + 'BatchCreateOccurrencesResponse', + 'CreateNoteRequest', + 'CreateOccurrenceRequest', + 'DeleteNoteRequest', + 'DeleteOccurrenceRequest', + 'GetNoteRequest', + 'GetOccurrenceNoteRequest', + 'GetOccurrenceRequest', + 'ListNoteOccurrencesRequest', + 'ListNoteOccurrencesResponse', + 'ListNotesRequest', + 'ListNotesResponse', + 'ListOccurrencesRequest', + 'ListOccurrencesResponse', + 'Note', + 'Occurrence', + 'UpdateNoteRequest', + 'UpdateOccurrenceRequest', + 'Fingerprint', + 'ImageNote', + 'ImageOccurrence', + 'Layer', + 'BuilderConfig', + 'Completeness', + 'InTotoProvenance', + 'Metadata', + 'Recipe', + 'InTotoSlsaProvenanceV1', + 'InTotoStatement', + 'Subject', + 'Distribution', + 'Location', + 'PackageNote', + 'PackageOccurrence', + 'Version', + 'Architecture', + 'AliasContext', + 'Artifact', + 'BuildProvenance', + 'CloudRepoSourceContext', + 'Command', + 'FileHashes', + 'GerritSourceContext', + 'GitSourceContext', + 'Hash', + 'ProjectRepoId', + 'RepoId', + 'Source', + 'SourceContext', + 'SbomReferenceIntotoPayload', + 'SbomReferenceIntotoPredicate', + 'SBOMReferenceNote', + 'SBOMReferenceOccurrence', + 'Severity', + 'SlsaProvenance', + 'SlsaProvenanceZeroTwo', + 'UpgradeDistribution', + 'UpgradeNote', + 'UpgradeOccurrence', + 'WindowsUpdate', + 'VulnerabilityAssessmentNote', + 'VulnerabilityNote', + 'VulnerabilityOccurrence', +) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/attestation.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/attestation.py new file mode 100644 index 000000000000..b001a8ec82a7 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/attestation.py @@ -0,0 +1,148 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 grafeas.grafeas_v1.types import common + + +__protobuf__ = proto.module( + package='grafeas.v1', + manifest={ + 'AttestationNote', + 'Jwt', + 'AttestationOccurrence', + }, +) + + +class AttestationNote(proto.Message): + r"""Note kind that represents a logical attestation "role" or + "authority". For example, an organization might have one + ``Authority`` for "QA" and one for "build". This note is intended to + act strictly as a grouping mechanism for the attached occurrences + (Attestations). This grouping mechanism also provides a security + boundary, since IAM ACLs gate the ability for a principle to attach + an occurrence to a given note. It also provides a single point of + lookup to find all attached attestation occurrences, even if they + don't all live in the same project. + + Attributes: + hint (grafeas.grafeas_v1.types.AttestationNote.Hint): + Hint hints at the purpose of the attestation + authority. + """ + + class Hint(proto.Message): + r"""This submessage provides human-readable hints about the + purpose of the authority. Because the name of a note acts as its + resource reference, it is important to disambiguate the + canonical name of the Note (which might be a UUID for security + purposes) from "readable" names more suitable for debug output. + Note that these hints should not be used to look up authorities + in security sensitive contexts, such as when looking up + attestations to verify. + + Attributes: + human_readable_name (str): + Required. The human readable name of this + attestation authority, for example "qa". + """ + + human_readable_name: str = proto.Field( + proto.STRING, + number=1, + ) + + hint: Hint = proto.Field( + proto.MESSAGE, + number=1, + message=Hint, + ) + + +class Jwt(proto.Message): + r""" + + Attributes: + compact_jwt (str): + The compact encoding of a JWS, which is + always three base64 encoded strings joined by + periods. For details, see: + + https://tools.ietf.org/html/rfc7515.html#section-3.1 + """ + + compact_jwt: str = proto.Field( + proto.STRING, + number=1, + ) + + +class AttestationOccurrence(proto.Message): + r"""Occurrence that represents a single "attestation". The + authenticity of an attestation can be verified using the + attached signature. If the verifier trusts the public key of the + signer, then verifying the signature is sufficient to establish + trust. In this circumstance, the authority to which this + attestation is attached is primarily useful for lookup (how to + find this attestation if you already know the authority and + artifact to be verified) and intent (for which authority this + attestation was intended to sign. + + Attributes: + serialized_payload (bytes): + Required. The serialized payload that is verified by one or + more ``signatures``. + signatures (MutableSequence[grafeas.grafeas_v1.types.Signature]): + One or more signatures over ``serialized_payload``. Verifier + implementations should consider this attestation message + verified if at least one ``signature`` verifies + ``serialized_payload``. See ``Signature`` in common.proto + for more details on signature structure and verification. + jwts (MutableSequence[grafeas.grafeas_v1.types.Jwt]): + One or more JWTs encoding a self-contained attestation. Each + JWT encodes the payload that it verifies within the JWT + itself. Verifier implementation SHOULD ignore the + ``serialized_payload`` field when verifying these JWTs. If + only JWTs are present on this AttestationOccurrence, then + the ``serialized_payload`` SHOULD be left empty. Each JWT + SHOULD encode a claim specific to the ``resource_uri`` of + this Occurrence, but this is not validated by Grafeas + metadata API implementations. The JWT itself is opaque to + Grafeas. + """ + + serialized_payload: bytes = proto.Field( + proto.BYTES, + number=1, + ) + signatures: MutableSequence[common.Signature] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=common.Signature, + ) + jwts: MutableSequence['Jwt'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Jwt', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/build.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/build.py new file mode 100644 index 000000000000..10eea8a73894 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/build.py @@ -0,0 +1,115 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 grafeas.grafeas_v1.types import intoto_provenance as g_intoto_provenance +from grafeas.grafeas_v1.types import intoto_statement as g_intoto_statement +from grafeas.grafeas_v1.types import provenance as g_provenance + + +__protobuf__ = proto.module( + package='grafeas.v1', + manifest={ + 'BuildNote', + 'BuildOccurrence', + }, +) + + +class BuildNote(proto.Message): + r"""Note holding the version of the provider's builder and the + signature of the provenance message in the build details + occurrence. + + Attributes: + builder_version (str): + Required. Immutable. Version of the builder + which produced this build. + """ + + builder_version: str = proto.Field( + proto.STRING, + number=1, + ) + + +class BuildOccurrence(proto.Message): + r"""Details of a build occurrence. + + Attributes: + provenance (grafeas.grafeas_v1.types.BuildProvenance): + The actual provenance for the build. + provenance_bytes (str): + Serialized JSON representation of the provenance, used in + generating the build signature in the corresponding build + note. After verifying the signature, ``provenance_bytes`` + can be unmarshalled and compared to the provenance to + confirm that it is unchanged. A base64-encoded string + representation of the provenance bytes is used for the + signature in order to interoperate with openssl which + expects this format for signature verification. + + The serialized form is captured both to avoid ambiguity in + how the provenance is marshalled to json as well to prevent + incompatibilities with future changes. + intoto_provenance (grafeas.grafeas_v1.types.InTotoProvenance): + Deprecated. See InTotoStatement for the + replacement. In-toto Provenance representation + as defined in spec. + intoto_statement (grafeas.grafeas_v1.types.InTotoStatement): + In-toto Statement representation as defined in spec. The + intoto_statement can contain any type of provenance. The + serialized payload of the statement can be stored and signed + in the Occurrence's envelope. + in_toto_slsa_provenance_v1 (grafeas.grafeas_v1.types.InTotoSlsaProvenanceV1): + In-Toto Slsa Provenance V1 represents a slsa + provenance meeting the slsa spec, wrapped in an + in-toto statement. This allows for direct + jsonification of a to-spec in-toto slsa + statement with a to-spec slsa provenance. + """ + + provenance: g_provenance.BuildProvenance = proto.Field( + proto.MESSAGE, + number=1, + message=g_provenance.BuildProvenance, + ) + provenance_bytes: str = proto.Field( + proto.STRING, + number=2, + ) + intoto_provenance: g_intoto_provenance.InTotoProvenance = proto.Field( + proto.MESSAGE, + number=3, + message=g_intoto_provenance.InTotoProvenance, + ) + intoto_statement: g_intoto_statement.InTotoStatement = proto.Field( + proto.MESSAGE, + number=4, + message=g_intoto_statement.InTotoStatement, + ) + in_toto_slsa_provenance_v1: g_intoto_statement.InTotoSlsaProvenanceV1 = proto.Field( + proto.MESSAGE, + number=5, + message=g_intoto_statement.InTotoSlsaProvenanceV1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/common.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/common.py new file mode 100644 index 000000000000..047f564874ba --- /dev/null +++ b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/common.py @@ -0,0 +1,295 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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='grafeas.v1', + manifest={ + 'NoteKind', + 'RelatedUrl', + 'Signature', + 'Envelope', + 'EnvelopeSignature', + 'FileLocation', + 'License', + 'Digest', + }, +) + + +class NoteKind(proto.Enum): + r"""Kind represents the kinds of notes supported. + + Values: + NOTE_KIND_UNSPECIFIED (0): + Default value. This value is unused. + VULNERABILITY (1): + The note and occurrence represent a package + vulnerability. + BUILD (2): + The note and occurrence assert build + provenance. + IMAGE (3): + This represents an image basis relationship. + PACKAGE (4): + This represents a package installed via a + package manager. + DEPLOYMENT (5): + The note and occurrence track deployment + events. + DISCOVERY (6): + The note and occurrence track the initial + discovery status of a resource. + ATTESTATION (7): + This represents a logical "role" that can + attest to artifacts. + UPGRADE (8): + This represents an available package upgrade. + COMPLIANCE (9): + This represents a Compliance Note + DSSE_ATTESTATION (10): + This represents a DSSE attestation Note + VULNERABILITY_ASSESSMENT (11): + This represents a Vulnerability Assessment. + SBOM_REFERENCE (12): + This represents an SBOM Reference. + """ + NOTE_KIND_UNSPECIFIED = 0 + VULNERABILITY = 1 + BUILD = 2 + IMAGE = 3 + PACKAGE = 4 + DEPLOYMENT = 5 + DISCOVERY = 6 + ATTESTATION = 7 + UPGRADE = 8 + COMPLIANCE = 9 + DSSE_ATTESTATION = 10 + VULNERABILITY_ASSESSMENT = 11 + SBOM_REFERENCE = 12 + + +class RelatedUrl(proto.Message): + r"""Metadata for any related URL information. + + Attributes: + url (str): + Specific URL associated with the resource. + label (str): + Label to describe usage of the URL. + """ + + url: str = proto.Field( + proto.STRING, + number=1, + ) + label: str = proto.Field( + proto.STRING, + number=2, + ) + + +class Signature(proto.Message): + r"""Verifiers (e.g. Kritis implementations) MUST verify signatures with + respect to the trust anchors defined in policy (e.g. a Kritis + policy). Typically this means that the verifier has been configured + with a map from ``public_key_id`` to public key material (and any + required parameters, e.g. signing algorithm). + + In particular, verification implementations MUST NOT treat the + signature ``public_key_id`` as anything more than a key lookup hint. + The ``public_key_id`` DOES NOT validate or authenticate a public + key; it only provides a mechanism for quickly selecting a public key + ALREADY CONFIGURED on the verifier through a trusted channel. + Verification implementations MUST reject signatures in any of the + following circumstances: + + - The ``public_key_id`` is not recognized by the verifier. + - The public key that ``public_key_id`` refers to does not verify + the signature with respect to the payload. + + The ``signature`` contents SHOULD NOT be "attached" (where the + payload is included with the serialized ``signature`` bytes). + Verifiers MUST ignore any "attached" payload and only verify + signatures with respect to explicitly provided payload (e.g. a + ``payload`` field on the proto message that holds this Signature, or + the canonical serialization of the proto message that holds this + signature). + + Attributes: + signature (bytes): + The content of the signature, an opaque + bytestring. The payload that this signature + verifies MUST be unambiguously provided with the + Signature during verification. A wrapper message + might provide the payload explicitly. + Alternatively, a message might have a canonical + serialization that can always be unambiguously + computed to derive the payload. + public_key_id (str): + The identifier for the public key that verifies this + signature. + + - The ``public_key_id`` is required. + - The ``public_key_id`` SHOULD be an RFC3986 conformant + URI. + - When possible, the ``public_key_id`` SHOULD be an + immutable reference, such as a cryptographic digest. + + Examples of valid ``public_key_id``\ s: + + OpenPGP V4 public key fingerprint: + + - "openpgp4fpr:74FAF3B861BDA0870C7B6DEF607E48D2A663AEEA" + See + https://www.iana.org/assignments/uri-schemes/prov/openpgp4fpr + for more details on this scheme. + + RFC6920 digest-named SubjectPublicKeyInfo (digest of the DER + serialization): + + - "ni:///sha-256;cD9o9Cq6LG3jD0iKXqEi_vdjJGecm_iXkbqVoScViaU" + - "nih:///sha-256;703f68f42aba2c6de30f488a5ea122fef76324679c9bf89791ba95a1271589a5". + """ + + signature: bytes = proto.Field( + proto.BYTES, + number=1, + ) + public_key_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class Envelope(proto.Message): + r"""MUST match + https://github.com/secure-systems-lab/dsse/blob/master/envelope.proto. + An authenticated message of arbitrary type. + + Attributes: + payload (bytes): + + payload_type (str): + + signatures (MutableSequence[grafeas.grafeas_v1.types.EnvelopeSignature]): + + """ + + payload: bytes = proto.Field( + proto.BYTES, + number=1, + ) + payload_type: str = proto.Field( + proto.STRING, + number=2, + ) + signatures: MutableSequence['EnvelopeSignature'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='EnvelopeSignature', + ) + + +class EnvelopeSignature(proto.Message): + r""" + + Attributes: + sig (bytes): + + keyid (str): + + """ + + sig: bytes = proto.Field( + proto.BYTES, + number=1, + ) + keyid: str = proto.Field( + proto.STRING, + number=2, + ) + + +class FileLocation(proto.Message): + r"""Indicates the location at which a package was found. + + Attributes: + file_path (str): + For jars that are contained inside .war + files, this filepath can indicate the path to + war file combined with the path to jar file. + """ + + file_path: str = proto.Field( + proto.STRING, + number=1, + ) + + +class License(proto.Message): + r"""License information. + + Attributes: + expression (str): + Often a single license can be used to + represent the licensing terms. Sometimes it is + necessary to include a choice of one or more + licenses or some combination of license + identifiers. + Examples: "LGPL-2.1-only OR MIT", "LGPL-2.1-only + AND MIT", "GPL-2.0-or-later WITH + Bison-exception-2.2". + comments (str): + Comments + """ + + expression: str = proto.Field( + proto.STRING, + number=1, + ) + comments: str = proto.Field( + proto.STRING, + number=2, + ) + + +class Digest(proto.Message): + r"""Digest information. + + Attributes: + algo (str): + ``SHA1``, ``SHA512`` etc. + digest_bytes (bytes): + Value of the digest. + """ + + algo: str = proto.Field( + proto.STRING, + number=1, + ) + digest_bytes: bytes = proto.Field( + proto.BYTES, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/compliance.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/compliance.py new file mode 100644 index 000000000000..b770fe9748cc --- /dev/null +++ b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/compliance.py @@ -0,0 +1,215 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 grafeas.grafeas_v1.types import severity as g_severity + + +__protobuf__ = proto.module( + package='grafeas.v1', + manifest={ + 'ComplianceNote', + 'ComplianceVersion', + 'ComplianceOccurrence', + 'NonCompliantFile', + }, +) + + +class ComplianceNote(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + title (str): + The title that identifies this compliance + check. + description (str): + A description about this compliance check. + version (MutableSequence[grafeas.grafeas_v1.types.ComplianceVersion]): + The OS and config versions the benchmark + applies to. + rationale (str): + A rationale for the existence of this + compliance check. + remediation (str): + A description of remediation steps if the + compliance check fails. + cis_benchmark (grafeas.grafeas_v1.types.ComplianceNote.CisBenchmark): + + This field is a member of `oneof`_ ``compliance_type``. + scan_instructions (bytes): + Serialized scan instructions with a + predefined format. + impact (str): + + This field is a member of `oneof`_ ``potential_impact``. + """ + + class CisBenchmark(proto.Message): + r"""A compliance check that is a CIS benchmark. + + Attributes: + profile_level (int): + + severity (grafeas.grafeas_v1.types.Severity): + + """ + + profile_level: int = proto.Field( + proto.INT32, + number=1, + ) + severity: g_severity.Severity = proto.Field( + proto.ENUM, + number=2, + enum=g_severity.Severity, + ) + + title: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + version: MutableSequence['ComplianceVersion'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='ComplianceVersion', + ) + rationale: str = proto.Field( + proto.STRING, + number=4, + ) + remediation: str = proto.Field( + proto.STRING, + number=5, + ) + cis_benchmark: CisBenchmark = proto.Field( + proto.MESSAGE, + number=6, + oneof='compliance_type', + message=CisBenchmark, + ) + scan_instructions: bytes = proto.Field( + proto.BYTES, + number=7, + ) + impact: str = proto.Field( + proto.STRING, + number=8, + oneof='potential_impact', + ) + + +class ComplianceVersion(proto.Message): + r"""Describes the CIS benchmark version that is applicable to a + given OS and os version. + + Attributes: + cpe_uri (str): + The CPE URI + (https://cpe.mitre.org/specification/) this + benchmark is applicable to. + benchmark_document (str): + The name of the document that defines this + benchmark, e.g. "CIS Container-Optimized OS". + version (str): + The version of the benchmark. This is set to + the version of the OS-specific CIS document the + benchmark is defined in. + """ + + cpe_uri: str = proto.Field( + proto.STRING, + number=1, + ) + benchmark_document: str = proto.Field( + proto.STRING, + number=3, + ) + version: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ComplianceOccurrence(proto.Message): + r"""An indication that the compliance checks in the associated + ComplianceNote were not satisfied for particular resources or a + specified reason. + + Attributes: + non_compliant_files (MutableSequence[grafeas.grafeas_v1.types.NonCompliantFile]): + + non_compliance_reason (str): + + version (grafeas.grafeas_v1.types.ComplianceVersion): + The OS and config version the benchmark was + run on. + """ + + non_compliant_files: MutableSequence['NonCompliantFile'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='NonCompliantFile', + ) + non_compliance_reason: str = proto.Field( + proto.STRING, + number=3, + ) + version: 'ComplianceVersion' = proto.Field( + proto.MESSAGE, + number=4, + message='ComplianceVersion', + ) + + +class NonCompliantFile(proto.Message): + r"""Details about files that caused a compliance check to fail. + + Attributes: + path (str): + Empty if ``display_command`` is set. + display_command (str): + Command to display the non-compliant files. + reason (str): + Explains why a file is non compliant for a + CIS check. + """ + + path: str = proto.Field( + proto.STRING, + number=1, + ) + display_command: str = proto.Field( + proto.STRING, + number=2, + ) + reason: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/cvss.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/cvss.py new file mode 100644 index 000000000000..e0e252edac00 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/cvss.py @@ -0,0 +1,464 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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='grafeas.v1', + manifest={ + 'CVSSVersion', + 'CVSSv3', + 'CVSS', + }, +) + + +class CVSSVersion(proto.Enum): + r"""CVSS Version. + + Values: + CVSS_VERSION_UNSPECIFIED (0): + No description available. + CVSS_VERSION_2 (1): + No description available. + CVSS_VERSION_3 (2): + No description available. + """ + CVSS_VERSION_UNSPECIFIED = 0 + CVSS_VERSION_2 = 1 + CVSS_VERSION_3 = 2 + + +class CVSSv3(proto.Message): + r"""Common Vulnerability Scoring System version 3. + For details, see + https://www.first.org/cvss/specification-document + + Attributes: + base_score (float): + The base score is a function of the base + metric scores. + exploitability_score (float): + + impact_score (float): + + attack_vector (grafeas.grafeas_v1.types.CVSSv3.AttackVector): + Base Metrics + Represents the intrinsic characteristics of a + vulnerability that are constant over time and + across user environments. + attack_complexity (grafeas.grafeas_v1.types.CVSSv3.AttackComplexity): + + privileges_required (grafeas.grafeas_v1.types.CVSSv3.PrivilegesRequired): + + user_interaction (grafeas.grafeas_v1.types.CVSSv3.UserInteraction): + + scope (grafeas.grafeas_v1.types.CVSSv3.Scope): + + confidentiality_impact (grafeas.grafeas_v1.types.CVSSv3.Impact): + + integrity_impact (grafeas.grafeas_v1.types.CVSSv3.Impact): + + availability_impact (grafeas.grafeas_v1.types.CVSSv3.Impact): + + """ + class AttackVector(proto.Enum): + r""" + + Values: + ATTACK_VECTOR_UNSPECIFIED (0): + No description available. + ATTACK_VECTOR_NETWORK (1): + No description available. + ATTACK_VECTOR_ADJACENT (2): + No description available. + ATTACK_VECTOR_LOCAL (3): + No description available. + ATTACK_VECTOR_PHYSICAL (4): + No description available. + """ + ATTACK_VECTOR_UNSPECIFIED = 0 + ATTACK_VECTOR_NETWORK = 1 + ATTACK_VECTOR_ADJACENT = 2 + ATTACK_VECTOR_LOCAL = 3 + ATTACK_VECTOR_PHYSICAL = 4 + + class AttackComplexity(proto.Enum): + r""" + + Values: + ATTACK_COMPLEXITY_UNSPECIFIED (0): + No description available. + ATTACK_COMPLEXITY_LOW (1): + No description available. + ATTACK_COMPLEXITY_HIGH (2): + No description available. + """ + ATTACK_COMPLEXITY_UNSPECIFIED = 0 + ATTACK_COMPLEXITY_LOW = 1 + ATTACK_COMPLEXITY_HIGH = 2 + + class PrivilegesRequired(proto.Enum): + r""" + + Values: + PRIVILEGES_REQUIRED_UNSPECIFIED (0): + No description available. + PRIVILEGES_REQUIRED_NONE (1): + No description available. + PRIVILEGES_REQUIRED_LOW (2): + No description available. + PRIVILEGES_REQUIRED_HIGH (3): + No description available. + """ + PRIVILEGES_REQUIRED_UNSPECIFIED = 0 + PRIVILEGES_REQUIRED_NONE = 1 + PRIVILEGES_REQUIRED_LOW = 2 + PRIVILEGES_REQUIRED_HIGH = 3 + + class UserInteraction(proto.Enum): + r""" + + Values: + USER_INTERACTION_UNSPECIFIED (0): + No description available. + USER_INTERACTION_NONE (1): + No description available. + USER_INTERACTION_REQUIRED (2): + No description available. + """ + USER_INTERACTION_UNSPECIFIED = 0 + USER_INTERACTION_NONE = 1 + USER_INTERACTION_REQUIRED = 2 + + class Scope(proto.Enum): + r""" + + Values: + SCOPE_UNSPECIFIED (0): + No description available. + SCOPE_UNCHANGED (1): + No description available. + SCOPE_CHANGED (2): + No description available. + """ + SCOPE_UNSPECIFIED = 0 + SCOPE_UNCHANGED = 1 + SCOPE_CHANGED = 2 + + class Impact(proto.Enum): + r""" + + Values: + IMPACT_UNSPECIFIED (0): + No description available. + IMPACT_HIGH (1): + No description available. + IMPACT_LOW (2): + No description available. + IMPACT_NONE (3): + No description available. + """ + IMPACT_UNSPECIFIED = 0 + IMPACT_HIGH = 1 + IMPACT_LOW = 2 + IMPACT_NONE = 3 + + base_score: float = proto.Field( + proto.FLOAT, + number=1, + ) + exploitability_score: float = proto.Field( + proto.FLOAT, + number=2, + ) + impact_score: float = proto.Field( + proto.FLOAT, + number=3, + ) + attack_vector: AttackVector = proto.Field( + proto.ENUM, + number=5, + enum=AttackVector, + ) + attack_complexity: AttackComplexity = proto.Field( + proto.ENUM, + number=6, + enum=AttackComplexity, + ) + privileges_required: PrivilegesRequired = proto.Field( + proto.ENUM, + number=7, + enum=PrivilegesRequired, + ) + user_interaction: UserInteraction = proto.Field( + proto.ENUM, + number=8, + enum=UserInteraction, + ) + scope: Scope = proto.Field( + proto.ENUM, + number=9, + enum=Scope, + ) + confidentiality_impact: Impact = proto.Field( + proto.ENUM, + number=10, + enum=Impact, + ) + integrity_impact: Impact = proto.Field( + proto.ENUM, + number=11, + enum=Impact, + ) + availability_impact: Impact = proto.Field( + proto.ENUM, + number=12, + enum=Impact, + ) + + +class CVSS(proto.Message): + r"""Common Vulnerability Scoring System. + For details, see + https://www.first.org/cvss/specification-document This is a + message we will try to use for storing various versions of CVSS + rather than making a separate proto for storing a specific + version. + + Attributes: + base_score (float): + The base score is a function of the base + metric scores. + exploitability_score (float): + + impact_score (float): + + attack_vector (grafeas.grafeas_v1.types.CVSS.AttackVector): + Base Metrics + Represents the intrinsic characteristics of a + vulnerability that are constant over time and + across user environments. + attack_complexity (grafeas.grafeas_v1.types.CVSS.AttackComplexity): + + authentication (grafeas.grafeas_v1.types.CVSS.Authentication): + + privileges_required (grafeas.grafeas_v1.types.CVSS.PrivilegesRequired): + + user_interaction (grafeas.grafeas_v1.types.CVSS.UserInteraction): + + scope (grafeas.grafeas_v1.types.CVSS.Scope): + + confidentiality_impact (grafeas.grafeas_v1.types.CVSS.Impact): + + integrity_impact (grafeas.grafeas_v1.types.CVSS.Impact): + + availability_impact (grafeas.grafeas_v1.types.CVSS.Impact): + + """ + class AttackVector(proto.Enum): + r""" + + Values: + ATTACK_VECTOR_UNSPECIFIED (0): + No description available. + ATTACK_VECTOR_NETWORK (1): + No description available. + ATTACK_VECTOR_ADJACENT (2): + No description available. + ATTACK_VECTOR_LOCAL (3): + No description available. + ATTACK_VECTOR_PHYSICAL (4): + No description available. + """ + ATTACK_VECTOR_UNSPECIFIED = 0 + ATTACK_VECTOR_NETWORK = 1 + ATTACK_VECTOR_ADJACENT = 2 + ATTACK_VECTOR_LOCAL = 3 + ATTACK_VECTOR_PHYSICAL = 4 + + class AttackComplexity(proto.Enum): + r""" + + Values: + ATTACK_COMPLEXITY_UNSPECIFIED (0): + No description available. + ATTACK_COMPLEXITY_LOW (1): + No description available. + ATTACK_COMPLEXITY_HIGH (2): + No description available. + ATTACK_COMPLEXITY_MEDIUM (3): + No description available. + """ + ATTACK_COMPLEXITY_UNSPECIFIED = 0 + ATTACK_COMPLEXITY_LOW = 1 + ATTACK_COMPLEXITY_HIGH = 2 + ATTACK_COMPLEXITY_MEDIUM = 3 + + class Authentication(proto.Enum): + r""" + + Values: + AUTHENTICATION_UNSPECIFIED (0): + No description available. + AUTHENTICATION_MULTIPLE (1): + No description available. + AUTHENTICATION_SINGLE (2): + No description available. + AUTHENTICATION_NONE (3): + No description available. + """ + AUTHENTICATION_UNSPECIFIED = 0 + AUTHENTICATION_MULTIPLE = 1 + AUTHENTICATION_SINGLE = 2 + AUTHENTICATION_NONE = 3 + + class PrivilegesRequired(proto.Enum): + r""" + + Values: + PRIVILEGES_REQUIRED_UNSPECIFIED (0): + No description available. + PRIVILEGES_REQUIRED_NONE (1): + No description available. + PRIVILEGES_REQUIRED_LOW (2): + No description available. + PRIVILEGES_REQUIRED_HIGH (3): + No description available. + """ + PRIVILEGES_REQUIRED_UNSPECIFIED = 0 + PRIVILEGES_REQUIRED_NONE = 1 + PRIVILEGES_REQUIRED_LOW = 2 + PRIVILEGES_REQUIRED_HIGH = 3 + + class UserInteraction(proto.Enum): + r""" + + Values: + USER_INTERACTION_UNSPECIFIED (0): + No description available. + USER_INTERACTION_NONE (1): + No description available. + USER_INTERACTION_REQUIRED (2): + No description available. + """ + USER_INTERACTION_UNSPECIFIED = 0 + USER_INTERACTION_NONE = 1 + USER_INTERACTION_REQUIRED = 2 + + class Scope(proto.Enum): + r""" + + Values: + SCOPE_UNSPECIFIED (0): + No description available. + SCOPE_UNCHANGED (1): + No description available. + SCOPE_CHANGED (2): + No description available. + """ + SCOPE_UNSPECIFIED = 0 + SCOPE_UNCHANGED = 1 + SCOPE_CHANGED = 2 + + class Impact(proto.Enum): + r""" + + Values: + IMPACT_UNSPECIFIED (0): + No description available. + IMPACT_HIGH (1): + No description available. + IMPACT_LOW (2): + No description available. + IMPACT_NONE (3): + No description available. + IMPACT_PARTIAL (4): + No description available. + IMPACT_COMPLETE (5): + No description available. + """ + IMPACT_UNSPECIFIED = 0 + IMPACT_HIGH = 1 + IMPACT_LOW = 2 + IMPACT_NONE = 3 + IMPACT_PARTIAL = 4 + IMPACT_COMPLETE = 5 + + base_score: float = proto.Field( + proto.FLOAT, + number=1, + ) + exploitability_score: float = proto.Field( + proto.FLOAT, + number=2, + ) + impact_score: float = proto.Field( + proto.FLOAT, + number=3, + ) + attack_vector: AttackVector = proto.Field( + proto.ENUM, + number=4, + enum=AttackVector, + ) + attack_complexity: AttackComplexity = proto.Field( + proto.ENUM, + number=5, + enum=AttackComplexity, + ) + authentication: Authentication = proto.Field( + proto.ENUM, + number=6, + enum=Authentication, + ) + privileges_required: PrivilegesRequired = proto.Field( + proto.ENUM, + number=7, + enum=PrivilegesRequired, + ) + user_interaction: UserInteraction = proto.Field( + proto.ENUM, + number=8, + enum=UserInteraction, + ) + scope: Scope = proto.Field( + proto.ENUM, + number=9, + enum=Scope, + ) + confidentiality_impact: Impact = proto.Field( + proto.ENUM, + number=10, + enum=Impact, + ) + integrity_impact: Impact = proto.Field( + proto.ENUM, + number=11, + enum=Impact, + ) + availability_impact: Impact = proto.Field( + proto.ENUM, + number=12, + enum=Impact, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/deployment.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/deployment.py new file mode 100644 index 000000000000..d22e451c7744 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/deployment.py @@ -0,0 +1,125 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='grafeas.v1', + manifest={ + 'DeploymentNote', + 'DeploymentOccurrence', + }, +) + + +class DeploymentNote(proto.Message): + r"""An artifact that can be deployed in some runtime. + + Attributes: + resource_uri (MutableSequence[str]): + Required. Resource URI for the artifact being + deployed. + """ + + resource_uri: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +class DeploymentOccurrence(proto.Message): + r"""The period during which some deployable was active in a + runtime. + + Attributes: + user_email (str): + Identity of the user that triggered this + deployment. + deploy_time (google.protobuf.timestamp_pb2.Timestamp): + Required. Beginning of the lifetime of this + deployment. + undeploy_time (google.protobuf.timestamp_pb2.Timestamp): + End of the lifetime of this deployment. + config (str): + Configuration used to create this deployment. + address (str): + Address of the runtime element hosting this + deployment. + resource_uri (MutableSequence[str]): + Output only. Resource URI for the artifact + being deployed taken from the deployable field + with the same name. + platform (grafeas.grafeas_v1.types.DeploymentOccurrence.Platform): + Platform hosting this deployment. + """ + class Platform(proto.Enum): + r"""Types of platforms. + + Values: + PLATFORM_UNSPECIFIED (0): + Unknown. + GKE (1): + Google Container Engine. + FLEX (2): + Google App Engine: Flexible Environment. + CUSTOM (3): + Custom user-defined platform. + """ + PLATFORM_UNSPECIFIED = 0 + GKE = 1 + FLEX = 2 + CUSTOM = 3 + + user_email: str = proto.Field( + proto.STRING, + number=1, + ) + deploy_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + undeploy_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + config: str = proto.Field( + proto.STRING, + number=4, + ) + address: str = proto.Field( + proto.STRING, + number=5, + ) + resource_uri: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=6, + ) + platform: Platform = proto.Field( + proto.ENUM, + number=7, + enum=Platform, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/discovery.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/discovery.py new file mode 100644 index 000000000000..627ab994ae06 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/discovery.py @@ -0,0 +1,281 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from grafeas.grafeas_v1.types import common + + +__protobuf__ = proto.module( + package='grafeas.v1', + manifest={ + 'DiscoveryNote', + 'DiscoveryOccurrence', + }, +) + + +class DiscoveryNote(proto.Message): + r"""A note that indicates a type of analysis a provider would perform. + This note exists in a provider's project. A ``Discovery`` occurrence + is created in a consumer's project at the start of analysis. + + Attributes: + analysis_kind (grafeas.grafeas_v1.types.NoteKind): + Required. Immutable. The kind of analysis + that is handled by this discovery. + """ + + analysis_kind: common.NoteKind = proto.Field( + proto.ENUM, + number=1, + enum=common.NoteKind, + ) + + +class DiscoveryOccurrence(proto.Message): + r"""Provides information about the analysis status of a + discovered resource. + + Attributes: + continuous_analysis (grafeas.grafeas_v1.types.DiscoveryOccurrence.ContinuousAnalysis): + Whether the resource is continuously + analyzed. + analysis_status (grafeas.grafeas_v1.types.DiscoveryOccurrence.AnalysisStatus): + The status of discovery for the resource. + analysis_completed (grafeas.grafeas_v1.types.DiscoveryOccurrence.AnalysisCompleted): + + analysis_error (MutableSequence[google.rpc.status_pb2.Status]): + Indicates any errors encountered during + analysis of a resource. There could be 0 or more + of these errors. + analysis_status_error (google.rpc.status_pb2.Status): + When an error is encountered this will + contain a LocalizedMessage under details to show + to the user. The LocalizedMessage is output only + and populated by the API. + cpe (str): + The CPE of the resource being scanned. + last_scan_time (google.protobuf.timestamp_pb2.Timestamp): + The last time this resource was scanned. + archive_time (google.protobuf.timestamp_pb2.Timestamp): + The time occurrences related to this + discovery occurrence were archived. + sbom_status (grafeas.grafeas_v1.types.DiscoveryOccurrence.SBOMStatus): + The status of an SBOM generation. + vulnerability_attestation (grafeas.grafeas_v1.types.DiscoveryOccurrence.VulnerabilityAttestation): + The status of an vulnerability attestation + generation. + """ + class ContinuousAnalysis(proto.Enum): + r"""Whether the resource is continuously analyzed. + + Values: + CONTINUOUS_ANALYSIS_UNSPECIFIED (0): + Unknown. + ACTIVE (1): + The resource is continuously analyzed. + INACTIVE (2): + The resource is ignored for continuous + analysis. + """ + CONTINUOUS_ANALYSIS_UNSPECIFIED = 0 + ACTIVE = 1 + INACTIVE = 2 + + class AnalysisStatus(proto.Enum): + r"""Analysis status for a resource. Currently for initial + analysis only (not updated in continuous analysis). + + Values: + ANALYSIS_STATUS_UNSPECIFIED (0): + Unknown. + PENDING (1): + Resource is known but no action has been + taken yet. + SCANNING (2): + Resource is being analyzed. + FINISHED_SUCCESS (3): + Analysis has finished successfully. + COMPLETE (3): + Analysis has completed. + FINISHED_FAILED (4): + Analysis has finished unsuccessfully, the + analysis itself is in a bad state. + FINISHED_UNSUPPORTED (5): + The resource is known not to be supported. + """ + _pb_options = {'allow_alias': True} + ANALYSIS_STATUS_UNSPECIFIED = 0 + PENDING = 1 + SCANNING = 2 + FINISHED_SUCCESS = 3 + COMPLETE = 3 + FINISHED_FAILED = 4 + FINISHED_UNSUPPORTED = 5 + + class AnalysisCompleted(proto.Message): + r"""Indicates which analysis completed successfully. Multiple + types of analysis can be performed on a single resource. + + Attributes: + analysis_type (MutableSequence[str]): + + """ + + analysis_type: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + class SBOMStatus(proto.Message): + r"""The status of an SBOM generation. + + Attributes: + sbom_state (grafeas.grafeas_v1.types.DiscoveryOccurrence.SBOMStatus.SBOMState): + The progress of the SBOM generation. + error (str): + If there was an error generating an SBOM, + this will indicate what that error was. + """ + class SBOMState(proto.Enum): + r"""An enum indicating the progress of the SBOM generation. + + Values: + SBOM_STATE_UNSPECIFIED (0): + Default unknown state. + PENDING (1): + SBOM scanning is pending. + COMPLETE (2): + SBOM scanning has completed. + """ + SBOM_STATE_UNSPECIFIED = 0 + PENDING = 1 + COMPLETE = 2 + + sbom_state: 'DiscoveryOccurrence.SBOMStatus.SBOMState' = proto.Field( + proto.ENUM, + number=1, + enum='DiscoveryOccurrence.SBOMStatus.SBOMState', + ) + error: str = proto.Field( + proto.STRING, + number=2, + ) + + class VulnerabilityAttestation(proto.Message): + r"""The status of an vulnerability attestation generation. + + Attributes: + last_attempt_time (google.protobuf.timestamp_pb2.Timestamp): + The last time we attempted to generate an + attestation. + state (grafeas.grafeas_v1.types.DiscoveryOccurrence.VulnerabilityAttestation.VulnerabilityAttestationState): + The success/failure state of the latest + attestation attempt. + error (str): + If failure, the error reason for why the + attestation generation failed. + """ + class VulnerabilityAttestationState(proto.Enum): + r"""An enum indicating the state of the attestation generation. + + Values: + VULNERABILITY_ATTESTATION_STATE_UNSPECIFIED (0): + Default unknown state. + SUCCESS (1): + Attestation was successfully generated and + stored. + FAILURE (2): + Attestation was unsuccessfully generated and + stored. + """ + VULNERABILITY_ATTESTATION_STATE_UNSPECIFIED = 0 + SUCCESS = 1 + FAILURE = 2 + + last_attempt_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + state: 'DiscoveryOccurrence.VulnerabilityAttestation.VulnerabilityAttestationState' = proto.Field( + proto.ENUM, + number=2, + enum='DiscoveryOccurrence.VulnerabilityAttestation.VulnerabilityAttestationState', + ) + error: str = proto.Field( + proto.STRING, + number=3, + ) + + continuous_analysis: ContinuousAnalysis = proto.Field( + proto.ENUM, + number=1, + enum=ContinuousAnalysis, + ) + analysis_status: AnalysisStatus = proto.Field( + proto.ENUM, + number=2, + enum=AnalysisStatus, + ) + analysis_completed: AnalysisCompleted = proto.Field( + proto.MESSAGE, + number=7, + message=AnalysisCompleted, + ) + analysis_error: MutableSequence[status_pb2.Status] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message=status_pb2.Status, + ) + analysis_status_error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=3, + message=status_pb2.Status, + ) + cpe: str = proto.Field( + proto.STRING, + number=4, + ) + last_scan_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + archive_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + sbom_status: SBOMStatus = proto.Field( + proto.MESSAGE, + number=9, + message=SBOMStatus, + ) + vulnerability_attestation: VulnerabilityAttestation = proto.Field( + proto.MESSAGE, + number=10, + message=VulnerabilityAttestation, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/dsse_attestation.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/dsse_attestation.py new file mode 100644 index 000000000000..afc3dc412306 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/dsse_attestation.py @@ -0,0 +1,102 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 grafeas.grafeas_v1.types import common +from grafeas.grafeas_v1.types import intoto_statement + + +__protobuf__ = proto.module( + package='grafeas.v1', + manifest={ + 'DSSEAttestationNote', + 'DSSEAttestationOccurrence', + }, +) + + +class DSSEAttestationNote(proto.Message): + r""" + + Attributes: + hint (grafeas.grafeas_v1.types.DSSEAttestationNote.DSSEHint): + DSSEHint hints at the purpose of the + attestation authority. + """ + + class DSSEHint(proto.Message): + r"""This submessage provides human-readable hints about the + purpose of the authority. Because the name of a note acts as its + resource reference, it is important to disambiguate the + canonical name of the Note (which might be a UUID for security + purposes) from "readable" names more suitable for debug output. + Note that these hints should not be used to look up authorities + in security sensitive contexts, such as when looking up + attestations to verify. + + Attributes: + human_readable_name (str): + Required. The human readable name of this + attestation authority, for example + "cloudbuild-prod". + """ + + human_readable_name: str = proto.Field( + proto.STRING, + number=1, + ) + + hint: DSSEHint = proto.Field( + proto.MESSAGE, + number=1, + message=DSSEHint, + ) + + +class DSSEAttestationOccurrence(proto.Message): + r"""Deprecated. Prefer to use a regular Occurrence, and populate + the Envelope at the top level of the Occurrence. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + envelope (grafeas.grafeas_v1.types.Envelope): + If doing something security critical, make + sure to verify the signatures in this metadata. + statement (grafeas.grafeas_v1.types.InTotoStatement): + + This field is a member of `oneof`_ ``decoded_payload``. + """ + + envelope: common.Envelope = proto.Field( + proto.MESSAGE, + number=1, + message=common.Envelope, + ) + statement: intoto_statement.InTotoStatement = proto.Field( + proto.MESSAGE, + number=2, + oneof='decoded_payload', + message=intoto_statement.InTotoStatement, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/grafeas.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/grafeas.py new file mode 100644 index 000000000000..b98b55887b0c --- /dev/null +++ b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/grafeas.py @@ -0,0 +1,921 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 timestamp_pb2 # type: ignore +from grafeas.grafeas_v1.types import attestation as g_attestation +from grafeas.grafeas_v1.types import build as g_build +from grafeas.grafeas_v1.types import common +from grafeas.grafeas_v1.types import compliance as g_compliance +from grafeas.grafeas_v1.types import deployment as g_deployment +from grafeas.grafeas_v1.types import discovery as g_discovery +from grafeas.grafeas_v1.types import dsse_attestation as g_dsse_attestation +from grafeas.grafeas_v1.types import image as g_image +from grafeas.grafeas_v1.types import package as g_package +from grafeas.grafeas_v1.types import sbom +from grafeas.grafeas_v1.types import upgrade as g_upgrade +from grafeas.grafeas_v1.types import vex +from grafeas.grafeas_v1.types import vulnerability as g_vulnerability + + +__protobuf__ = proto.module( + package='grafeas.v1', + manifest={ + 'Occurrence', + 'Note', + 'GetOccurrenceRequest', + 'ListOccurrencesRequest', + 'ListOccurrencesResponse', + 'DeleteOccurrenceRequest', + 'CreateOccurrenceRequest', + 'UpdateOccurrenceRequest', + 'GetNoteRequest', + 'GetOccurrenceNoteRequest', + 'ListNotesRequest', + 'ListNotesResponse', + 'DeleteNoteRequest', + 'CreateNoteRequest', + 'UpdateNoteRequest', + 'ListNoteOccurrencesRequest', + 'ListNoteOccurrencesResponse', + 'BatchCreateNotesRequest', + 'BatchCreateNotesResponse', + 'BatchCreateOccurrencesRequest', + 'BatchCreateOccurrencesResponse', + }, +) + + +class Occurrence(proto.Message): + r"""An instance of an analysis type that has been found on a + resource. + + 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: + name (str): + Output only. The name of the occurrence in the form of + ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. + resource_uri (str): + Required. Immutable. A URI that represents the resource for + which the occurrence applies. For example, + ``https://gcr.io/project/image@sha256:123abc`` for a Docker + image. + note_name (str): + Required. Immutable. The analysis note associated with this + occurrence, in the form of + ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. This field can + be used as a filter in list requests. + kind (grafeas.grafeas_v1.types.NoteKind): + Output only. This explicitly denotes which of + the occurrence details are specified. This field + can be used as a filter in list requests. + remediation (str): + A description of actions that can be taken to + remedy the note. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time this occurrence was + created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time this occurrence was + last updated. + vulnerability (grafeas.grafeas_v1.types.VulnerabilityOccurrence): + Describes a security vulnerability. + + This field is a member of `oneof`_ ``details``. + build (grafeas.grafeas_v1.types.BuildOccurrence): + Describes a verifiable build. + + This field is a member of `oneof`_ ``details``. + image (grafeas.grafeas_v1.types.ImageOccurrence): + Describes how this resource derives from the + basis in the associated note. + + This field is a member of `oneof`_ ``details``. + package (grafeas.grafeas_v1.types.PackageOccurrence): + Describes the installation of a package on + the linked resource. + + This field is a member of `oneof`_ ``details``. + deployment (grafeas.grafeas_v1.types.DeploymentOccurrence): + Describes the deployment of an artifact on a + runtime. + + This field is a member of `oneof`_ ``details``. + discovery (grafeas.grafeas_v1.types.DiscoveryOccurrence): + Describes when a resource was discovered. + + This field is a member of `oneof`_ ``details``. + attestation (grafeas.grafeas_v1.types.AttestationOccurrence): + Describes an attestation of an artifact. + + This field is a member of `oneof`_ ``details``. + upgrade (grafeas.grafeas_v1.types.UpgradeOccurrence): + Describes an available package upgrade on the + linked resource. + + This field is a member of `oneof`_ ``details``. + compliance (grafeas.grafeas_v1.types.ComplianceOccurrence): + Describes a compliance violation on a linked + resource. + + This field is a member of `oneof`_ ``details``. + dsse_attestation (grafeas.grafeas_v1.types.DSSEAttestationOccurrence): + Describes an attestation of an artifact using + dsse. + + This field is a member of `oneof`_ ``details``. + sbom_reference (grafeas.grafeas_v1.types.SBOMReferenceOccurrence): + Describes a specific SBOM reference + occurrences. + + This field is a member of `oneof`_ ``details``. + envelope (grafeas.grafeas_v1.types.Envelope): + https://github.com/secure-systems-lab/dsse + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + resource_uri: str = proto.Field( + proto.STRING, + number=2, + ) + note_name: str = proto.Field( + proto.STRING, + number=3, + ) + kind: common.NoteKind = proto.Field( + proto.ENUM, + number=4, + enum=common.NoteKind, + ) + remediation: str = proto.Field( + proto.STRING, + number=5, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + vulnerability: g_vulnerability.VulnerabilityOccurrence = proto.Field( + proto.MESSAGE, + number=8, + oneof='details', + message=g_vulnerability.VulnerabilityOccurrence, + ) + build: g_build.BuildOccurrence = proto.Field( + proto.MESSAGE, + number=9, + oneof='details', + message=g_build.BuildOccurrence, + ) + image: g_image.ImageOccurrence = proto.Field( + proto.MESSAGE, + number=10, + oneof='details', + message=g_image.ImageOccurrence, + ) + package: g_package.PackageOccurrence = proto.Field( + proto.MESSAGE, + number=11, + oneof='details', + message=g_package.PackageOccurrence, + ) + deployment: g_deployment.DeploymentOccurrence = proto.Field( + proto.MESSAGE, + number=12, + oneof='details', + message=g_deployment.DeploymentOccurrence, + ) + discovery: g_discovery.DiscoveryOccurrence = proto.Field( + proto.MESSAGE, + number=13, + oneof='details', + message=g_discovery.DiscoveryOccurrence, + ) + attestation: g_attestation.AttestationOccurrence = proto.Field( + proto.MESSAGE, + number=14, + oneof='details', + message=g_attestation.AttestationOccurrence, + ) + upgrade: g_upgrade.UpgradeOccurrence = proto.Field( + proto.MESSAGE, + number=15, + oneof='details', + message=g_upgrade.UpgradeOccurrence, + ) + compliance: g_compliance.ComplianceOccurrence = proto.Field( + proto.MESSAGE, + number=16, + oneof='details', + message=g_compliance.ComplianceOccurrence, + ) + dsse_attestation: g_dsse_attestation.DSSEAttestationOccurrence = proto.Field( + proto.MESSAGE, + number=17, + oneof='details', + message=g_dsse_attestation.DSSEAttestationOccurrence, + ) + sbom_reference: sbom.SBOMReferenceOccurrence = proto.Field( + proto.MESSAGE, + number=19, + oneof='details', + message=sbom.SBOMReferenceOccurrence, + ) + envelope: common.Envelope = proto.Field( + proto.MESSAGE, + number=18, + message=common.Envelope, + ) + + +class Note(proto.Message): + r"""A type of analysis that can be done for a resource. + + 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: + name (str): + Output only. The name of the note in the form of + ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. + short_description (str): + A one sentence description of this note. + long_description (str): + A detailed description of this note. + kind (grafeas.grafeas_v1.types.NoteKind): + Output only. The type of analysis. This field + can be used as a filter in list requests. + related_url (MutableSequence[grafeas.grafeas_v1.types.RelatedUrl]): + URLs associated with this note. + expiration_time (google.protobuf.timestamp_pb2.Timestamp): + Time of expiration for this note. Empty if + note does not expire. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time this note was created. + This field can be used as a filter in list + requests. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time this note was last + updated. This field can be used as a filter in + list requests. + related_note_names (MutableSequence[str]): + Other notes related to this note. + vulnerability (grafeas.grafeas_v1.types.VulnerabilityNote): + A note describing a package vulnerability. + + This field is a member of `oneof`_ ``type``. + build (grafeas.grafeas_v1.types.BuildNote): + A note describing build provenance for a + verifiable build. + + This field is a member of `oneof`_ ``type``. + image (grafeas.grafeas_v1.types.ImageNote): + A note describing a base image. + + This field is a member of `oneof`_ ``type``. + package (grafeas.grafeas_v1.types.PackageNote): + A note describing a package hosted by various + package managers. + + This field is a member of `oneof`_ ``type``. + deployment (grafeas.grafeas_v1.types.DeploymentNote): + A note describing something that can be + deployed. + + This field is a member of `oneof`_ ``type``. + discovery (grafeas.grafeas_v1.types.DiscoveryNote): + A note describing the initial analysis of a + resource. + + This field is a member of `oneof`_ ``type``. + attestation (grafeas.grafeas_v1.types.AttestationNote): + A note describing an attestation role. + + This field is a member of `oneof`_ ``type``. + upgrade (grafeas.grafeas_v1.types.UpgradeNote): + A note describing available package upgrades. + + This field is a member of `oneof`_ ``type``. + compliance (grafeas.grafeas_v1.types.ComplianceNote): + A note describing a compliance check. + + This field is a member of `oneof`_ ``type``. + dsse_attestation (grafeas.grafeas_v1.types.DSSEAttestationNote): + A note describing a dsse attestation note. + + This field is a member of `oneof`_ ``type``. + vulnerability_assessment (grafeas.grafeas_v1.types.VulnerabilityAssessmentNote): + A note describing a vulnerability assessment. + + This field is a member of `oneof`_ ``type``. + sbom_reference (grafeas.grafeas_v1.types.SBOMReferenceNote): + A note describing an SBOM reference. + + This field is a member of `oneof`_ ``type``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + short_description: str = proto.Field( + proto.STRING, + number=2, + ) + long_description: str = proto.Field( + proto.STRING, + number=3, + ) + kind: common.NoteKind = proto.Field( + proto.ENUM, + number=4, + enum=common.NoteKind, + ) + related_url: MutableSequence[common.RelatedUrl] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=common.RelatedUrl, + ) + expiration_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + related_note_names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=9, + ) + vulnerability: g_vulnerability.VulnerabilityNote = proto.Field( + proto.MESSAGE, + number=10, + oneof='type', + message=g_vulnerability.VulnerabilityNote, + ) + build: g_build.BuildNote = proto.Field( + proto.MESSAGE, + number=11, + oneof='type', + message=g_build.BuildNote, + ) + image: g_image.ImageNote = proto.Field( + proto.MESSAGE, + number=12, + oneof='type', + message=g_image.ImageNote, + ) + package: g_package.PackageNote = proto.Field( + proto.MESSAGE, + number=13, + oneof='type', + message=g_package.PackageNote, + ) + deployment: g_deployment.DeploymentNote = proto.Field( + proto.MESSAGE, + number=14, + oneof='type', + message=g_deployment.DeploymentNote, + ) + discovery: g_discovery.DiscoveryNote = proto.Field( + proto.MESSAGE, + number=15, + oneof='type', + message=g_discovery.DiscoveryNote, + ) + attestation: g_attestation.AttestationNote = proto.Field( + proto.MESSAGE, + number=16, + oneof='type', + message=g_attestation.AttestationNote, + ) + upgrade: g_upgrade.UpgradeNote = proto.Field( + proto.MESSAGE, + number=17, + oneof='type', + message=g_upgrade.UpgradeNote, + ) + compliance: g_compliance.ComplianceNote = proto.Field( + proto.MESSAGE, + number=18, + oneof='type', + message=g_compliance.ComplianceNote, + ) + dsse_attestation: g_dsse_attestation.DSSEAttestationNote = proto.Field( + proto.MESSAGE, + number=19, + oneof='type', + message=g_dsse_attestation.DSSEAttestationNote, + ) + vulnerability_assessment: vex.VulnerabilityAssessmentNote = proto.Field( + proto.MESSAGE, + number=20, + oneof='type', + message=vex.VulnerabilityAssessmentNote, + ) + sbom_reference: sbom.SBOMReferenceNote = proto.Field( + proto.MESSAGE, + number=21, + oneof='type', + message=sbom.SBOMReferenceNote, + ) + + +class GetOccurrenceRequest(proto.Message): + r"""Request to get an occurrence. + + Attributes: + name (str): + The name of the occurrence in the form of + ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListOccurrencesRequest(proto.Message): + r"""Request to list occurrences. + + Attributes: + parent (str): + The name of the project to list occurrences for in the form + of ``projects/[PROJECT_ID]``. + filter (str): + The filter expression. + page_size (int): + Number of occurrences to return in the list. + Must be positive. Max allowed page size is 1000. + If not specified, page size defaults to 20. + page_token (str): + Token to provide to skip to a particular spot + in the list. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + page_token: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListOccurrencesResponse(proto.Message): + r"""Response for listing occurrences. + + Attributes: + occurrences (MutableSequence[grafeas.grafeas_v1.types.Occurrence]): + The occurrences requested. + next_page_token (str): + The next pagination token in the list response. It should be + used as ``page_token`` for the following request. An empty + value means no more results. + """ + + @property + def raw_page(self): + return self + + occurrences: MutableSequence['Occurrence'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Occurrence', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteOccurrenceRequest(proto.Message): + r"""Request to delete an occurrence. + + Attributes: + name (str): + The name of the occurrence in the form of + ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateOccurrenceRequest(proto.Message): + r"""Request to create a new occurrence. + + Attributes: + parent (str): + The name of the project in the form of + ``projects/[PROJECT_ID]``, under which the occurrence is to + be created. + occurrence (grafeas.grafeas_v1.types.Occurrence): + The occurrence to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + occurrence: 'Occurrence' = proto.Field( + proto.MESSAGE, + number=2, + message='Occurrence', + ) + + +class UpdateOccurrenceRequest(proto.Message): + r"""Request to update an occurrence. + + Attributes: + name (str): + The name of the occurrence in the form of + ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. + occurrence (grafeas.grafeas_v1.types.Occurrence): + The updated occurrence. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The fields to update. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + occurrence: 'Occurrence' = proto.Field( + proto.MESSAGE, + number=2, + message='Occurrence', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class GetNoteRequest(proto.Message): + r"""Request to get a note. + + Attributes: + name (str): + The name of the note in the form of + ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetOccurrenceNoteRequest(proto.Message): + r"""Request to get the note to which the specified occurrence is + attached. + + Attributes: + name (str): + The name of the occurrence in the form of + ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListNotesRequest(proto.Message): + r"""Request to list notes. + + Attributes: + parent (str): + The name of the project to list notes for in the form of + ``projects/[PROJECT_ID]``. + filter (str): + The filter expression. + page_size (int): + Number of notes to return in the list. Must + be positive. Max allowed page size is 1000. If + not specified, page size defaults to 20. + page_token (str): + Token to provide to skip to a particular spot + in the list. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + page_token: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListNotesResponse(proto.Message): + r"""Response for listing notes. + + Attributes: + notes (MutableSequence[grafeas.grafeas_v1.types.Note]): + The notes requested. + next_page_token (str): + The next pagination token in the list response. It should be + used as ``page_token`` for the following request. An empty + value means no more results. + """ + + @property + def raw_page(self): + return self + + notes: MutableSequence['Note'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Note', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteNoteRequest(proto.Message): + r"""Request to delete a note. + + Attributes: + name (str): + The name of the note in the form of + ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateNoteRequest(proto.Message): + r"""Request to create a new note. + + Attributes: + parent (str): + The name of the project in the form of + ``projects/[PROJECT_ID]``, under which the note is to be + created. + note_id (str): + The ID to use for this note. + note (grafeas.grafeas_v1.types.Note): + The note to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + note_id: str = proto.Field( + proto.STRING, + number=2, + ) + note: 'Note' = proto.Field( + proto.MESSAGE, + number=3, + message='Note', + ) + + +class UpdateNoteRequest(proto.Message): + r"""Request to update a note. + + Attributes: + name (str): + The name of the note in the form of + ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. + note (grafeas.grafeas_v1.types.Note): + The updated note. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The fields to update. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + note: 'Note' = proto.Field( + proto.MESSAGE, + number=2, + message='Note', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class ListNoteOccurrencesRequest(proto.Message): + r"""Request to list occurrences for a note. + + Attributes: + name (str): + The name of the note to list occurrences for in the form of + ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. + filter (str): + The filter expression. + page_size (int): + Number of occurrences to return in the list. + page_token (str): + Token to provide to skip to a particular spot + in the list. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + page_token: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListNoteOccurrencesResponse(proto.Message): + r"""Response for listing occurrences for a note. + + Attributes: + occurrences (MutableSequence[grafeas.grafeas_v1.types.Occurrence]): + The occurrences attached to the specified + note. + next_page_token (str): + Token to provide to skip to a particular spot + in the list. + """ + + @property + def raw_page(self): + return self + + occurrences: MutableSequence['Occurrence'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Occurrence', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class BatchCreateNotesRequest(proto.Message): + r"""Request to create notes in batch. + + Attributes: + parent (str): + The name of the project in the form of + ``projects/[PROJECT_ID]``, under which the notes are to be + created. + notes (MutableMapping[str, grafeas.grafeas_v1.types.Note]): + The notes to create. Max allowed length is + 1000. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + notes: MutableMapping[str, 'Note'] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message='Note', + ) + + +class BatchCreateNotesResponse(proto.Message): + r"""Response for creating notes in batch. + + Attributes: + notes (MutableSequence[grafeas.grafeas_v1.types.Note]): + The notes that were created. + """ + + notes: MutableSequence['Note'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Note', + ) + + +class BatchCreateOccurrencesRequest(proto.Message): + r"""Request to create occurrences in batch. + + Attributes: + parent (str): + The name of the project in the form of + ``projects/[PROJECT_ID]``, under which the occurrences are + to be created. + occurrences (MutableSequence[grafeas.grafeas_v1.types.Occurrence]): + The occurrences to create. Max allowed length + is 1000. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + occurrences: MutableSequence['Occurrence'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Occurrence', + ) + + +class BatchCreateOccurrencesResponse(proto.Message): + r"""Response for creating occurrences in batch. + + Attributes: + occurrences (MutableSequence[grafeas.grafeas_v1.types.Occurrence]): + The occurrences that were created. + """ + + occurrences: MutableSequence['Occurrence'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Occurrence', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/image.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/image.py new file mode 100644 index 000000000000..9fde99b85808 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/image.py @@ -0,0 +1,158 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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='grafeas.v1', + manifest={ + 'Layer', + 'Fingerprint', + 'ImageNote', + 'ImageOccurrence', + }, +) + + +class Layer(proto.Message): + r"""Layer holds metadata specific to a layer of a Docker image. + + Attributes: + directive (str): + Required. The recovered Dockerfile directive + used to construct this layer. See + https://docs.docker.com/engine/reference/builder/ + for more information. + arguments (str): + The recovered arguments to the Dockerfile + directive. + """ + + directive: str = proto.Field( + proto.STRING, + number=1, + ) + arguments: str = proto.Field( + proto.STRING, + number=2, + ) + + +class Fingerprint(proto.Message): + r"""A set of properties that uniquely identify a given Docker + image. + + Attributes: + v1_name (str): + Required. The layer ID of the final layer in + the Docker image's v1 representation. + v2_blob (MutableSequence[str]): + Required. The ordered list of v2 blobs that + represent a given image. + v2_name (str): + Output only. The name of the image's v2 blobs computed via: + [bottom] := v2_blob[bottom] [N] := sha256(v2_blob[N] + " " + + v2_name[N+1]) Only the name of the final blob is kept. + """ + + v1_name: str = proto.Field( + proto.STRING, + number=1, + ) + v2_blob: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + v2_name: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ImageNote(proto.Message): + r"""Basis describes the base image portion (Note) of the DockerImage + relationship. Linked occurrences are derived from this or an + equivalent image via: FROM Or an equivalent + reference, e.g., a tag of the resource_url. + + Attributes: + resource_url (str): + Required. Immutable. The resource_url for the resource + representing the basis of associated occurrence images. + fingerprint (grafeas.grafeas_v1.types.Fingerprint): + Required. Immutable. The fingerprint of the + base image. + """ + + resource_url: str = proto.Field( + proto.STRING, + number=1, + ) + fingerprint: 'Fingerprint' = proto.Field( + proto.MESSAGE, + number=2, + message='Fingerprint', + ) + + +class ImageOccurrence(proto.Message): + r"""Details of the derived image portion of the DockerImage + relationship. This image would be produced from a Dockerfile + with FROM . + + Attributes: + fingerprint (grafeas.grafeas_v1.types.Fingerprint): + Required. The fingerprint of the derived + image. + distance (int): + Output only. The number of layers by which + this image differs from the associated image + basis. + layer_info (MutableSequence[grafeas.grafeas_v1.types.Layer]): + This contains layer-specific metadata, if populated it has + length "distance" and is ordered with [distance] being the + layer immediately following the base image and [1] being the + final layer. + base_resource_url (str): + Output only. This contains the base image URL + for the derived image occurrence. + """ + + fingerprint: 'Fingerprint' = proto.Field( + proto.MESSAGE, + number=1, + message='Fingerprint', + ) + distance: int = proto.Field( + proto.INT32, + number=2, + ) + layer_info: MutableSequence['Layer'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Layer', + ) + base_resource_url: str = proto.Field( + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/intoto_provenance.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/intoto_provenance.py new file mode 100644 index 000000000000..940bd414da8f --- /dev/null +++ b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/intoto_provenance.py @@ -0,0 +1,248 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 any_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='grafeas.v1', + manifest={ + 'Recipe', + 'Completeness', + 'Metadata', + 'BuilderConfig', + 'InTotoProvenance', + }, +) + + +class Recipe(proto.Message): + r"""Steps taken to build the artifact. + For a TaskRun, typically each container corresponds to one step + in the recipe. + + Attributes: + type_ (str): + URI indicating what type of recipe was + performed. It determines the meaning of + recipe.entryPoint, recipe.arguments, + recipe.environment, and materials. + defined_in_material (int): + Index in materials containing the recipe + steps that are not implied by recipe.type. For + example, if the recipe type were "make", then + this would point to the source containing the + Makefile, not the make program itself. Set to -1 + if the recipe doesn't come from a material, as + zero is default unset value for int64. + entry_point (str): + String identifying the entry point into the + build. This is often a path to a configuration + file and/or a target label within that file. The + syntax and meaning are defined by recipe.type. + For example, if the recipe type were "make", + then this would reference the directory in which + to run make as well as which target to use. + arguments (MutableSequence[google.protobuf.any_pb2.Any]): + Collection of all external inputs that + influenced the build on top of + recipe.definedInMaterial and recipe.entryPoint. + For example, if the recipe type were "make", + then this might be the flags passed to make + aside from the target, which is captured in + recipe.entryPoint. Since the arguments field can + greatly vary in structure, depending on the + builder and recipe type, this is of form "Any". + environment (MutableSequence[google.protobuf.any_pb2.Any]): + Any other builder-controlled inputs necessary + for correctly evaluating the recipe. Usually + only needed for reproducing the build but not + evaluated as part of policy. Since the + environment field can greatly vary in structure, + depending on the builder and recipe type, this + is of form "Any". + """ + + type_: str = proto.Field( + proto.STRING, + number=1, + ) + defined_in_material: int = proto.Field( + proto.INT64, + number=2, + ) + entry_point: str = proto.Field( + proto.STRING, + number=3, + ) + arguments: MutableSequence[any_pb2.Any] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=any_pb2.Any, + ) + environment: MutableSequence[any_pb2.Any] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=any_pb2.Any, + ) + + +class Completeness(proto.Message): + r"""Indicates that the builder claims certain fields in this + message to be complete. + + Attributes: + arguments (bool): + If true, the builder claims that + recipe.arguments is complete, meaning that all + external inputs are properly captured in the + recipe. + environment (bool): + If true, the builder claims that + recipe.environment is claimed to be complete. + materials (bool): + If true, the builder claims that materials + are complete, usually through some controls to + prevent network access. Sometimes called + "hermetic". + """ + + arguments: bool = proto.Field( + proto.BOOL, + number=1, + ) + environment: bool = proto.Field( + proto.BOOL, + number=2, + ) + materials: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class Metadata(proto.Message): + r"""Other properties of the build. + + Attributes: + build_invocation_id (str): + Identifies the particular build invocation, + which can be useful for finding associated logs + or other ad-hoc analysis. The value SHOULD be + globally unique, per in-toto Provenance spec. + build_started_on (google.protobuf.timestamp_pb2.Timestamp): + The timestamp of when the build started. + build_finished_on (google.protobuf.timestamp_pb2.Timestamp): + The timestamp of when the build completed. + completeness (grafeas.grafeas_v1.types.Completeness): + Indicates that the builder claims certain + fields in this message to be complete. + reproducible (bool): + If true, the builder claims that running the + recipe on materials will produce bit-for-bit + identical output. + """ + + build_invocation_id: str = proto.Field( + proto.STRING, + number=1, + ) + build_started_on: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + build_finished_on: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + completeness: 'Completeness' = proto.Field( + proto.MESSAGE, + number=4, + message='Completeness', + ) + reproducible: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class BuilderConfig(proto.Message): + r""" + + Attributes: + id (str): + + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + + +class InTotoProvenance(proto.Message): + r""" + + Attributes: + builder_config (grafeas.grafeas_v1.types.BuilderConfig): + required + recipe (grafeas.grafeas_v1.types.Recipe): + Identifies the configuration used for the + build. When combined with materials, this SHOULD + fully describe the build, such that re-running + this recipe results in bit-for-bit identical + output (if the build is reproducible). + metadata (grafeas.grafeas_v1.types.Metadata): + + materials (MutableSequence[str]): + The collection of artifacts that influenced + the build including sources, dependencies, build + tools, base images, and so on. This is + considered to be incomplete unless + metadata.completeness.materials is true. Unset + or null is equivalent to empty. + """ + + builder_config: 'BuilderConfig' = proto.Field( + proto.MESSAGE, + number=1, + message='BuilderConfig', + ) + recipe: 'Recipe' = proto.Field( + proto.MESSAGE, + number=2, + message='Recipe', + ) + metadata: 'Metadata' = proto.Field( + proto.MESSAGE, + number=3, + message='Metadata', + ) + materials: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/intoto_statement.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/intoto_statement.py new file mode 100644 index 000000000000..d42bddb2cdf9 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/intoto_statement.py @@ -0,0 +1,353 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from grafeas.grafeas_v1.types import intoto_provenance +from grafeas.grafeas_v1.types import slsa_provenance as g_slsa_provenance +from grafeas.grafeas_v1.types import slsa_provenance_zero_two as g_slsa_provenance_zero_two + + +__protobuf__ = proto.module( + package='grafeas.v1', + manifest={ + 'InTotoStatement', + 'Subject', + 'InTotoSlsaProvenanceV1', + }, +) + + +class InTotoStatement(proto.Message): + r"""Spec defined at + https://github.com/in-toto/attestation/tree/main/spec#statement + The serialized InTotoStatement will be stored as + Envelope.payload. Envelope.payloadType is always + "application/vnd.in-toto+json". + + 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: + type_ (str): + Always ``https://in-toto.io/Statement/v0.1``. + subject (MutableSequence[grafeas.grafeas_v1.types.Subject]): + + predicate_type (str): + ``https://slsa.dev/provenance/v0.1`` for SlsaProvenance. + provenance (grafeas.grafeas_v1.types.InTotoProvenance): + + This field is a member of `oneof`_ ``predicate``. + slsa_provenance (grafeas.grafeas_v1.types.SlsaProvenance): + + This field is a member of `oneof`_ ``predicate``. + slsa_provenance_zero_two (grafeas.grafeas_v1.types.SlsaProvenanceZeroTwo): + + This field is a member of `oneof`_ ``predicate``. + """ + + type_: str = proto.Field( + proto.STRING, + number=1, + ) + subject: MutableSequence['Subject'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Subject', + ) + predicate_type: str = proto.Field( + proto.STRING, + number=3, + ) + provenance: intoto_provenance.InTotoProvenance = proto.Field( + proto.MESSAGE, + number=4, + oneof='predicate', + message=intoto_provenance.InTotoProvenance, + ) + slsa_provenance: g_slsa_provenance.SlsaProvenance = proto.Field( + proto.MESSAGE, + number=5, + oneof='predicate', + message=g_slsa_provenance.SlsaProvenance, + ) + slsa_provenance_zero_two: g_slsa_provenance_zero_two.SlsaProvenanceZeroTwo = proto.Field( + proto.MESSAGE, + number=6, + oneof='predicate', + message=g_slsa_provenance_zero_two.SlsaProvenanceZeroTwo, + ) + + +class Subject(proto.Message): + r""" + + Attributes: + name (str): + + digest (MutableMapping[str, str]): + ``"": ""`` Algorithms can be e.g. + sha256, sha512 See + https://github.com/in-toto/attestation/blob/main/spec/field_types.md#DigestSet + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + digest: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + + +class InTotoSlsaProvenanceV1(proto.Message): + r""" + + Attributes: + type_ (str): + InToto spec defined at + https://github.com/in-toto/attestation/tree/main/spec#statement + subject (MutableSequence[grafeas.grafeas_v1.types.Subject]): + + predicate_type (str): + + predicate (grafeas.grafeas_v1.types.InTotoSlsaProvenanceV1.SlsaProvenanceV1): + + """ + + class SlsaProvenanceV1(proto.Message): + r"""Keep in sync with schema at + https://github.com/slsa-framework/slsa/blob/main/docs/provenance/schema/v1/provenance.proto + Builder renamed to ProvenanceBuilder because of Java conflicts. + + Attributes: + build_definition (grafeas.grafeas_v1.types.InTotoSlsaProvenanceV1.BuildDefinition): + + run_details (grafeas.grafeas_v1.types.InTotoSlsaProvenanceV1.RunDetails): + + """ + + build_definition: 'InTotoSlsaProvenanceV1.BuildDefinition' = proto.Field( + proto.MESSAGE, + number=1, + message='InTotoSlsaProvenanceV1.BuildDefinition', + ) + run_details: 'InTotoSlsaProvenanceV1.RunDetails' = proto.Field( + proto.MESSAGE, + number=2, + message='InTotoSlsaProvenanceV1.RunDetails', + ) + + class BuildDefinition(proto.Message): + r""" + + Attributes: + build_type (str): + + external_parameters (google.protobuf.struct_pb2.Struct): + + internal_parameters (google.protobuf.struct_pb2.Struct): + + resolved_dependencies (MutableSequence[grafeas.grafeas_v1.types.InTotoSlsaProvenanceV1.ResourceDescriptor]): + + """ + + build_type: str = proto.Field( + proto.STRING, + number=1, + ) + external_parameters: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=2, + message=struct_pb2.Struct, + ) + internal_parameters: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=3, + message=struct_pb2.Struct, + ) + resolved_dependencies: MutableSequence['InTotoSlsaProvenanceV1.ResourceDescriptor'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='InTotoSlsaProvenanceV1.ResourceDescriptor', + ) + + class ResourceDescriptor(proto.Message): + r""" + + Attributes: + name (str): + + uri (str): + + digest (MutableMapping[str, str]): + + content (bytes): + + download_location (str): + + media_type (str): + + annotations (MutableMapping[str, google.protobuf.struct_pb2.Value]): + + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + digest: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=3, + ) + content: bytes = proto.Field( + proto.BYTES, + number=4, + ) + download_location: str = proto.Field( + proto.STRING, + number=5, + ) + media_type: str = proto.Field( + proto.STRING, + number=6, + ) + annotations: MutableMapping[str, struct_pb2.Value] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=7, + message=struct_pb2.Value, + ) + + class RunDetails(proto.Message): + r""" + + Attributes: + builder (grafeas.grafeas_v1.types.InTotoSlsaProvenanceV1.ProvenanceBuilder): + + metadata (grafeas.grafeas_v1.types.InTotoSlsaProvenanceV1.BuildMetadata): + + byproducts (MutableSequence[grafeas.grafeas_v1.types.InTotoSlsaProvenanceV1.ResourceDescriptor]): + + """ + + builder: 'InTotoSlsaProvenanceV1.ProvenanceBuilder' = proto.Field( + proto.MESSAGE, + number=1, + message='InTotoSlsaProvenanceV1.ProvenanceBuilder', + ) + metadata: 'InTotoSlsaProvenanceV1.BuildMetadata' = proto.Field( + proto.MESSAGE, + number=2, + message='InTotoSlsaProvenanceV1.BuildMetadata', + ) + byproducts: MutableSequence['InTotoSlsaProvenanceV1.ResourceDescriptor'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='InTotoSlsaProvenanceV1.ResourceDescriptor', + ) + + class ProvenanceBuilder(proto.Message): + r""" + + Attributes: + id (str): + + version (MutableMapping[str, str]): + + builder_dependencies (MutableSequence[grafeas.grafeas_v1.types.InTotoSlsaProvenanceV1.ResourceDescriptor]): + + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + version: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + builder_dependencies: MutableSequence['InTotoSlsaProvenanceV1.ResourceDescriptor'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='InTotoSlsaProvenanceV1.ResourceDescriptor', + ) + + class BuildMetadata(proto.Message): + r""" + + Attributes: + invocation_id (str): + + started_on (google.protobuf.timestamp_pb2.Timestamp): + + finished_on (google.protobuf.timestamp_pb2.Timestamp): + + """ + + invocation_id: str = proto.Field( + proto.STRING, + number=1, + ) + started_on: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + finished_on: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + type_: str = proto.Field( + proto.STRING, + number=1, + ) + subject: MutableSequence['Subject'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Subject', + ) + predicate_type: str = proto.Field( + proto.STRING, + number=3, + ) + predicate: SlsaProvenanceV1 = proto.Field( + proto.MESSAGE, + number=4, + message=SlsaProvenanceV1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/package.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/package.py new file mode 100644 index 000000000000..d2402a958a94 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/package.py @@ -0,0 +1,378 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 grafeas.grafeas_v1.types import common + + +__protobuf__ = proto.module( + package='grafeas.v1', + manifest={ + 'Architecture', + 'Distribution', + 'Location', + 'PackageNote', + 'PackageOccurrence', + 'Version', + }, +) + + +class Architecture(proto.Enum): + r"""Instruction set architectures supported by various package + managers. + + Values: + ARCHITECTURE_UNSPECIFIED (0): + Unknown architecture. + X86 (1): + X86 architecture. + X64 (2): + X64 architecture. + """ + ARCHITECTURE_UNSPECIFIED = 0 + X86 = 1 + X64 = 2 + + +class Distribution(proto.Message): + r"""This represents a particular channel of distribution for a + given package. E.g., Debian's jessie-backports dpkg mirror. + + Attributes: + cpe_uri (str): + The cpe_uri in `CPE + format `__ denoting + the package manager version distributing a package. + architecture (grafeas.grafeas_v1.types.Architecture): + The CPU architecture for which packages in + this distribution channel were built. + latest_version (grafeas.grafeas_v1.types.Version): + The latest available version of this package + in this distribution channel. + maintainer (str): + A freeform string denoting the maintainer of + this package. + url (str): + The distribution channel-specific homepage + for this package. + description (str): + The distribution channel-specific description + of this package. + """ + + cpe_uri: str = proto.Field( + proto.STRING, + number=1, + ) + architecture: 'Architecture' = proto.Field( + proto.ENUM, + number=2, + enum='Architecture', + ) + latest_version: 'Version' = proto.Field( + proto.MESSAGE, + number=3, + message='Version', + ) + maintainer: str = proto.Field( + proto.STRING, + number=4, + ) + url: str = proto.Field( + proto.STRING, + number=5, + ) + description: str = proto.Field( + proto.STRING, + number=6, + ) + + +class Location(proto.Message): + r"""An occurrence of a particular package installation found within a + system's filesystem. E.g., glibc was found in + ``/var/lib/dpkg/status``. + + Attributes: + cpe_uri (str): + Deprecated. The CPE URI in `CPE + format `__ + version (grafeas.grafeas_v1.types.Version): + Deprecated. + The version installed at this location. + path (str): + The path from which we gathered that this + package/version is installed. + """ + + cpe_uri: str = proto.Field( + proto.STRING, + number=1, + ) + version: 'Version' = proto.Field( + proto.MESSAGE, + number=2, + message='Version', + ) + path: str = proto.Field( + proto.STRING, + number=3, + ) + + +class PackageNote(proto.Message): + r"""PackageNote represents a particular package version. + + Attributes: + name (str): + The name of the package. + distribution (MutableSequence[grafeas.grafeas_v1.types.Distribution]): + Deprecated. + The various channels by which a package is + distributed. + package_type (str): + The type of package; whether native or non + native (e.g., ruby gems, node.js packages, + etc.). + cpe_uri (str): + The cpe_uri in `CPE + format `__ denoting + the package manager version distributing a package. The + cpe_uri will be blank for language packages. + architecture (grafeas.grafeas_v1.types.Architecture): + The CPU architecture for which packages in + this distribution channel were built. + Architecture will be blank for language + packages. + version (grafeas.grafeas_v1.types.Version): + The version of the package. + maintainer (str): + A freeform text denoting the maintainer of + this package. + url (str): + The homepage for this package. + description (str): + The description of this package. + license_ (grafeas.grafeas_v1.types.License): + Licenses that have been declared by the + authors of the package. + digest (MutableSequence[grafeas.grafeas_v1.types.Digest]): + Hash value, typically a file digest, that + allows unique identification a specific package. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + distribution: MutableSequence['Distribution'] = proto.RepeatedField( + proto.MESSAGE, + number=10, + message='Distribution', + ) + package_type: str = proto.Field( + proto.STRING, + number=11, + ) + cpe_uri: str = proto.Field( + proto.STRING, + number=12, + ) + architecture: 'Architecture' = proto.Field( + proto.ENUM, + number=13, + enum='Architecture', + ) + version: 'Version' = proto.Field( + proto.MESSAGE, + number=14, + message='Version', + ) + maintainer: str = proto.Field( + proto.STRING, + number=15, + ) + url: str = proto.Field( + proto.STRING, + number=16, + ) + description: str = proto.Field( + proto.STRING, + number=17, + ) + license_: common.License = proto.Field( + proto.MESSAGE, + number=18, + message=common.License, + ) + digest: MutableSequence[common.Digest] = proto.RepeatedField( + proto.MESSAGE, + number=19, + message=common.Digest, + ) + + +class PackageOccurrence(proto.Message): + r"""Details on how a particular software package was installed on + a system. + + Attributes: + name (str): + The name of the installed package. + location (MutableSequence[grafeas.grafeas_v1.types.Location]): + All of the places within the filesystem + versions of this package have been found. + package_type (str): + The type of package; whether native or non + native (e.g., ruby gems, node.js packages, + etc.). + cpe_uri (str): + The cpe_uri in `CPE + format `__ denoting + the package manager version distributing a package. The + cpe_uri will be blank for language packages. + architecture (grafeas.grafeas_v1.types.Architecture): + The CPU architecture for which packages in + this distribution channel were built. + Architecture will be blank for language + packages. + license_ (grafeas.grafeas_v1.types.License): + Licenses that have been declared by the + authors of the package. + version (grafeas.grafeas_v1.types.Version): + The version of the package. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + location: MutableSequence['Location'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Location', + ) + package_type: str = proto.Field( + proto.STRING, + number=3, + ) + cpe_uri: str = proto.Field( + proto.STRING, + number=4, + ) + architecture: 'Architecture' = proto.Field( + proto.ENUM, + number=5, + enum='Architecture', + ) + license_: common.License = proto.Field( + proto.MESSAGE, + number=6, + message=common.License, + ) + version: 'Version' = proto.Field( + proto.MESSAGE, + number=7, + message='Version', + ) + + +class Version(proto.Message): + r"""Version contains structured information about the version of + a package. + + Attributes: + epoch (int): + Used to correct mistakes in the version + numbering scheme. + name (str): + Required only when version kind is NORMAL. + The main part of the version name. + revision (str): + The iteration of the package build from the + above version. + inclusive (bool): + Whether this version is specifying part of an + inclusive range. Grafeas does not have the + capability to specify version ranges; instead we + have fields that specify start version and end + versions. At times this is insufficient - we + also need to specify whether the version is + included in the range or is excluded from the + range. This boolean is expected to be set to + true when the version is included in a range. + kind (grafeas.grafeas_v1.types.Version.VersionKind): + Required. Distinguishes between sentinel + MIN/MAX versions and normal versions. + full_name (str): + Human readable version string. This string is + of the form :- and is + only set when kind is NORMAL. + """ + class VersionKind(proto.Enum): + r"""Whether this is an ordinary package version or a sentinel + MIN/MAX version. + + Values: + VERSION_KIND_UNSPECIFIED (0): + Unknown. + NORMAL (1): + A standard package version. + MINIMUM (2): + A special version representing negative + infinity. + MAXIMUM (3): + A special version representing positive + infinity. + """ + VERSION_KIND_UNSPECIFIED = 0 + NORMAL = 1 + MINIMUM = 2 + MAXIMUM = 3 + + epoch: int = proto.Field( + proto.INT32, + number=1, + ) + name: str = proto.Field( + proto.STRING, + number=2, + ) + revision: str = proto.Field( + proto.STRING, + number=3, + ) + inclusive: bool = proto.Field( + proto.BOOL, + number=6, + ) + kind: VersionKind = proto.Field( + proto.ENUM, + number=4, + enum=VersionKind, + ) + full_name: str = proto.Field( + proto.STRING, + number=5, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/provenance.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/provenance.py new file mode 100644 index 000000000000..b09cbad6cbdd --- /dev/null +++ b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/provenance.py @@ -0,0 +1,597 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='grafeas.v1', + manifest={ + 'BuildProvenance', + 'Source', + 'FileHashes', + 'Hash', + 'Command', + 'Artifact', + 'SourceContext', + 'AliasContext', + 'CloudRepoSourceContext', + 'GerritSourceContext', + 'GitSourceContext', + 'RepoId', + 'ProjectRepoId', + }, +) + + +class BuildProvenance(proto.Message): + r"""Provenance of a build. Contains all information needed to + verify the full details about the build from source to + completion. + + Attributes: + id (str): + Required. Unique identifier of the build. + project_id (str): + ID of the project. + commands (MutableSequence[grafeas.grafeas_v1.types.Command]): + Commands requested by the build. + built_artifacts (MutableSequence[grafeas.grafeas_v1.types.Artifact]): + Output of the build. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Time at which the build was created. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Time at which execution of the build was + started. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Time at which execution of the build was + finished. + creator (str): + E-mail address of the user who initiated this + build. Note that this was the user's e-mail + address at the time the build was initiated; + this address may not represent the same end-user + for all time. + logs_uri (str): + URI where any logs for this provenance were + written. + source_provenance (grafeas.grafeas_v1.types.Source): + Details of the Source input to the build. + trigger_id (str): + Trigger identifier if the build was triggered + automatically; empty if not. + build_options (MutableMapping[str, str]): + Special options applied to this build. This + is a catch-all field where build providers can + enter any desired additional details. + builder_version (str): + Version string of the builder at the time + this build was executed. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + project_id: str = proto.Field( + proto.STRING, + number=2, + ) + commands: MutableSequence['Command'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Command', + ) + built_artifacts: MutableSequence['Artifact'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Artifact', + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + creator: str = proto.Field( + proto.STRING, + number=8, + ) + logs_uri: str = proto.Field( + proto.STRING, + number=9, + ) + source_provenance: 'Source' = proto.Field( + proto.MESSAGE, + number=10, + message='Source', + ) + trigger_id: str = proto.Field( + proto.STRING, + number=11, + ) + build_options: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=12, + ) + builder_version: str = proto.Field( + proto.STRING, + number=13, + ) + + +class Source(proto.Message): + r"""Source describes the location of the source used for the + build. + + Attributes: + artifact_storage_source_uri (str): + If provided, the input binary artifacts for + the build came from this location. + file_hashes (MutableMapping[str, grafeas.grafeas_v1.types.FileHashes]): + Hash(es) of the build source, which can be + used to verify that the original source + integrity was maintained in the build. + + The keys to this map are file paths used as + build source and the values contain the hash + values for those files. + + If the build source came in a single package + such as a gzipped tarfile (.tar.gz), the + FileHash will be for the single path to that + file. + context (grafeas.grafeas_v1.types.SourceContext): + If provided, the source code used for the + build came from this location. + additional_contexts (MutableSequence[grafeas.grafeas_v1.types.SourceContext]): + If provided, some of the source code used for + the build may be found in these locations, in + the case where the source repository had + multiple remotes or submodules. This list will + not include the context specified in the context + field. + """ + + artifact_storage_source_uri: str = proto.Field( + proto.STRING, + number=1, + ) + file_hashes: MutableMapping[str, 'FileHashes'] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message='FileHashes', + ) + context: 'SourceContext' = proto.Field( + proto.MESSAGE, + number=3, + message='SourceContext', + ) + additional_contexts: MutableSequence['SourceContext'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='SourceContext', + ) + + +class FileHashes(proto.Message): + r"""Container message for hashes of byte content of files, used + in source messages to verify integrity of source input to the + build. + + Attributes: + file_hash (MutableSequence[grafeas.grafeas_v1.types.Hash]): + Required. Collection of file hashes. + """ + + file_hash: MutableSequence['Hash'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Hash', + ) + + +class Hash(proto.Message): + r"""Container message for hash values. + + Attributes: + type_ (str): + Required. The type of hash that was + performed, e.g. "SHA-256". + value (bytes): + Required. The hash value. + """ + + type_: str = proto.Field( + proto.STRING, + number=1, + ) + value: bytes = proto.Field( + proto.BYTES, + number=2, + ) + + +class Command(proto.Message): + r"""Command describes a step performed as part of the build + pipeline. + + Attributes: + name (str): + Required. Name of the command, as presented on the command + line, or if the command is packaged as a Docker container, + as presented to ``docker pull``. + env (MutableSequence[str]): + Environment variables set before running this + command. + args (MutableSequence[str]): + Command-line arguments used when executing + this command. + dir_ (str): + Working directory (relative to project source + root) used when running this command. + id (str): + Optional unique identifier for this command, used in + wait_for to reference this command as a dependency. + wait_for (MutableSequence[str]): + The ID(s) of the command(s) that this command + depends on. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + env: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + args: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + dir_: str = proto.Field( + proto.STRING, + number=4, + ) + id: str = proto.Field( + proto.STRING, + number=5, + ) + wait_for: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=6, + ) + + +class Artifact(proto.Message): + r"""Artifact describes a build product. + + Attributes: + checksum (str): + Hash or checksum value of a binary, or Docker + Registry 2.0 digest of a container. + id (str): + Artifact ID, if any; for container images, this will be a + URL by digest like + ``gcr.io/projectID/imagename@sha256:123456``. + names (MutableSequence[str]): + Related artifact names. This may be the path to a binary or + jar file, or in the case of a container build, the name used + to push the container image to Google Container Registry, as + presented to ``docker push``. Note that a single Artifact ID + can have multiple names, for example if two tags are applied + to one image. + """ + + checksum: str = proto.Field( + proto.STRING, + number=1, + ) + id: str = proto.Field( + proto.STRING, + number=2, + ) + names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class SourceContext(proto.Message): + r"""A SourceContext is a reference to a tree of files. A + SourceContext together with a path point to a unique revision of + a single file or directory. + + 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: + cloud_repo (grafeas.grafeas_v1.types.CloudRepoSourceContext): + A SourceContext referring to a revision in a + Google Cloud Source Repo. + + This field is a member of `oneof`_ ``context``. + gerrit (grafeas.grafeas_v1.types.GerritSourceContext): + A SourceContext referring to a Gerrit + project. + + This field is a member of `oneof`_ ``context``. + git (grafeas.grafeas_v1.types.GitSourceContext): + A SourceContext referring to any third party + Git repo (e.g., GitHub). + + This field is a member of `oneof`_ ``context``. + labels (MutableMapping[str, str]): + Labels with user defined metadata. + """ + + cloud_repo: 'CloudRepoSourceContext' = proto.Field( + proto.MESSAGE, + number=1, + oneof='context', + message='CloudRepoSourceContext', + ) + gerrit: 'GerritSourceContext' = proto.Field( + proto.MESSAGE, + number=2, + oneof='context', + message='GerritSourceContext', + ) + git: 'GitSourceContext' = proto.Field( + proto.MESSAGE, + number=3, + oneof='context', + message='GitSourceContext', + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + + +class AliasContext(proto.Message): + r"""An alias to a repo revision. + + Attributes: + kind (grafeas.grafeas_v1.types.AliasContext.Kind): + The alias kind. + name (str): + The alias name. + """ + class Kind(proto.Enum): + r"""The type of an alias. + + Values: + KIND_UNSPECIFIED (0): + Unknown. + FIXED (1): + Git tag. + MOVABLE (2): + Git branch. + OTHER (4): + Used to specify non-standard aliases. For + example, if a Git repo has a ref named + "refs/foo/bar". + """ + KIND_UNSPECIFIED = 0 + FIXED = 1 + MOVABLE = 2 + OTHER = 4 + + kind: Kind = proto.Field( + proto.ENUM, + number=1, + enum=Kind, + ) + name: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CloudRepoSourceContext(proto.Message): + r"""A CloudRepoSourceContext denotes a particular revision in a + Google Cloud Source Repo. + + 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: + repo_id (grafeas.grafeas_v1.types.RepoId): + The ID of the repo. + revision_id (str): + A revision ID. + + This field is a member of `oneof`_ ``revision``. + alias_context (grafeas.grafeas_v1.types.AliasContext): + An alias, which may be a branch or tag. + + This field is a member of `oneof`_ ``revision``. + """ + + repo_id: 'RepoId' = proto.Field( + proto.MESSAGE, + number=1, + message='RepoId', + ) + revision_id: str = proto.Field( + proto.STRING, + number=2, + oneof='revision', + ) + alias_context: 'AliasContext' = proto.Field( + proto.MESSAGE, + number=3, + oneof='revision', + message='AliasContext', + ) + + +class GerritSourceContext(proto.Message): + r"""A SourceContext referring to a Gerrit project. + + 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: + host_uri (str): + The URI of a running Gerrit instance. + gerrit_project (str): + The full project name within the host. + Projects may be nested, so "project/subproject" + is a valid project name. The "repo name" is the + hostURI/project. + revision_id (str): + A revision (commit) ID. + + This field is a member of `oneof`_ ``revision``. + alias_context (grafeas.grafeas_v1.types.AliasContext): + An alias, which may be a branch or tag. + + This field is a member of `oneof`_ ``revision``. + """ + + host_uri: str = proto.Field( + proto.STRING, + number=1, + ) + gerrit_project: str = proto.Field( + proto.STRING, + number=2, + ) + revision_id: str = proto.Field( + proto.STRING, + number=3, + oneof='revision', + ) + alias_context: 'AliasContext' = proto.Field( + proto.MESSAGE, + number=4, + oneof='revision', + message='AliasContext', + ) + + +class GitSourceContext(proto.Message): + r"""A GitSourceContext denotes a particular revision in a third + party Git repository (e.g., GitHub). + + Attributes: + url (str): + Git repository URL. + revision_id (str): + Git commit hash. + """ + + url: str = proto.Field( + proto.STRING, + number=1, + ) + revision_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class RepoId(proto.Message): + r"""A unique identifier for a Cloud Repo. + + 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: + project_repo_id (grafeas.grafeas_v1.types.ProjectRepoId): + A combination of a project ID and a repo + name. + + This field is a member of `oneof`_ ``id``. + uid (str): + A server-assigned, globally unique + identifier. + + This field is a member of `oneof`_ ``id``. + """ + + project_repo_id: 'ProjectRepoId' = proto.Field( + proto.MESSAGE, + number=1, + oneof='id', + message='ProjectRepoId', + ) + uid: str = proto.Field( + proto.STRING, + number=2, + oneof='id', + ) + + +class ProjectRepoId(proto.Message): + r"""Selects a repo using a Google Cloud Platform project ID + (e.g., winged-cargo-31) and a repo name within that project. + + Attributes: + project_id (str): + The ID of the project. + repo_name (str): + The name of the repo. Leave empty for the + default repo. + """ + + project_id: str = proto.Field( + proto.STRING, + number=1, + ) + repo_name: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/sbom.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/sbom.py new file mode 100644 index 000000000000..e4e85214f8c7 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/sbom.py @@ -0,0 +1,171 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 grafeas.grafeas_v1.types import common +from grafeas.grafeas_v1.types import intoto_statement + + +__protobuf__ = proto.module( + package='grafeas.v1', + manifest={ + 'SBOMReferenceNote', + 'SBOMReferenceOccurrence', + 'SbomReferenceIntotoPayload', + 'SbomReferenceIntotoPredicate', + }, +) + + +class SBOMReferenceNote(proto.Message): + r"""The note representing an SBOM reference. + + Attributes: + format_ (str): + The format that SBOM takes. E.g. may be spdx, + cyclonedx, etc... + version (str): + The version of the format that the SBOM + takes. E.g. if the format is spdx, the version + may be 2.3. + """ + + format_: str = proto.Field( + proto.STRING, + number=1, + ) + version: str = proto.Field( + proto.STRING, + number=2, + ) + + +class SBOMReferenceOccurrence(proto.Message): + r"""The occurrence representing an SBOM reference as applied to a + specific resource. The occurrence follows the DSSE + specification. See + https://github.com/secure-systems-lab/dsse/blob/master/envelope.md + for more details. + + Attributes: + payload (grafeas.grafeas_v1.types.SbomReferenceIntotoPayload): + The actual payload that contains the SBOM + reference data. + payload_type (str): + The kind of payload that + SbomReferenceIntotoPayload takes. Since it's in + the intoto format, this value is expected to be + 'application/vnd.in-toto+json'. + signatures (MutableSequence[grafeas.grafeas_v1.types.EnvelopeSignature]): + The signatures over the payload. + """ + + payload: 'SbomReferenceIntotoPayload' = proto.Field( + proto.MESSAGE, + number=1, + message='SbomReferenceIntotoPayload', + ) + payload_type: str = proto.Field( + proto.STRING, + number=2, + ) + signatures: MutableSequence[common.EnvelopeSignature] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=common.EnvelopeSignature, + ) + + +class SbomReferenceIntotoPayload(proto.Message): + r"""The actual payload that contains the SBOM Reference data. + The payload follows the intoto statement specification. See + https://github.com/in-toto/attestation/blob/main/spec/v1.0/statement.md + for more details. + + Attributes: + type_ (str): + Identifier for the schema of the Statement. + predicate_type (str): + URI identifying the type of the Predicate. + subject (MutableSequence[grafeas.grafeas_v1.types.Subject]): + Set of software artifacts that the + attestation applies to. Each element represents + a single software artifact. + predicate (grafeas.grafeas_v1.types.SbomReferenceIntotoPredicate): + Additional parameters of the Predicate. + Includes the actual data about the SBOM. + """ + + type_: str = proto.Field( + proto.STRING, + number=1, + ) + predicate_type: str = proto.Field( + proto.STRING, + number=2, + ) + subject: MutableSequence[intoto_statement.Subject] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=intoto_statement.Subject, + ) + predicate: 'SbomReferenceIntotoPredicate' = proto.Field( + proto.MESSAGE, + number=4, + message='SbomReferenceIntotoPredicate', + ) + + +class SbomReferenceIntotoPredicate(proto.Message): + r"""A predicate which describes the SBOM being referenced. + + Attributes: + referrer_id (str): + The person or system referring this predicate + to the consumer. + location (str): + The location of the SBOM. + mime_type (str): + The mime type of the SBOM. + digest (MutableMapping[str, str]): + A map of algorithm to digest of the contents + of the SBOM. + """ + + referrer_id: str = proto.Field( + proto.STRING, + number=1, + ) + location: str = proto.Field( + proto.STRING, + number=2, + ) + mime_type: str = proto.Field( + proto.STRING, + number=3, + ) + digest: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/severity.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/severity.py new file mode 100644 index 000000000000..cee526950a5c --- /dev/null +++ b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/severity.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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='grafeas.v1', + manifest={ + 'Severity', + }, +) + + +class Severity(proto.Enum): + r"""Note provider assigned severity/impact ranking. + + Values: + SEVERITY_UNSPECIFIED (0): + Unknown. + MINIMAL (1): + Minimal severity. + LOW (2): + Low severity. + MEDIUM (3): + Medium severity. + HIGH (4): + High severity. + CRITICAL (5): + Critical severity. + """ + SEVERITY_UNSPECIFIED = 0 + MINIMAL = 1 + LOW = 2 + MEDIUM = 3 + HIGH = 4 + CRITICAL = 5 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/slsa_provenance.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/slsa_provenance.py new file mode 100644 index 000000000000..9284bfed9ae0 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/slsa_provenance.py @@ -0,0 +1,258 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 any_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='grafeas.v1', + manifest={ + 'SlsaProvenance', + }, +) + + +class SlsaProvenance(proto.Message): + r""" + + Attributes: + builder (grafeas.grafeas_v1.types.SlsaProvenance.SlsaBuilder): + required + recipe (grafeas.grafeas_v1.types.SlsaProvenance.SlsaRecipe): + Identifies the configuration used for the + build. When combined with materials, this SHOULD + fully describe the build, such that re-running + this recipe results in bit-for-bit identical + output (if the build is reproducible). + metadata (grafeas.grafeas_v1.types.SlsaProvenance.SlsaMetadata): + + materials (MutableSequence[grafeas.grafeas_v1.types.SlsaProvenance.Material]): + The collection of artifacts that influenced + the build including sources, dependencies, build + tools, base images, and so on. This is + considered to be incomplete unless + metadata.completeness.materials is true. Unset + or null is equivalent to empty. + """ + + class SlsaRecipe(proto.Message): + r"""Steps taken to build the artifact. + For a TaskRun, typically each container corresponds to one step + in the recipe. + + Attributes: + type_ (str): + URI indicating what type of recipe was + performed. It determines the meaning of + recipe.entryPoint, recipe.arguments, + recipe.environment, and materials. + defined_in_material (int): + Index in materials containing the recipe + steps that are not implied by recipe.type. For + example, if the recipe type were "make", then + this would point to the source containing the + Makefile, not the make program itself. Set to -1 + if the recipe doesn't come from a material, as + zero is default unset value for int64. + entry_point (str): + String identifying the entry point into the + build. This is often a path to a configuration + file and/or a target label within that file. The + syntax and meaning are defined by recipe.type. + For example, if the recipe type were "make", + then this would reference the directory in which + to run make as well as which target to use. + arguments (google.protobuf.any_pb2.Any): + Collection of all external inputs that + influenced the build on top of + recipe.definedInMaterial and recipe.entryPoint. + For example, if the recipe type were "make", + then this might be the flags passed to make + aside from the target, which is captured in + recipe.entryPoint. Depending on the recipe Type, + the structure may be different. + environment (google.protobuf.any_pb2.Any): + Any other builder-controlled inputs necessary + for correctly evaluating the recipe. Usually + only needed for reproducing the build but not + evaluated as part of policy. Depending on the + recipe Type, the structure may be different. + """ + + type_: str = proto.Field( + proto.STRING, + number=1, + ) + defined_in_material: int = proto.Field( + proto.INT64, + number=2, + ) + entry_point: str = proto.Field( + proto.STRING, + number=3, + ) + arguments: any_pb2.Any = proto.Field( + proto.MESSAGE, + number=4, + message=any_pb2.Any, + ) + environment: any_pb2.Any = proto.Field( + proto.MESSAGE, + number=5, + message=any_pb2.Any, + ) + + class SlsaCompleteness(proto.Message): + r"""Indicates that the builder claims certain fields in this + message to be complete. + + Attributes: + arguments (bool): + If true, the builder claims that + recipe.arguments is complete, meaning that all + external inputs are properly captured in the + recipe. + environment (bool): + If true, the builder claims that + recipe.environment is claimed to be complete. + materials (bool): + If true, the builder claims that materials + are complete, usually through some controls to + prevent network access. Sometimes called + "hermetic". + """ + + arguments: bool = proto.Field( + proto.BOOL, + number=1, + ) + environment: bool = proto.Field( + proto.BOOL, + number=2, + ) + materials: bool = proto.Field( + proto.BOOL, + number=3, + ) + + class SlsaMetadata(proto.Message): + r"""Other properties of the build. + + Attributes: + build_invocation_id (str): + Identifies the particular build invocation, + which can be useful for finding associated logs + or other ad-hoc analysis. The value SHOULD be + globally unique, per in-toto Provenance spec. + build_started_on (google.protobuf.timestamp_pb2.Timestamp): + The timestamp of when the build started. + build_finished_on (google.protobuf.timestamp_pb2.Timestamp): + The timestamp of when the build completed. + completeness (grafeas.grafeas_v1.types.SlsaProvenance.SlsaCompleteness): + Indicates that the builder claims certain + fields in this message to be complete. + reproducible (bool): + If true, the builder claims that running the + recipe on materials will produce bit-for-bit + identical output. + """ + + build_invocation_id: str = proto.Field( + proto.STRING, + number=1, + ) + build_started_on: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + build_finished_on: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + completeness: 'SlsaProvenance.SlsaCompleteness' = proto.Field( + proto.MESSAGE, + number=4, + message='SlsaProvenance.SlsaCompleteness', + ) + reproducible: bool = proto.Field( + proto.BOOL, + number=5, + ) + + class SlsaBuilder(proto.Message): + r""" + + Attributes: + id (str): + + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + + class Material(proto.Message): + r""" + + Attributes: + uri (str): + + digest (MutableMapping[str, str]): + + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + digest: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + + builder: SlsaBuilder = proto.Field( + proto.MESSAGE, + number=1, + message=SlsaBuilder, + ) + recipe: SlsaRecipe = proto.Field( + proto.MESSAGE, + number=2, + message=SlsaRecipe, + ) + metadata: SlsaMetadata = proto.Field( + proto.MESSAGE, + number=3, + message=SlsaMetadata, + ) + materials: MutableSequence[Material] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=Material, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/slsa_provenance_zero_two.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/slsa_provenance_zero_two.py new file mode 100644 index 000000000000..c7bb72971913 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/slsa_provenance_zero_two.py @@ -0,0 +1,242 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='grafeas.v1', + manifest={ + 'SlsaProvenanceZeroTwo', + }, +) + + +class SlsaProvenanceZeroTwo(proto.Message): + r"""See full explanation of fields at slsa.dev/provenance/v0.2. + + Attributes: + builder (grafeas.grafeas_v1.types.SlsaProvenanceZeroTwo.SlsaBuilder): + + build_type (str): + + invocation (grafeas.grafeas_v1.types.SlsaProvenanceZeroTwo.SlsaInvocation): + + build_config (google.protobuf.struct_pb2.Struct): + + metadata (grafeas.grafeas_v1.types.SlsaProvenanceZeroTwo.SlsaMetadata): + + materials (MutableSequence[grafeas.grafeas_v1.types.SlsaProvenanceZeroTwo.SlsaMaterial]): + + """ + + class SlsaBuilder(proto.Message): + r"""Identifies the entity that executed the recipe, which is + trusted to have correctly performed the operation and populated + this provenance. + + Attributes: + id (str): + + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + + class SlsaMaterial(proto.Message): + r"""The collection of artifacts that influenced the build + including sources, dependencies, build tools, base images, and + so on. + + Attributes: + uri (str): + + digest (MutableMapping[str, str]): + + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + digest: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + + class SlsaInvocation(proto.Message): + r"""Identifies the event that kicked off the build. + + Attributes: + config_source (grafeas.grafeas_v1.types.SlsaProvenanceZeroTwo.SlsaConfigSource): + + parameters (google.protobuf.struct_pb2.Struct): + + environment (google.protobuf.struct_pb2.Struct): + + """ + + config_source: 'SlsaProvenanceZeroTwo.SlsaConfigSource' = proto.Field( + proto.MESSAGE, + number=1, + message='SlsaProvenanceZeroTwo.SlsaConfigSource', + ) + parameters: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=2, + message=struct_pb2.Struct, + ) + environment: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=3, + message=struct_pb2.Struct, + ) + + class SlsaConfigSource(proto.Message): + r"""Describes where the config file that kicked off the build + came from. This is effectively a pointer to the source where + buildConfig came from. + + Attributes: + uri (str): + + digest (MutableMapping[str, str]): + + entry_point (str): + + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + digest: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + entry_point: str = proto.Field( + proto.STRING, + number=3, + ) + + class SlsaMetadata(proto.Message): + r"""Other properties of the build. + + Attributes: + build_invocation_id (str): + + build_started_on (google.protobuf.timestamp_pb2.Timestamp): + + build_finished_on (google.protobuf.timestamp_pb2.Timestamp): + + completeness (grafeas.grafeas_v1.types.SlsaProvenanceZeroTwo.SlsaCompleteness): + + reproducible (bool): + + """ + + build_invocation_id: str = proto.Field( + proto.STRING, + number=1, + ) + build_started_on: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + build_finished_on: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + completeness: 'SlsaProvenanceZeroTwo.SlsaCompleteness' = proto.Field( + proto.MESSAGE, + number=4, + message='SlsaProvenanceZeroTwo.SlsaCompleteness', + ) + reproducible: bool = proto.Field( + proto.BOOL, + number=5, + ) + + class SlsaCompleteness(proto.Message): + r"""Indicates that the builder claims certain fields in this + message to be complete. + + Attributes: + parameters (bool): + + environment (bool): + + materials (bool): + + """ + + parameters: bool = proto.Field( + proto.BOOL, + number=1, + ) + environment: bool = proto.Field( + proto.BOOL, + number=2, + ) + materials: bool = proto.Field( + proto.BOOL, + number=3, + ) + + builder: SlsaBuilder = proto.Field( + proto.MESSAGE, + number=1, + message=SlsaBuilder, + ) + build_type: str = proto.Field( + proto.STRING, + number=2, + ) + invocation: SlsaInvocation = proto.Field( + proto.MESSAGE, + number=3, + message=SlsaInvocation, + ) + build_config: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=4, + message=struct_pb2.Struct, + ) + metadata: SlsaMetadata = proto.Field( + proto.MESSAGE, + number=5, + message=SlsaMetadata, + ) + materials: MutableSequence[SlsaMaterial] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=SlsaMaterial, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/upgrade.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/upgrade.py new file mode 100644 index 000000000000..a7181f7a083f --- /dev/null +++ b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/upgrade.py @@ -0,0 +1,266 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 timestamp_pb2 # type: ignore +from grafeas.grafeas_v1.types import package as g_package + + +__protobuf__ = proto.module( + package='grafeas.v1', + manifest={ + 'UpgradeNote', + 'UpgradeDistribution', + 'WindowsUpdate', + 'UpgradeOccurrence', + }, +) + + +class UpgradeNote(proto.Message): + r"""An Upgrade Note represents a potential upgrade of a package to a + given version. For each package version combination (i.e. bash 4.0, + bash 4.1, bash 4.1.2), there will be an Upgrade Note. For Windows, + windows_update field represents the information related to the + update. + + Attributes: + package (str): + Required for non-Windows OS. The package this + Upgrade is for. + version (grafeas.grafeas_v1.types.Version): + Required for non-Windows OS. The version of + the package in machine + human readable form. + distributions (MutableSequence[grafeas.grafeas_v1.types.UpgradeDistribution]): + Metadata about the upgrade for each specific + operating system. + windows_update (grafeas.grafeas_v1.types.WindowsUpdate): + Required for Windows OS. Represents the + metadata about the Windows update. + """ + + package: str = proto.Field( + proto.STRING, + number=1, + ) + version: g_package.Version = proto.Field( + proto.MESSAGE, + number=2, + message=g_package.Version, + ) + distributions: MutableSequence['UpgradeDistribution'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='UpgradeDistribution', + ) + windows_update: 'WindowsUpdate' = proto.Field( + proto.MESSAGE, + number=4, + message='WindowsUpdate', + ) + + +class UpgradeDistribution(proto.Message): + r"""The Upgrade Distribution represents metadata about the + Upgrade for each operating system (CPE). Some distributions have + additional metadata around updates, classifying them into + various categories and severities. + + Attributes: + cpe_uri (str): + Required - The specific operating system this + metadata applies to. See + https://cpe.mitre.org/specification/. + classification (str): + The operating system classification of this Upgrade, as + specified by the upstream operating system upgrade feed. For + Windows the classification is one of the category_ids listed + at + https://docs.microsoft.com/en-us/previous-versions/windows/desktop/ff357803(v=vs.85) + severity (str): + The severity as specified by the upstream + operating system. + cve (MutableSequence[str]): + The cve tied to this Upgrade. + """ + + cpe_uri: str = proto.Field( + proto.STRING, + number=1, + ) + classification: str = proto.Field( + proto.STRING, + number=2, + ) + severity: str = proto.Field( + proto.STRING, + number=3, + ) + cve: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + + +class WindowsUpdate(proto.Message): + r"""Windows Update represents the metadata about the update for + the Windows operating system. The fields in this message come + from the Windows Update API documented at + https://docs.microsoft.com/en-us/windows/win32/api/wuapi/nn-wuapi-iupdate. + + Attributes: + identity (grafeas.grafeas_v1.types.WindowsUpdate.Identity): + Required - The unique identifier for the + update. + title (str): + The localized title of the update. + description (str): + The localized description of the update. + categories (MutableSequence[grafeas.grafeas_v1.types.WindowsUpdate.Category]): + The list of categories to which the update + belongs. + kb_article_ids (MutableSequence[str]): + The Microsoft Knowledge Base article IDs that + are associated with the update. + support_url (str): + The hyperlink to the support information for + the update. + last_published_timestamp (google.protobuf.timestamp_pb2.Timestamp): + The last published timestamp of the update. + """ + + class Identity(proto.Message): + r"""The unique identifier of the update. + + Attributes: + update_id (str): + The revision independent identifier of the + update. + revision (int): + The revision number of the update. + """ + + update_id: str = proto.Field( + proto.STRING, + number=1, + ) + revision: int = proto.Field( + proto.INT32, + number=2, + ) + + class Category(proto.Message): + r"""The category to which the update belongs. + + Attributes: + category_id (str): + The identifier of the category. + name (str): + The localized name of the category. + """ + + category_id: str = proto.Field( + proto.STRING, + number=1, + ) + name: str = proto.Field( + proto.STRING, + number=2, + ) + + identity: Identity = proto.Field( + proto.MESSAGE, + number=1, + message=Identity, + ) + title: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + categories: MutableSequence[Category] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=Category, + ) + kb_article_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + support_url: str = proto.Field( + proto.STRING, + number=6, + ) + last_published_timestamp: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + + +class UpgradeOccurrence(proto.Message): + r"""An Upgrade Occurrence represents that a specific resource_url could + install a specific upgrade. This presence is supplied via local + sources (i.e. it is present in the mirror and the running system has + noticed its availability). For Windows, both distribution and + windows_update contain information for the Windows update. + + Attributes: + package (str): + Required for non-Windows OS. The package this + Upgrade is for. + parsed_version (grafeas.grafeas_v1.types.Version): + Required for non-Windows OS. The version of + the package in a machine + human readable form. + distribution (grafeas.grafeas_v1.types.UpgradeDistribution): + Metadata about the upgrade for available for the specific + operating system for the resource_url. This allows efficient + filtering, as well as making it easier to use the + occurrence. + windows_update (grafeas.grafeas_v1.types.WindowsUpdate): + Required for Windows OS. Represents the + metadata about the Windows update. + """ + + package: str = proto.Field( + proto.STRING, + number=1, + ) + parsed_version: g_package.Version = proto.Field( + proto.MESSAGE, + number=3, + message=g_package.Version, + ) + distribution: 'UpgradeDistribution' = proto.Field( + proto.MESSAGE, + number=4, + message='UpgradeDistribution', + ) + windows_update: 'WindowsUpdate' = proto.Field( + proto.MESSAGE, + number=5, + message='WindowsUpdate', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/vex.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/vex.py new file mode 100644 index 000000000000..813c1613f2b7 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/vex.py @@ -0,0 +1,384 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 grafeas.grafeas_v1.types import common + + +__protobuf__ = proto.module( + package='grafeas.v1', + manifest={ + 'VulnerabilityAssessmentNote', + }, +) + + +class VulnerabilityAssessmentNote(proto.Message): + r"""A single VulnerabilityAssessmentNote represents + one particular product's vulnerability assessment for one CVE. + + Attributes: + title (str): + The title of the note. E.g. ``Vex-Debian-11.4`` + short_description (str): + A one sentence description of this Vex. + long_description (str): + A detailed description of this Vex. + language_code (str): + Identifies the language used by this + document, corresponding to IETF BCP 47 / RFC + 5646. + publisher (grafeas.grafeas_v1.types.VulnerabilityAssessmentNote.Publisher): + Publisher details of this Note. + product (grafeas.grafeas_v1.types.VulnerabilityAssessmentNote.Product): + The product affected by this vex. + assessment (grafeas.grafeas_v1.types.VulnerabilityAssessmentNote.Assessment): + Represents a vulnerability assessment for the + product. + """ + + class Publisher(proto.Message): + r"""Publisher contains information about the publisher of + this Note. + (-- api-linter: core::0123::resource-annotation=disabled + aip.dev/not-precedent: Publisher is not a separate resource. --) + + Attributes: + name (str): + Name of the publisher. + Examples: 'Google', 'Google Cloud Platform'. + issuing_authority (str): + Provides information about the authority of + the issuing party to release the document, in + particular, the party's constituency and + responsibilities or other obligations. + publisher_namespace (str): + The context or namespace. + Contains a URL which is under control of the + issuing party and can be used as a globally + unique identifier for that issuing party. + Example: https://csaf.io + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + issuing_authority: str = proto.Field( + proto.STRING, + number=2, + ) + publisher_namespace: str = proto.Field( + proto.STRING, + number=3, + ) + + class Product(proto.Message): + r"""Product contains information about a product and how to + uniquely identify it. + (-- api-linter: core::0123::resource-annotation=disabled + aip.dev/not-precedent: Product is not a separate resource. --) + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Name of the product. + id (str): + Token that identifies a product so that it + can be referred to from other parts in the + document. There is no predefined format as long + as it uniquely identifies a group in the context + of the current document. + generic_uri (str): + Contains a URI which is vendor-specific. + Example: The artifact repository URL of an + image. + + This field is a member of `oneof`_ ``identifier``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + id: str = proto.Field( + proto.STRING, + number=2, + ) + generic_uri: str = proto.Field( + proto.STRING, + number=3, + oneof='identifier', + ) + + class Assessment(proto.Message): + r"""Assessment provides all information that is related to a + single vulnerability for this product. + + Attributes: + cve (str): + Holds the MITRE standard Common Vulnerabilities and + Exposures (CVE) tracking number for the vulnerability. + Deprecated: Use vulnerability_id instead to denote CVEs. + vulnerability_id (str): + The vulnerability identifier for this + Assessment. Will hold one of common identifiers + e.g. CVE, GHSA etc. + short_description (str): + A one sentence description of this Vex. + long_description (str): + A detailed description of this Vex. + related_uris (MutableSequence[grafeas.grafeas_v1.types.RelatedUrl]): + Holds a list of references associated with + this vulnerability item and assessment. These + uris have additional information about the + vulnerability and the assessment itself. E.g. + Link to a document which details how this + assessment concluded the state of this + vulnerability. + state (grafeas.grafeas_v1.types.VulnerabilityAssessmentNote.Assessment.State): + Provides the state of this Vulnerability + assessment. + impacts (MutableSequence[str]): + Contains information about the impact of this + vulnerability, this will change with time. + justification (grafeas.grafeas_v1.types.VulnerabilityAssessmentNote.Assessment.Justification): + Justification provides the justification when the state of + the assessment if NOT_AFFECTED. + remediations (MutableSequence[grafeas.grafeas_v1.types.VulnerabilityAssessmentNote.Assessment.Remediation]): + Specifies details on how to handle (and + presumably, fix) a vulnerability. + """ + class State(proto.Enum): + r"""Provides the state of this Vulnerability assessment. + + Values: + STATE_UNSPECIFIED (0): + No state is specified. + AFFECTED (1): + This product is known to be affected by this + vulnerability. + NOT_AFFECTED (2): + This product is known to be not affected by + this vulnerability. + FIXED (3): + This product contains a fix for this + vulnerability. + UNDER_INVESTIGATION (4): + It is not known yet whether these versions + are or are not affected by the vulnerability. + However, it is still under investigation. + """ + STATE_UNSPECIFIED = 0 + AFFECTED = 1 + NOT_AFFECTED = 2 + FIXED = 3 + UNDER_INVESTIGATION = 4 + + class Justification(proto.Message): + r"""Justification provides the justification when the state of the + assessment if NOT_AFFECTED. + + Attributes: + justification_type (grafeas.grafeas_v1.types.VulnerabilityAssessmentNote.Assessment.Justification.JustificationType): + The justification type for this + vulnerability. + details (str): + Additional details on why this justification + was chosen. + """ + class JustificationType(proto.Enum): + r"""Provides the type of justification. + + Values: + JUSTIFICATION_TYPE_UNSPECIFIED (0): + JUSTIFICATION_TYPE_UNSPECIFIED. + COMPONENT_NOT_PRESENT (1): + The vulnerable component is not present in + the product. + VULNERABLE_CODE_NOT_PRESENT (2): + The vulnerable code is not present. Typically + this case occurs when source code is configured + or built in a way that excludes the vulnerable + code. + VULNERABLE_CODE_NOT_IN_EXECUTE_PATH (3): + The vulnerable code can not be executed. + Typically this case occurs when the product + includes the vulnerable code but does not call + or use the vulnerable code. + VULNERABLE_CODE_CANNOT_BE_CONTROLLED_BY_ADVERSARY (4): + The vulnerable code cannot be controlled by + an attacker to exploit the vulnerability. + INLINE_MITIGATIONS_ALREADY_EXIST (5): + The product includes built-in protections or + features that prevent exploitation of the + vulnerability. These built-in protections cannot + be subverted by the attacker and cannot be + configured or disabled by the user. These + mitigations completely prevent exploitation + based on known attack vectors. + """ + JUSTIFICATION_TYPE_UNSPECIFIED = 0 + COMPONENT_NOT_PRESENT = 1 + VULNERABLE_CODE_NOT_PRESENT = 2 + VULNERABLE_CODE_NOT_IN_EXECUTE_PATH = 3 + VULNERABLE_CODE_CANNOT_BE_CONTROLLED_BY_ADVERSARY = 4 + INLINE_MITIGATIONS_ALREADY_EXIST = 5 + + justification_type: 'VulnerabilityAssessmentNote.Assessment.Justification.JustificationType' = proto.Field( + proto.ENUM, + number=1, + enum='VulnerabilityAssessmentNote.Assessment.Justification.JustificationType', + ) + details: str = proto.Field( + proto.STRING, + number=2, + ) + + class Remediation(proto.Message): + r"""Specifies details on how to handle (and presumably, fix) a + vulnerability. + + Attributes: + remediation_type (grafeas.grafeas_v1.types.VulnerabilityAssessmentNote.Assessment.Remediation.RemediationType): + The type of remediation that can be applied. + details (str): + Contains a comprehensive human-readable + discussion of the remediation. + remediation_uri (grafeas.grafeas_v1.types.RelatedUrl): + Contains the URL where to obtain the + remediation. + """ + class RemediationType(proto.Enum): + r"""The type of remediation that can be applied. + + Values: + REMEDIATION_TYPE_UNSPECIFIED (0): + No remediation type specified. + MITIGATION (1): + A MITIGATION is available. + NO_FIX_PLANNED (2): + No fix is planned. + NONE_AVAILABLE (3): + Not available. + VENDOR_FIX (4): + A vendor fix is available. + WORKAROUND (5): + A workaround is available. + """ + REMEDIATION_TYPE_UNSPECIFIED = 0 + MITIGATION = 1 + NO_FIX_PLANNED = 2 + NONE_AVAILABLE = 3 + VENDOR_FIX = 4 + WORKAROUND = 5 + + remediation_type: 'VulnerabilityAssessmentNote.Assessment.Remediation.RemediationType' = proto.Field( + proto.ENUM, + number=1, + enum='VulnerabilityAssessmentNote.Assessment.Remediation.RemediationType', + ) + details: str = proto.Field( + proto.STRING, + number=2, + ) + remediation_uri: common.RelatedUrl = proto.Field( + proto.MESSAGE, + number=3, + message=common.RelatedUrl, + ) + + cve: str = proto.Field( + proto.STRING, + number=1, + ) + vulnerability_id: str = proto.Field( + proto.STRING, + number=9, + ) + short_description: str = proto.Field( + proto.STRING, + number=2, + ) + long_description: str = proto.Field( + proto.STRING, + number=3, + ) + related_uris: MutableSequence[common.RelatedUrl] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=common.RelatedUrl, + ) + state: 'VulnerabilityAssessmentNote.Assessment.State' = proto.Field( + proto.ENUM, + number=5, + enum='VulnerabilityAssessmentNote.Assessment.State', + ) + impacts: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=6, + ) + justification: 'VulnerabilityAssessmentNote.Assessment.Justification' = proto.Field( + proto.MESSAGE, + number=7, + message='VulnerabilityAssessmentNote.Assessment.Justification', + ) + remediations: MutableSequence['VulnerabilityAssessmentNote.Assessment.Remediation'] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message='VulnerabilityAssessmentNote.Assessment.Remediation', + ) + + title: str = proto.Field( + proto.STRING, + number=1, + ) + short_description: str = proto.Field( + proto.STRING, + number=2, + ) + long_description: str = proto.Field( + proto.STRING, + number=3, + ) + language_code: str = proto.Field( + proto.STRING, + number=4, + ) + publisher: Publisher = proto.Field( + proto.MESSAGE, + number=5, + message=Publisher, + ) + product: Product = proto.Field( + proto.MESSAGE, + number=6, + message=Product, + ) + assessment: Assessment = proto.Field( + proto.MESSAGE, + number=7, + message=Assessment, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/vulnerability.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/vulnerability.py new file mode 100644 index 000000000000..97000d7d501b --- /dev/null +++ b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/vulnerability.py @@ -0,0 +1,594 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 timestamp_pb2 # type: ignore +from grafeas.grafeas_v1.types import common +from grafeas.grafeas_v1.types import cvss +from grafeas.grafeas_v1.types import package +from grafeas.grafeas_v1.types import severity as g_severity +from grafeas.grafeas_v1.types import vex + + +__protobuf__ = proto.module( + package='grafeas.v1', + manifest={ + 'VulnerabilityNote', + 'VulnerabilityOccurrence', + }, +) + + +class VulnerabilityNote(proto.Message): + r"""A security vulnerability that can be found in resources. + + Attributes: + cvss_score (float): + The CVSS score of this vulnerability. CVSS + score is on a scale of 0 - 10 where 0 indicates + low severity and 10 indicates high severity. + severity (grafeas.grafeas_v1.types.Severity): + The note provider assigned severity of this + vulnerability. + details (MutableSequence[grafeas.grafeas_v1.types.VulnerabilityNote.Detail]): + Details of all known distros and packages + affected by this vulnerability. + cvss_v3 (grafeas.grafeas_v1.types.CVSSv3): + The full description of the CVSSv3 for this + vulnerability. + windows_details (MutableSequence[grafeas.grafeas_v1.types.VulnerabilityNote.WindowsDetail]): + Windows details get their own format because + the information format and model don't match a + normal detail. Specifically Windows updates are + done as patches, thus Windows vulnerabilities + really are a missing package, rather than a + package being at an incorrect version. + source_update_time (google.protobuf.timestamp_pb2.Timestamp): + The time this information was last changed at + the source. This is an upstream timestamp from + the underlying information source - e.g. Ubuntu + security tracker. + cvss_version (grafeas.grafeas_v1.types.CVSSVersion): + CVSS version used to populate cvss_score and severity. + cvss_v2 (grafeas.grafeas_v1.types.CVSS): + The full description of the v2 CVSS for this + vulnerability. + """ + + class Detail(proto.Message): + r"""A detail for a distro and package affected by this + vulnerability and its associated fix (if one is available). + + Attributes: + severity_name (str): + The distro assigned severity of this + vulnerability. + description (str): + A vendor-specific description of this + vulnerability. + package_type (str): + The type of package; whether native or non + native (e.g., ruby gems, node.js packages, + etc.). + affected_cpe_uri (str): + Required. The `CPE + URI `__ this + vulnerability affects. + affected_package (str): + Required. The package this vulnerability + affects. + affected_version_start (grafeas.grafeas_v1.types.Version): + The version number at the start of an interval in which this + vulnerability exists. A vulnerability can affect a package + between version numbers that are disjoint sets of intervals + (example: [1.0.0-1.1.0], [2.4.6-2.4.8] and [4.5.6-4.6.8]) + each of which will be represented in its own Detail. If a + specific affected version is provided by a vulnerability + database, affected_version_start and affected_version_end + will be the same in that Detail. + affected_version_end (grafeas.grafeas_v1.types.Version): + The version number at the end of an interval in which this + vulnerability exists. A vulnerability can affect a package + between version numbers that are disjoint sets of intervals + (example: [1.0.0-1.1.0], [2.4.6-2.4.8] and [4.5.6-4.6.8]) + each of which will be represented in its own Detail. If a + specific affected version is provided by a vulnerability + database, affected_version_start and affected_version_end + will be the same in that Detail. + fixed_cpe_uri (str): + The distro recommended `CPE + URI `__ to update to + that contains a fix for this vulnerability. It is possible + for this to be different from the affected_cpe_uri. + fixed_package (str): + The distro recommended package to update to that contains a + fix for this vulnerability. It is possible for this to be + different from the affected_package. + fixed_version (grafeas.grafeas_v1.types.Version): + The distro recommended version to update to + that contains a fix for this vulnerability. + Setting this to VersionKind.MAXIMUM means no + such version is yet available. + is_obsolete (bool): + Whether this detail is obsolete. Occurrences + are expected not to point to obsolete details. + source_update_time (google.protobuf.timestamp_pb2.Timestamp): + The time this information was last changed at + the source. This is an upstream timestamp from + the underlying information source - e.g. Ubuntu + security tracker. + source (str): + The source from which the information in this + Detail was obtained. + vendor (str): + The name of the vendor of the product. + """ + + severity_name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + package_type: str = proto.Field( + proto.STRING, + number=3, + ) + affected_cpe_uri: str = proto.Field( + proto.STRING, + number=4, + ) + affected_package: str = proto.Field( + proto.STRING, + number=5, + ) + affected_version_start: package.Version = proto.Field( + proto.MESSAGE, + number=6, + message=package.Version, + ) + affected_version_end: package.Version = proto.Field( + proto.MESSAGE, + number=7, + message=package.Version, + ) + fixed_cpe_uri: str = proto.Field( + proto.STRING, + number=8, + ) + fixed_package: str = proto.Field( + proto.STRING, + number=9, + ) + fixed_version: package.Version = proto.Field( + proto.MESSAGE, + number=10, + message=package.Version, + ) + is_obsolete: bool = proto.Field( + proto.BOOL, + number=11, + ) + source_update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=12, + message=timestamp_pb2.Timestamp, + ) + source: str = proto.Field( + proto.STRING, + number=13, + ) + vendor: str = proto.Field( + proto.STRING, + number=14, + ) + + class WindowsDetail(proto.Message): + r""" + + Attributes: + cpe_uri (str): + Required. The `CPE + URI `__ this + vulnerability affects. + name (str): + Required. The name of this vulnerability. + description (str): + The description of this vulnerability. + fixing_kbs (MutableSequence[grafeas.grafeas_v1.types.VulnerabilityNote.WindowsDetail.KnowledgeBase]): + Required. The names of the KBs which have + hotfixes to mitigate this vulnerability. Note + that there may be multiple hotfixes (and thus + multiple KBs) that mitigate a given + vulnerability. Currently any listed KBs presence + is considered a fix. + """ + + class KnowledgeBase(proto.Message): + r""" + + Attributes: + name (str): + The KB name (generally of the form KB[0-9]+ (e.g., + KB123456)). + url (str): + A link to the KB in the [Windows update catalog] + (https://www.catalog.update.microsoft.com/). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + url: str = proto.Field( + proto.STRING, + number=2, + ) + + cpe_uri: str = proto.Field( + proto.STRING, + number=1, + ) + name: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + fixing_kbs: MutableSequence['VulnerabilityNote.WindowsDetail.KnowledgeBase'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='VulnerabilityNote.WindowsDetail.KnowledgeBase', + ) + + cvss_score: float = proto.Field( + proto.FLOAT, + number=1, + ) + severity: g_severity.Severity = proto.Field( + proto.ENUM, + number=2, + enum=g_severity.Severity, + ) + details: MutableSequence[Detail] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=Detail, + ) + cvss_v3: cvss.CVSSv3 = proto.Field( + proto.MESSAGE, + number=4, + message=cvss.CVSSv3, + ) + windows_details: MutableSequence[WindowsDetail] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=WindowsDetail, + ) + source_update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + cvss_version: cvss.CVSSVersion = proto.Field( + proto.ENUM, + number=7, + enum=cvss.CVSSVersion, + ) + cvss_v2: cvss.CVSS = proto.Field( + proto.MESSAGE, + number=8, + message=cvss.CVSS, + ) + + +class VulnerabilityOccurrence(proto.Message): + r"""An occurrence of a severity vulnerability on a resource. + + Attributes: + type_ (str): + The type of package; whether native or non + native (e.g., ruby gems, node.js packages, + etc.). + severity (grafeas.grafeas_v1.types.Severity): + Output only. The note provider assigned + severity of this vulnerability. + cvss_score (float): + Output only. The CVSS score of this + vulnerability. CVSS score is on a scale of 0 - + 10 where 0 indicates low severity and 10 + indicates high severity. + cvssv3 (grafeas.grafeas_v1.types.CVSS): + The cvss v3 score for the vulnerability. + package_issue (MutableSequence[grafeas.grafeas_v1.types.VulnerabilityOccurrence.PackageIssue]): + Required. The set of affected locations and + their fixes (if available) within the associated + resource. + short_description (str): + Output only. A one sentence description of + this vulnerability. + long_description (str): + Output only. A detailed description of this + vulnerability. + related_urls (MutableSequence[grafeas.grafeas_v1.types.RelatedUrl]): + Output only. URLs related to this + vulnerability. + effective_severity (grafeas.grafeas_v1.types.Severity): + The distro assigned severity for this + vulnerability when it is available, otherwise + this is the note provider assigned severity. + + When there are multiple PackageIssues for this + vulnerability, they can have different effective + severities because some might be provided by the + distro while others are provided by the language + ecosystem for a language pack. For this reason, + it is advised to use the effective severity on + the PackageIssue level. In the case where + multiple PackageIssues have differing effective + severities, this field should be the highest + severity for any of the PackageIssues. + fix_available (bool): + Output only. Whether at least one of the + affected packages has a fix available. + cvss_version (grafeas.grafeas_v1.types.CVSSVersion): + Output only. CVSS version used to populate cvss_score and + severity. + cvss_v2 (grafeas.grafeas_v1.types.CVSS): + The cvss v2 score for the vulnerability. + vex_assessment (grafeas.grafeas_v1.types.VulnerabilityOccurrence.VexAssessment): + + extra_details (str): + Occurrence-specific extra details about the + vulnerability. + """ + + class PackageIssue(proto.Message): + r"""A detail for a distro and package this vulnerability + occurrence was found in and its associated fix (if one is + available). + + Attributes: + affected_cpe_uri (str): + Required. The `CPE + URI `__ this + vulnerability was found in. + affected_package (str): + Required. The package this vulnerability was + found in. + affected_version (grafeas.grafeas_v1.types.Version): + Required. The version of the package that is + installed on the resource affected by this + vulnerability. + fixed_cpe_uri (str): + The `CPE URI `__ this + vulnerability was fixed in. It is possible for this to be + different from the affected_cpe_uri. + fixed_package (str): + The package this vulnerability was fixed in. It is possible + for this to be different from the affected_package. + fixed_version (grafeas.grafeas_v1.types.Version): + Required. The version of the package this + vulnerability was fixed in. Setting this to + VersionKind.MAXIMUM means no fix is yet + available. + fix_available (bool): + Output only. Whether a fix is available for + this package. + package_type (str): + The type of package (e.g. OS, MAVEN, GO). + effective_severity (grafeas.grafeas_v1.types.Severity): + The distro or language system assigned + severity for this vulnerability when that is + available and note provider assigned severity + when it is not available. + file_location (MutableSequence[grafeas.grafeas_v1.types.FileLocation]): + The location at which this package was found. + """ + + affected_cpe_uri: str = proto.Field( + proto.STRING, + number=1, + ) + affected_package: str = proto.Field( + proto.STRING, + number=2, + ) + affected_version: package.Version = proto.Field( + proto.MESSAGE, + number=3, + message=package.Version, + ) + fixed_cpe_uri: str = proto.Field( + proto.STRING, + number=4, + ) + fixed_package: str = proto.Field( + proto.STRING, + number=5, + ) + fixed_version: package.Version = proto.Field( + proto.MESSAGE, + number=6, + message=package.Version, + ) + fix_available: bool = proto.Field( + proto.BOOL, + number=7, + ) + package_type: str = proto.Field( + proto.STRING, + number=8, + ) + effective_severity: g_severity.Severity = proto.Field( + proto.ENUM, + number=9, + enum=g_severity.Severity, + ) + file_location: MutableSequence[common.FileLocation] = proto.RepeatedField( + proto.MESSAGE, + number=10, + message=common.FileLocation, + ) + + class VexAssessment(proto.Message): + r"""VexAssessment provides all publisher provided Vex information + that is related to this vulnerability. + + Attributes: + cve (str): + Holds the MITRE standard Common Vulnerabilities and + Exposures (CVE) tracking number for the vulnerability. + Deprecated: Use vulnerability_id instead to denote CVEs. + vulnerability_id (str): + The vulnerability identifier for this + Assessment. Will hold one of common identifiers + e.g. CVE, GHSA etc. + related_uris (MutableSequence[grafeas.grafeas_v1.types.RelatedUrl]): + Holds a list of references associated with + this vulnerability item and assessment. + note_name (str): + The VulnerabilityAssessment note from which this + VexAssessment was generated. This will be of the form: + ``projects/[PROJECT_ID]/notes/[NOTE_ID]``. (-- api-linter: + core::0122::name-suffix=disabled aip.dev/not-precedent: The + suffix is kept for consistency. --) + state (grafeas.grafeas_v1.types.VulnerabilityAssessmentNote.Assessment.State): + Provides the state of this Vulnerability + assessment. + impacts (MutableSequence[str]): + Contains information about the impact of this + vulnerability, this will change with time. + remediations (MutableSequence[grafeas.grafeas_v1.types.VulnerabilityAssessmentNote.Assessment.Remediation]): + Specifies details on how to handle (and + presumably, fix) a vulnerability. + justification (grafeas.grafeas_v1.types.VulnerabilityAssessmentNote.Assessment.Justification): + Justification provides the justification when the state of + the assessment if NOT_AFFECTED. + """ + + cve: str = proto.Field( + proto.STRING, + number=1, + ) + vulnerability_id: str = proto.Field( + proto.STRING, + number=8, + ) + related_uris: MutableSequence[common.RelatedUrl] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=common.RelatedUrl, + ) + note_name: str = proto.Field( + proto.STRING, + number=3, + ) + state: vex.VulnerabilityAssessmentNote.Assessment.State = proto.Field( + proto.ENUM, + number=4, + enum=vex.VulnerabilityAssessmentNote.Assessment.State, + ) + impacts: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + remediations: MutableSequence[vex.VulnerabilityAssessmentNote.Assessment.Remediation] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=vex.VulnerabilityAssessmentNote.Assessment.Remediation, + ) + justification: vex.VulnerabilityAssessmentNote.Assessment.Justification = proto.Field( + proto.MESSAGE, + number=7, + message=vex.VulnerabilityAssessmentNote.Assessment.Justification, + ) + + type_: str = proto.Field( + proto.STRING, + number=1, + ) + severity: g_severity.Severity = proto.Field( + proto.ENUM, + number=2, + enum=g_severity.Severity, + ) + cvss_score: float = proto.Field( + proto.FLOAT, + number=3, + ) + cvssv3: cvss.CVSS = proto.Field( + proto.MESSAGE, + number=10, + message=cvss.CVSS, + ) + package_issue: MutableSequence[PackageIssue] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=PackageIssue, + ) + short_description: str = proto.Field( + proto.STRING, + number=5, + ) + long_description: str = proto.Field( + proto.STRING, + number=6, + ) + related_urls: MutableSequence[common.RelatedUrl] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=common.RelatedUrl, + ) + effective_severity: g_severity.Severity = proto.Field( + proto.ENUM, + number=8, + enum=g_severity.Severity, + ) + fix_available: bool = proto.Field( + proto.BOOL, + number=9, + ) + cvss_version: cvss.CVSSVersion = proto.Field( + proto.ENUM, + number=11, + enum=cvss.CVSSVersion, + ) + cvss_v2: cvss.CVSS = proto.Field( + proto.MESSAGE, + number=12, + message=cvss.CVSS, + ) + vex_assessment: VexAssessment = proto.Field( + proto.MESSAGE, + number=13, + message=VexAssessment, + ) + extra_details: str = proto.Field( + proto.STRING, + number=14, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/grafeas/v1/mypy.ini b/owl-bot-staging/grafeas/v1/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/grafeas/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/grafeas/v1/noxfile.py b/owl-bot-staging/grafeas/v1/noxfile.py new file mode 100644 index 000000000000..72c4db956057 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/noxfile.py @@ -0,0 +1,280 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = 'grafeas' + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.13" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "prerelease_deps", +] + +@nox.session(python=ALL_PYTHON) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def unit(session, protobuf_implementation): + """Run the unit test suite.""" + + 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+") + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") + + # 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") + + session.run( + 'py.test', + '--quiet', + '--cov=grafeas/grafeas_v1/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)), + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + +@nox.session(python=ALL_PYTHON[-1]) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def prerelease_deps(session, protobuf_implementation): + """Run the unit test suite against pre-release versions of dependencies.""" + + 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 test environment dependencies + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + + # Install the package without dependencies + session.install('-e', '.', '--no-deps') + + # We test the minimum dependency versions using the minimum Python + # version so the lowest python runtime that we test has a corresponding constraints + # file, located at `testing/constraints--.txt`, which contains all of the + # 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 + ) + ] + + session.install(*constraints_deps) + + prerel_deps = [ + "googleapis-common-protos", + "google-api-core", + "google-auth", + # Exclude grpcio!=1.67.0rc1 which does not support python 3.13 + "grpcio!=1.67.0rc1", + "grpcio-status", + "protobuf", + "proto-plus", + ] + + for dep in prerel_deps: + session.install("--pre", "--no-deps", "--upgrade", dep) + + # Remaining dependencies + other_deps = [ + "requests", + ] + session.install(*other_deps) + + # Print out prerelease package versions + + session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") + session.run("python", "-c", "import google.auth; print(google.auth.__version__)") + session.run("python", "-c", "import grpc; print(grpc.__version__)") + session.run( + "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" + ) + session.run( + "python", "-c", "import proto; print(proto.__version__)" + ) + + session.run( + 'py.test', + '--quiet', + '--cov=grafeas/grafeas_v1/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)), + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + + +@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=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install( + 'mypy', + 'types-requests', + 'types-protobuf' + ) + session.install('.') + session.run( + 'mypy', + '-p', + 'grafeas', + ) + + +@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 docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==7.0.1", "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=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", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_notes_async.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_notes_async.py new file mode 100644 index 000000000000..9ed3ef3bae74 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_notes_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchCreateNotes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_BatchCreateNotes_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 grafeas import grafeas_v1 + + +async def sample_batch_create_notes(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.BatchCreateNotesRequest( + parent="parent_value", + ) + + # Make the request + response = await client.batch_create_notes(request=request) + + # Handle the response + print(response) + +# [END containeranalysis_v1_generated_Grafeas_BatchCreateNotes_async] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_notes_sync.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_notes_sync.py new file mode 100644 index 000000000000..096f01fd138e --- /dev/null +++ b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_notes_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchCreateNotes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_BatchCreateNotes_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 grafeas import grafeas_v1 + + +def sample_batch_create_notes(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.BatchCreateNotesRequest( + parent="parent_value", + ) + + # Make the request + response = client.batch_create_notes(request=request) + + # Handle the response + print(response) + +# [END containeranalysis_v1_generated_Grafeas_BatchCreateNotes_sync] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_occurrences_async.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_occurrences_async.py new file mode 100644 index 000000000000..10d0a30d5906 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_occurrences_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchCreateOccurrences +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_BatchCreateOccurrences_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 grafeas import grafeas_v1 + + +async def sample_batch_create_occurrences(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.BatchCreateOccurrencesRequest( + parent="parent_value", + ) + + # Make the request + response = await client.batch_create_occurrences(request=request) + + # Handle the response + print(response) + +# [END containeranalysis_v1_generated_Grafeas_BatchCreateOccurrences_async] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_occurrences_sync.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_occurrences_sync.py new file mode 100644 index 000000000000..8f3350d81758 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_occurrences_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchCreateOccurrences +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_BatchCreateOccurrences_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 grafeas import grafeas_v1 + + +def sample_batch_create_occurrences(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.BatchCreateOccurrencesRequest( + parent="parent_value", + ) + + # Make the request + response = client.batch_create_occurrences(request=request) + + # Handle the response + print(response) + +# [END containeranalysis_v1_generated_Grafeas_BatchCreateOccurrences_sync] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_note_async.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_note_async.py new file mode 100644 index 000000000000..22163012ecf9 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_note_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateNote +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_CreateNote_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 grafeas import grafeas_v1 + + +async def sample_create_note(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.CreateNoteRequest( + parent="parent_value", + note_id="note_id_value", + ) + + # Make the request + response = await client.create_note(request=request) + + # Handle the response + print(response) + +# [END containeranalysis_v1_generated_Grafeas_CreateNote_async] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_note_sync.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_note_sync.py new file mode 100644 index 000000000000..45d9b8827182 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_note_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateNote +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_CreateNote_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 grafeas import grafeas_v1 + + +def sample_create_note(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.CreateNoteRequest( + parent="parent_value", + note_id="note_id_value", + ) + + # Make the request + response = client.create_note(request=request) + + # Handle the response + print(response) + +# [END containeranalysis_v1_generated_Grafeas_CreateNote_sync] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_occurrence_async.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_occurrence_async.py new file mode 100644 index 000000000000..55ad3999e351 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_occurrence_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateOccurrence +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_CreateOccurrence_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 grafeas import grafeas_v1 + + +async def sample_create_occurrence(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.CreateOccurrenceRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_occurrence(request=request) + + # Handle the response + print(response) + +# [END containeranalysis_v1_generated_Grafeas_CreateOccurrence_async] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_occurrence_sync.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_occurrence_sync.py new file mode 100644 index 000000000000..fbb4fd13a857 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_occurrence_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateOccurrence +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_CreateOccurrence_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 grafeas import grafeas_v1 + + +def sample_create_occurrence(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.CreateOccurrenceRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_occurrence(request=request) + + # Handle the response + print(response) + +# [END containeranalysis_v1_generated_Grafeas_CreateOccurrence_sync] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_note_async.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_note_async.py new file mode 100644 index 000000000000..c128ae0f2a90 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_note_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteNote +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_DeleteNote_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 grafeas import grafeas_v1 + + +async def sample_delete_note(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.DeleteNoteRequest( + name="name_value", + ) + + # Make the request + await client.delete_note(request=request) + + +# [END containeranalysis_v1_generated_Grafeas_DeleteNote_async] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_note_sync.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_note_sync.py new file mode 100644 index 000000000000..8311e5af56c1 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_note_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteNote +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_DeleteNote_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 grafeas import grafeas_v1 + + +def sample_delete_note(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.DeleteNoteRequest( + name="name_value", + ) + + # Make the request + client.delete_note(request=request) + + +# [END containeranalysis_v1_generated_Grafeas_DeleteNote_sync] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_occurrence_async.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_occurrence_async.py new file mode 100644 index 000000000000..eb53c4ac9f81 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_occurrence_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteOccurrence +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_DeleteOccurrence_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 grafeas import grafeas_v1 + + +async def sample_delete_occurrence(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.DeleteOccurrenceRequest( + name="name_value", + ) + + # Make the request + await client.delete_occurrence(request=request) + + +# [END containeranalysis_v1_generated_Grafeas_DeleteOccurrence_async] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_occurrence_sync.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_occurrence_sync.py new file mode 100644 index 000000000000..1d3df488a391 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_occurrence_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteOccurrence +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_DeleteOccurrence_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 grafeas import grafeas_v1 + + +def sample_delete_occurrence(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.DeleteOccurrenceRequest( + name="name_value", + ) + + # Make the request + client.delete_occurrence(request=request) + + +# [END containeranalysis_v1_generated_Grafeas_DeleteOccurrence_sync] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_note_async.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_note_async.py new file mode 100644 index 000000000000..eb74332119ed --- /dev/null +++ b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_note_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetNote +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_GetNote_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 grafeas import grafeas_v1 + + +async def sample_get_note(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.GetNoteRequest( + name="name_value", + ) + + # Make the request + response = await client.get_note(request=request) + + # Handle the response + print(response) + +# [END containeranalysis_v1_generated_Grafeas_GetNote_async] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_note_sync.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_note_sync.py new file mode 100644 index 000000000000..4026633cc025 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_note_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetNote +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_GetNote_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 grafeas import grafeas_v1 + + +def sample_get_note(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.GetNoteRequest( + name="name_value", + ) + + # Make the request + response = client.get_note(request=request) + + # Handle the response + print(response) + +# [END containeranalysis_v1_generated_Grafeas_GetNote_sync] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_async.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_async.py new file mode 100644 index 000000000000..cedafd39e047 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetOccurrence +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_GetOccurrence_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 grafeas import grafeas_v1 + + +async def sample_get_occurrence(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.GetOccurrenceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_occurrence(request=request) + + # Handle the response + print(response) + +# [END containeranalysis_v1_generated_Grafeas_GetOccurrence_async] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_note_async.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_note_async.py new file mode 100644 index 000000000000..28817551ddf3 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_note_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetOccurrenceNote +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_GetOccurrenceNote_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 grafeas import grafeas_v1 + + +async def sample_get_occurrence_note(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.GetOccurrenceNoteRequest( + name="name_value", + ) + + # Make the request + response = await client.get_occurrence_note(request=request) + + # Handle the response + print(response) + +# [END containeranalysis_v1_generated_Grafeas_GetOccurrenceNote_async] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_note_sync.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_note_sync.py new file mode 100644 index 000000000000..7bf9619cccaf --- /dev/null +++ b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_note_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetOccurrenceNote +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_GetOccurrenceNote_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 grafeas import grafeas_v1 + + +def sample_get_occurrence_note(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.GetOccurrenceNoteRequest( + name="name_value", + ) + + # Make the request + response = client.get_occurrence_note(request=request) + + # Handle the response + print(response) + +# [END containeranalysis_v1_generated_Grafeas_GetOccurrenceNote_sync] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_sync.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_sync.py new file mode 100644 index 000000000000..644d7b6f2049 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetOccurrence +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_GetOccurrence_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 grafeas import grafeas_v1 + + +def sample_get_occurrence(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.GetOccurrenceRequest( + name="name_value", + ) + + # Make the request + response = client.get_occurrence(request=request) + + # Handle the response + print(response) + +# [END containeranalysis_v1_generated_Grafeas_GetOccurrence_sync] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_note_occurrences_async.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_note_occurrences_async.py new file mode 100644 index 000000000000..ea4829680ae4 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_note_occurrences_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListNoteOccurrences +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_ListNoteOccurrences_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 grafeas import grafeas_v1 + + +async def sample_list_note_occurrences(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.ListNoteOccurrencesRequest( + name="name_value", + ) + + # Make the request + page_result = client.list_note_occurrences(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END containeranalysis_v1_generated_Grafeas_ListNoteOccurrences_async] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_note_occurrences_sync.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_note_occurrences_sync.py new file mode 100644 index 000000000000..789dcba080e8 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_note_occurrences_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListNoteOccurrences +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_ListNoteOccurrences_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 grafeas import grafeas_v1 + + +def sample_list_note_occurrences(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.ListNoteOccurrencesRequest( + name="name_value", + ) + + # Make the request + page_result = client.list_note_occurrences(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END containeranalysis_v1_generated_Grafeas_ListNoteOccurrences_sync] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_notes_async.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_notes_async.py new file mode 100644 index 000000000000..488eb4dad8aa --- /dev/null +++ b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_notes_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListNotes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_ListNotes_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 grafeas import grafeas_v1 + + +async def sample_list_notes(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.ListNotesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_notes(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END containeranalysis_v1_generated_Grafeas_ListNotes_async] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_notes_sync.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_notes_sync.py new file mode 100644 index 000000000000..d1ce09fe5d61 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_notes_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListNotes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_ListNotes_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 grafeas import grafeas_v1 + + +def sample_list_notes(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.ListNotesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_notes(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END containeranalysis_v1_generated_Grafeas_ListNotes_sync] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_occurrences_async.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_occurrences_async.py new file mode 100644 index 000000000000..007d4ef85574 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_occurrences_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListOccurrences +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_ListOccurrences_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 grafeas import grafeas_v1 + + +async def sample_list_occurrences(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.ListOccurrencesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_occurrences(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END containeranalysis_v1_generated_Grafeas_ListOccurrences_async] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_occurrences_sync.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_occurrences_sync.py new file mode 100644 index 000000000000..d960929c9388 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_occurrences_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListOccurrences +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_ListOccurrences_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 grafeas import grafeas_v1 + + +def sample_list_occurrences(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.ListOccurrencesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_occurrences(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END containeranalysis_v1_generated_Grafeas_ListOccurrences_sync] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_note_async.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_note_async.py new file mode 100644 index 000000000000..5a15196348e3 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_note_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateNote +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_UpdateNote_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 grafeas import grafeas_v1 + + +async def sample_update_note(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.UpdateNoteRequest( + name="name_value", + ) + + # Make the request + response = await client.update_note(request=request) + + # Handle the response + print(response) + +# [END containeranalysis_v1_generated_Grafeas_UpdateNote_async] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_note_sync.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_note_sync.py new file mode 100644 index 000000000000..ea0db334ebc1 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_note_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateNote +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_UpdateNote_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 grafeas import grafeas_v1 + + +def sample_update_note(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.UpdateNoteRequest( + name="name_value", + ) + + # Make the request + response = client.update_note(request=request) + + # Handle the response + print(response) + +# [END containeranalysis_v1_generated_Grafeas_UpdateNote_sync] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_occurrence_async.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_occurrence_async.py new file mode 100644 index 000000000000..38d13497f807 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_occurrence_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateOccurrence +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_UpdateOccurrence_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 grafeas import grafeas_v1 + + +async def sample_update_occurrence(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.UpdateOccurrenceRequest( + name="name_value", + ) + + # Make the request + response = await client.update_occurrence(request=request) + + # Handle the response + print(response) + +# [END containeranalysis_v1_generated_Grafeas_UpdateOccurrence_async] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_occurrence_sync.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_occurrence_sync.py new file mode 100644 index 000000000000..af456757fbb8 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_occurrence_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateOccurrence +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_UpdateOccurrence_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 grafeas import grafeas_v1 + + +def sample_update_occurrence(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.UpdateOccurrenceRequest( + name="name_value", + ) + + # Make the request + response = client.update_occurrence(request=request) + + # Handle the response + print(response) + +# [END containeranalysis_v1_generated_Grafeas_UpdateOccurrence_sync] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/snippet_metadata_grafeas.v1.json b/owl-bot-staging/grafeas/v1/samples/generated_samples/snippet_metadata_grafeas.v1.json new file mode 100644 index 000000000000..290215d3171d --- /dev/null +++ b/owl-bot-staging/grafeas/v1/samples/generated_samples/snippet_metadata_grafeas.v1.json @@ -0,0 +1,2353 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "grafeas.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "grafeas", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", + "shortName": "GrafeasAsyncClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.batch_create_notes", + "method": { + "fullName": "grafeas.v1.Grafeas.BatchCreateNotes", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "BatchCreateNotes" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.BatchCreateNotesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "notes", + "type": "MutableMapping[str, grafeas.grafeas_v1.types.Note]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "grafeas.grafeas_v1.types.BatchCreateNotesResponse", + "shortName": "batch_create_notes" + }, + "description": "Sample for BatchCreateNotes", + "file": "containeranalysis_v1_generated_grafeas_batch_create_notes_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_BatchCreateNotes_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": "containeranalysis_v1_generated_grafeas_batch_create_notes_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasClient", + "shortName": "GrafeasClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasClient.batch_create_notes", + "method": { + "fullName": "grafeas.v1.Grafeas.BatchCreateNotes", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "BatchCreateNotes" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.BatchCreateNotesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "notes", + "type": "MutableMapping[str, grafeas.grafeas_v1.types.Note]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "grafeas.grafeas_v1.types.BatchCreateNotesResponse", + "shortName": "batch_create_notes" + }, + "description": "Sample for BatchCreateNotes", + "file": "containeranalysis_v1_generated_grafeas_batch_create_notes_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_BatchCreateNotes_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": "containeranalysis_v1_generated_grafeas_batch_create_notes_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", + "shortName": "GrafeasAsyncClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.batch_create_occurrences", + "method": { + "fullName": "grafeas.v1.Grafeas.BatchCreateOccurrences", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "BatchCreateOccurrences" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.BatchCreateOccurrencesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "occurrences", + "type": "MutableSequence[grafeas.grafeas_v1.types.Occurrence]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "grafeas.grafeas_v1.types.BatchCreateOccurrencesResponse", + "shortName": "batch_create_occurrences" + }, + "description": "Sample for BatchCreateOccurrences", + "file": "containeranalysis_v1_generated_grafeas_batch_create_occurrences_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_BatchCreateOccurrences_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": "containeranalysis_v1_generated_grafeas_batch_create_occurrences_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasClient", + "shortName": "GrafeasClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasClient.batch_create_occurrences", + "method": { + "fullName": "grafeas.v1.Grafeas.BatchCreateOccurrences", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "BatchCreateOccurrences" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.BatchCreateOccurrencesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "occurrences", + "type": "MutableSequence[grafeas.grafeas_v1.types.Occurrence]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "grafeas.grafeas_v1.types.BatchCreateOccurrencesResponse", + "shortName": "batch_create_occurrences" + }, + "description": "Sample for BatchCreateOccurrences", + "file": "containeranalysis_v1_generated_grafeas_batch_create_occurrences_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_BatchCreateOccurrences_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": "containeranalysis_v1_generated_grafeas_batch_create_occurrences_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", + "shortName": "GrafeasAsyncClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.create_note", + "method": { + "fullName": "grafeas.v1.Grafeas.CreateNote", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "CreateNote" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.CreateNoteRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "note_id", + "type": "str" + }, + { + "name": "note", + "type": "grafeas.grafeas_v1.types.Note" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "grafeas.grafeas_v1.types.Note", + "shortName": "create_note" + }, + "description": "Sample for CreateNote", + "file": "containeranalysis_v1_generated_grafeas_create_note_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_CreateNote_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": "containeranalysis_v1_generated_grafeas_create_note_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasClient", + "shortName": "GrafeasClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasClient.create_note", + "method": { + "fullName": "grafeas.v1.Grafeas.CreateNote", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "CreateNote" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.CreateNoteRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "note_id", + "type": "str" + }, + { + "name": "note", + "type": "grafeas.grafeas_v1.types.Note" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "grafeas.grafeas_v1.types.Note", + "shortName": "create_note" + }, + "description": "Sample for CreateNote", + "file": "containeranalysis_v1_generated_grafeas_create_note_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_CreateNote_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": "containeranalysis_v1_generated_grafeas_create_note_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", + "shortName": "GrafeasAsyncClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.create_occurrence", + "method": { + "fullName": "grafeas.v1.Grafeas.CreateOccurrence", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "CreateOccurrence" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.CreateOccurrenceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "occurrence", + "type": "grafeas.grafeas_v1.types.Occurrence" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "grafeas.grafeas_v1.types.Occurrence", + "shortName": "create_occurrence" + }, + "description": "Sample for CreateOccurrence", + "file": "containeranalysis_v1_generated_grafeas_create_occurrence_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_CreateOccurrence_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": "containeranalysis_v1_generated_grafeas_create_occurrence_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasClient", + "shortName": "GrafeasClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasClient.create_occurrence", + "method": { + "fullName": "grafeas.v1.Grafeas.CreateOccurrence", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "CreateOccurrence" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.CreateOccurrenceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "occurrence", + "type": "grafeas.grafeas_v1.types.Occurrence" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "grafeas.grafeas_v1.types.Occurrence", + "shortName": "create_occurrence" + }, + "description": "Sample for CreateOccurrence", + "file": "containeranalysis_v1_generated_grafeas_create_occurrence_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_CreateOccurrence_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": "containeranalysis_v1_generated_grafeas_create_occurrence_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", + "shortName": "GrafeasAsyncClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.delete_note", + "method": { + "fullName": "grafeas.v1.Grafeas.DeleteNote", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "DeleteNote" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.DeleteNoteRequest" + }, + { + "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_note" + }, + "description": "Sample for DeleteNote", + "file": "containeranalysis_v1_generated_grafeas_delete_note_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_DeleteNote_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": "containeranalysis_v1_generated_grafeas_delete_note_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasClient", + "shortName": "GrafeasClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasClient.delete_note", + "method": { + "fullName": "grafeas.v1.Grafeas.DeleteNote", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "DeleteNote" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.DeleteNoteRequest" + }, + { + "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_note" + }, + "description": "Sample for DeleteNote", + "file": "containeranalysis_v1_generated_grafeas_delete_note_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_DeleteNote_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": "containeranalysis_v1_generated_grafeas_delete_note_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", + "shortName": "GrafeasAsyncClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.delete_occurrence", + "method": { + "fullName": "grafeas.v1.Grafeas.DeleteOccurrence", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "DeleteOccurrence" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.DeleteOccurrenceRequest" + }, + { + "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_occurrence" + }, + "description": "Sample for DeleteOccurrence", + "file": "containeranalysis_v1_generated_grafeas_delete_occurrence_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_DeleteOccurrence_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": "containeranalysis_v1_generated_grafeas_delete_occurrence_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasClient", + "shortName": "GrafeasClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasClient.delete_occurrence", + "method": { + "fullName": "grafeas.v1.Grafeas.DeleteOccurrence", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "DeleteOccurrence" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.DeleteOccurrenceRequest" + }, + { + "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_occurrence" + }, + "description": "Sample for DeleteOccurrence", + "file": "containeranalysis_v1_generated_grafeas_delete_occurrence_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_DeleteOccurrence_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": "containeranalysis_v1_generated_grafeas_delete_occurrence_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", + "shortName": "GrafeasAsyncClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.get_note", + "method": { + "fullName": "grafeas.v1.Grafeas.GetNote", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "GetNote" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.GetNoteRequest" + }, + { + "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": "grafeas.grafeas_v1.types.Note", + "shortName": "get_note" + }, + "description": "Sample for GetNote", + "file": "containeranalysis_v1_generated_grafeas_get_note_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_GetNote_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": "containeranalysis_v1_generated_grafeas_get_note_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasClient", + "shortName": "GrafeasClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasClient.get_note", + "method": { + "fullName": "grafeas.v1.Grafeas.GetNote", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "GetNote" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.GetNoteRequest" + }, + { + "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": "grafeas.grafeas_v1.types.Note", + "shortName": "get_note" + }, + "description": "Sample for GetNote", + "file": "containeranalysis_v1_generated_grafeas_get_note_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_GetNote_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": "containeranalysis_v1_generated_grafeas_get_note_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", + "shortName": "GrafeasAsyncClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.get_occurrence_note", + "method": { + "fullName": "grafeas.v1.Grafeas.GetOccurrenceNote", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "GetOccurrenceNote" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.GetOccurrenceNoteRequest" + }, + { + "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": "grafeas.grafeas_v1.types.Note", + "shortName": "get_occurrence_note" + }, + "description": "Sample for GetOccurrenceNote", + "file": "containeranalysis_v1_generated_grafeas_get_occurrence_note_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_GetOccurrenceNote_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": "containeranalysis_v1_generated_grafeas_get_occurrence_note_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasClient", + "shortName": "GrafeasClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasClient.get_occurrence_note", + "method": { + "fullName": "grafeas.v1.Grafeas.GetOccurrenceNote", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "GetOccurrenceNote" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.GetOccurrenceNoteRequest" + }, + { + "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": "grafeas.grafeas_v1.types.Note", + "shortName": "get_occurrence_note" + }, + "description": "Sample for GetOccurrenceNote", + "file": "containeranalysis_v1_generated_grafeas_get_occurrence_note_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_GetOccurrenceNote_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": "containeranalysis_v1_generated_grafeas_get_occurrence_note_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", + "shortName": "GrafeasAsyncClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.get_occurrence", + "method": { + "fullName": "grafeas.v1.Grafeas.GetOccurrence", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "GetOccurrence" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.GetOccurrenceRequest" + }, + { + "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": "grafeas.grafeas_v1.types.Occurrence", + "shortName": "get_occurrence" + }, + "description": "Sample for GetOccurrence", + "file": "containeranalysis_v1_generated_grafeas_get_occurrence_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_GetOccurrence_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": "containeranalysis_v1_generated_grafeas_get_occurrence_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasClient", + "shortName": "GrafeasClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasClient.get_occurrence", + "method": { + "fullName": "grafeas.v1.Grafeas.GetOccurrence", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "GetOccurrence" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.GetOccurrenceRequest" + }, + { + "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": "grafeas.grafeas_v1.types.Occurrence", + "shortName": "get_occurrence" + }, + "description": "Sample for GetOccurrence", + "file": "containeranalysis_v1_generated_grafeas_get_occurrence_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_GetOccurrence_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": "containeranalysis_v1_generated_grafeas_get_occurrence_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", + "shortName": "GrafeasAsyncClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.list_note_occurrences", + "method": { + "fullName": "grafeas.v1.Grafeas.ListNoteOccurrences", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "ListNoteOccurrences" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.ListNoteOccurrencesRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "filter", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "grafeas.grafeas_v1.services.grafeas.pagers.ListNoteOccurrencesAsyncPager", + "shortName": "list_note_occurrences" + }, + "description": "Sample for ListNoteOccurrences", + "file": "containeranalysis_v1_generated_grafeas_list_note_occurrences_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_ListNoteOccurrences_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": "containeranalysis_v1_generated_grafeas_list_note_occurrences_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasClient", + "shortName": "GrafeasClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasClient.list_note_occurrences", + "method": { + "fullName": "grafeas.v1.Grafeas.ListNoteOccurrences", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "ListNoteOccurrences" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.ListNoteOccurrencesRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "filter", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "grafeas.grafeas_v1.services.grafeas.pagers.ListNoteOccurrencesPager", + "shortName": "list_note_occurrences" + }, + "description": "Sample for ListNoteOccurrences", + "file": "containeranalysis_v1_generated_grafeas_list_note_occurrences_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_ListNoteOccurrences_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": "containeranalysis_v1_generated_grafeas_list_note_occurrences_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", + "shortName": "GrafeasAsyncClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.list_notes", + "method": { + "fullName": "grafeas.v1.Grafeas.ListNotes", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "ListNotes" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.ListNotesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "filter", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "grafeas.grafeas_v1.services.grafeas.pagers.ListNotesAsyncPager", + "shortName": "list_notes" + }, + "description": "Sample for ListNotes", + "file": "containeranalysis_v1_generated_grafeas_list_notes_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_ListNotes_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": "containeranalysis_v1_generated_grafeas_list_notes_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasClient", + "shortName": "GrafeasClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasClient.list_notes", + "method": { + "fullName": "grafeas.v1.Grafeas.ListNotes", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "ListNotes" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.ListNotesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "filter", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "grafeas.grafeas_v1.services.grafeas.pagers.ListNotesPager", + "shortName": "list_notes" + }, + "description": "Sample for ListNotes", + "file": "containeranalysis_v1_generated_grafeas_list_notes_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_ListNotes_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": "containeranalysis_v1_generated_grafeas_list_notes_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", + "shortName": "GrafeasAsyncClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.list_occurrences", + "method": { + "fullName": "grafeas.v1.Grafeas.ListOccurrences", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "ListOccurrences" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.ListOccurrencesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "filter", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "grafeas.grafeas_v1.services.grafeas.pagers.ListOccurrencesAsyncPager", + "shortName": "list_occurrences" + }, + "description": "Sample for ListOccurrences", + "file": "containeranalysis_v1_generated_grafeas_list_occurrences_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_ListOccurrences_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": "containeranalysis_v1_generated_grafeas_list_occurrences_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasClient", + "shortName": "GrafeasClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasClient.list_occurrences", + "method": { + "fullName": "grafeas.v1.Grafeas.ListOccurrences", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "ListOccurrences" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.ListOccurrencesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "filter", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "grafeas.grafeas_v1.services.grafeas.pagers.ListOccurrencesPager", + "shortName": "list_occurrences" + }, + "description": "Sample for ListOccurrences", + "file": "containeranalysis_v1_generated_grafeas_list_occurrences_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_ListOccurrences_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": "containeranalysis_v1_generated_grafeas_list_occurrences_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", + "shortName": "GrafeasAsyncClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.update_note", + "method": { + "fullName": "grafeas.v1.Grafeas.UpdateNote", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "UpdateNote" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.UpdateNoteRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "note", + "type": "grafeas.grafeas_v1.types.Note" + }, + { + "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": "grafeas.grafeas_v1.types.Note", + "shortName": "update_note" + }, + "description": "Sample for UpdateNote", + "file": "containeranalysis_v1_generated_grafeas_update_note_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_UpdateNote_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": "containeranalysis_v1_generated_grafeas_update_note_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasClient", + "shortName": "GrafeasClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasClient.update_note", + "method": { + "fullName": "grafeas.v1.Grafeas.UpdateNote", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "UpdateNote" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.UpdateNoteRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "note", + "type": "grafeas.grafeas_v1.types.Note" + }, + { + "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": "grafeas.grafeas_v1.types.Note", + "shortName": "update_note" + }, + "description": "Sample for UpdateNote", + "file": "containeranalysis_v1_generated_grafeas_update_note_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_UpdateNote_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": "containeranalysis_v1_generated_grafeas_update_note_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", + "shortName": "GrafeasAsyncClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.update_occurrence", + "method": { + "fullName": "grafeas.v1.Grafeas.UpdateOccurrence", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "UpdateOccurrence" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.UpdateOccurrenceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "occurrence", + "type": "grafeas.grafeas_v1.types.Occurrence" + }, + { + "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": "grafeas.grafeas_v1.types.Occurrence", + "shortName": "update_occurrence" + }, + "description": "Sample for UpdateOccurrence", + "file": "containeranalysis_v1_generated_grafeas_update_occurrence_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_UpdateOccurrence_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": "containeranalysis_v1_generated_grafeas_update_occurrence_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasClient", + "shortName": "GrafeasClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasClient.update_occurrence", + "method": { + "fullName": "grafeas.v1.Grafeas.UpdateOccurrence", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "UpdateOccurrence" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.UpdateOccurrenceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "occurrence", + "type": "grafeas.grafeas_v1.types.Occurrence" + }, + { + "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": "grafeas.grafeas_v1.types.Occurrence", + "shortName": "update_occurrence" + }, + "description": "Sample for UpdateOccurrence", + "file": "containeranalysis_v1_generated_grafeas_update_occurrence_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_UpdateOccurrence_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": "containeranalysis_v1_generated_grafeas_update_occurrence_sync.py" + } + ] +} diff --git a/owl-bot-staging/grafeas/v1/scripts/fixup_grafeas_v1_keywords.py b/owl-bot-staging/grafeas/v1/scripts/fixup_grafeas_v1_keywords.py new file mode 100644 index 000000000000..78bae6683cc8 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/scripts/fixup_grafeas_v1_keywords.py @@ -0,0 +1,189 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 grafeasCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'batch_create_notes': ('parent', 'notes', ), + 'batch_create_occurrences': ('parent', 'occurrences', ), + 'create_note': ('parent', 'note_id', 'note', ), + 'create_occurrence': ('parent', 'occurrence', ), + 'delete_note': ('name', ), + 'delete_occurrence': ('name', ), + 'get_note': ('name', ), + 'get_occurrence': ('name', ), + 'get_occurrence_note': ('name', ), + 'list_note_occurrences': ('name', 'filter', 'page_size', 'page_token', ), + 'list_notes': ('parent', 'filter', 'page_size', 'page_token', ), + 'list_occurrences': ('parent', 'filter', 'page_size', 'page_token', ), + 'update_note': ('name', 'note', 'update_mask', ), + 'update_occurrence': ('name', 'occurrence', '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=grafeasCallTransformer(), +): + """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 grafeas 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/grafeas/v1/setup.py b/owl-bot-staging/grafeas/v1/setup.py new file mode 100644 index 000000000000..42545da2ab4f --- /dev/null +++ b/owl-bot-staging/grafeas/v1/setup.py @@ -0,0 +1,98 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 = 'grafeas' + + +description = "Grafeas API client library" + +version = None + +with open(os.path.join(package_root, 'grafeas/grafeas/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.0dev,!=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.0dev,!=2.24.0,!=2.25.0", + "proto-plus >= 1.22.3, <2.0.0dev", + "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'", + "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", +] +extras = { +} +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/grafeas" + +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("grafeas") +] + +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/grafeas/v1/testing/constraints-3.10.txt b/owl-bot-staging/grafeas/v1/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/testing/constraints-3.10.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/grafeas/v1/testing/constraints-3.11.txt b/owl-bot-staging/grafeas/v1/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/testing/constraints-3.11.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/grafeas/v1/testing/constraints-3.12.txt b/owl-bot-staging/grafeas/v1/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/testing/constraints-3.12.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/grafeas/v1/testing/constraints-3.13.txt b/owl-bot-staging/grafeas/v1/testing/constraints-3.13.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/testing/constraints-3.13.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/grafeas/v1/testing/constraints-3.7.txt b/owl-bot-staging/grafeas/v1/testing/constraints-3.7.txt new file mode 100644 index 000000000000..fc812592b0ee --- /dev/null +++ b/owl-bot-staging/grafeas/v1/testing/constraints-3.7.txt @@ -0,0 +1,10 @@ +# 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.0dev", +# 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 diff --git a/owl-bot-staging/grafeas/v1/testing/constraints-3.8.txt b/owl-bot-staging/grafeas/v1/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/testing/constraints-3.8.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/grafeas/v1/testing/constraints-3.9.txt b/owl-bot-staging/grafeas/v1/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/testing/constraints-3.9.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/grafeas/v1/tests/__init__.py b/owl-bot-staging/grafeas/v1/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/grafeas/v1/tests/unit/__init__.py b/owl-bot-staging/grafeas/v1/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/grafeas/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/grafeas/v1/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/grafeas/v1/tests/unit/gapic/grafeas_v1/__init__.py b/owl-bot-staging/grafeas/v1/tests/unit/gapic/grafeas_v1/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/tests/unit/gapic/grafeas_v1/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/grafeas/v1/tests/unit/gapic/grafeas_v1/test_grafeas.py b/owl-bot-staging/grafeas/v1/tests/unit/gapic/grafeas_v1/test_grafeas.py new file mode 100644 index 000000000000..d227ae4d2f80 --- /dev/null +++ b/owl-bot-staging/grafeas/v1/tests/unit/gapic/grafeas_v1/test_grafeas.py @@ -0,0 +1,11993 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 any_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from grafeas.grafeas_v1.services.grafeas import GrafeasAsyncClient +from grafeas.grafeas_v1.services.grafeas import GrafeasClient +from grafeas.grafeas_v1.services.grafeas import pagers +from grafeas.grafeas_v1.services.grafeas import transports +from grafeas.grafeas_v1.types import attestation +from grafeas.grafeas_v1.types import build +from grafeas.grafeas_v1.types import common +from grafeas.grafeas_v1.types import compliance +from grafeas.grafeas_v1.types import cvss +from grafeas.grafeas_v1.types import deployment +from grafeas.grafeas_v1.types import discovery +from grafeas.grafeas_v1.types import dsse_attestation +from grafeas.grafeas_v1.types import grafeas +from grafeas.grafeas_v1.types import image +from grafeas.grafeas_v1.types import intoto_provenance +from grafeas.grafeas_v1.types import intoto_statement +from grafeas.grafeas_v1.types import package +from grafeas.grafeas_v1.types import provenance +from grafeas.grafeas_v1.types import sbom +from grafeas.grafeas_v1.types import severity +from grafeas.grafeas_v1.types import slsa_provenance +from grafeas.grafeas_v1.types import slsa_provenance_zero_two +from grafeas.grafeas_v1.types import upgrade +from grafeas.grafeas_v1.types import vex +from grafeas.grafeas_v1.types import vulnerability +import google.auth + + +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 GrafeasClient._get_default_mtls_endpoint(None) is None + assert GrafeasClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert GrafeasClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert GrafeasClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert GrafeasClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert GrafeasClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert GrafeasClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert GrafeasClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert GrafeasClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + GrafeasClient._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 GrafeasClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert GrafeasClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert GrafeasClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + GrafeasClient._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 GrafeasClient._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 GrafeasClient._get_client_cert_source(None, False) is None + assert GrafeasClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert GrafeasClient._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 GrafeasClient._get_client_cert_source(None, True) is mock_default_cert_source + assert GrafeasClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(GrafeasClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GrafeasClient)) +@mock.patch.object(GrafeasAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GrafeasAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = GrafeasClient._DEFAULT_UNIVERSE + default_endpoint = GrafeasClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = GrafeasClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert GrafeasClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert GrafeasClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == GrafeasClient.DEFAULT_MTLS_ENDPOINT + assert GrafeasClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert GrafeasClient._get_api_endpoint(None, None, default_universe, "always") == GrafeasClient.DEFAULT_MTLS_ENDPOINT + assert GrafeasClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == GrafeasClient.DEFAULT_MTLS_ENDPOINT + assert GrafeasClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert GrafeasClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + GrafeasClient._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 GrafeasClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert GrafeasClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert GrafeasClient._get_universe_domain(None, None) == GrafeasClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + GrafeasClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize("client_class,transport_name", [ + (GrafeasClient, "grpc"), + (GrafeasAsyncClient, "grpc_asyncio"), + (GrafeasClient, "rest"), +]) +def test_grafeas_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 == ( + 'containeranalysis.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://containeranalysis.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.GrafeasGrpcTransport, "grpc"), + (transports.GrafeasGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.GrafeasRestTransport, "rest"), +]) +def test_grafeas_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", [ + (GrafeasClient, "grpc"), + (GrafeasAsyncClient, "grpc_asyncio"), + (GrafeasClient, "rest"), +]) +def test_grafeas_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 == ( + 'containeranalysis.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://containeranalysis.googleapis.com' + ) + + +def test_grafeas_client_get_transport_class(): + transport = GrafeasClient.get_transport_class() + available_transports = [ + transports.GrafeasGrpcTransport, + transports.GrafeasRestTransport, + ] + assert transport in available_transports + + transport = GrafeasClient.get_transport_class("grpc") + assert transport == transports.GrafeasGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (GrafeasClient, transports.GrafeasGrpcTransport, "grpc"), + (GrafeasAsyncClient, transports.GrafeasGrpcAsyncIOTransport, "grpc_asyncio"), + (GrafeasClient, transports.GrafeasRestTransport, "rest"), +]) +@mock.patch.object(GrafeasClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GrafeasClient)) +@mock.patch.object(GrafeasAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GrafeasAsyncClient)) +def test_grafeas_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(GrafeasClient, '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(GrafeasClient, '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", [ + (GrafeasClient, transports.GrafeasGrpcTransport, "grpc", "true"), + (GrafeasAsyncClient, transports.GrafeasGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (GrafeasClient, transports.GrafeasGrpcTransport, "grpc", "false"), + (GrafeasAsyncClient, transports.GrafeasGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (GrafeasClient, transports.GrafeasRestTransport, "rest", "true"), + (GrafeasClient, transports.GrafeasRestTransport, "rest", "false"), +]) +@mock.patch.object(GrafeasClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GrafeasClient)) +@mock.patch.object(GrafeasAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GrafeasAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_grafeas_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", [ + GrafeasClient, GrafeasAsyncClient +]) +@mock.patch.object(GrafeasClient, "DEFAULT_ENDPOINT", modify_default_endpoint(GrafeasClient)) +@mock.patch.object(GrafeasAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(GrafeasAsyncClient)) +def test_grafeas_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", [ + GrafeasClient, GrafeasAsyncClient +]) +@mock.patch.object(GrafeasClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GrafeasClient)) +@mock.patch.object(GrafeasAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GrafeasAsyncClient)) +def test_grafeas_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = GrafeasClient._DEFAULT_UNIVERSE + default_endpoint = GrafeasClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = GrafeasClient._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", [ + (GrafeasClient, transports.GrafeasGrpcTransport, "grpc"), + (GrafeasAsyncClient, transports.GrafeasGrpcAsyncIOTransport, "grpc_asyncio"), + (GrafeasClient, transports.GrafeasRestTransport, "rest"), +]) +def test_grafeas_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", [ + (GrafeasClient, transports.GrafeasGrpcTransport, "grpc", grpc_helpers), + (GrafeasAsyncClient, transports.GrafeasGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (GrafeasClient, transports.GrafeasRestTransport, "rest", None), +]) +def test_grafeas_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_grafeas_client_client_options_from_dict(): + with mock.patch('grafeas.grafeas_v1.services.grafeas.transports.GrafeasGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = GrafeasClient( + 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", [ + (GrafeasClient, transports.GrafeasGrpcTransport, "grpc", grpc_helpers), + (GrafeasAsyncClient, transports.GrafeasGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_grafeas_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( + "containeranalysis.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( +), + scopes=None, + default_host="containeranalysis.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + grafeas.GetOccurrenceRequest, + dict, +]) +def test_get_occurrence(request_type, transport: str = 'grpc'): + client = GrafeasClient( + 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_occurrence), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Occurrence( + name='name_value', + resource_uri='resource_uri_value', + note_name='note_name_value', + kind=common.NoteKind.VULNERABILITY, + remediation='remediation_value', + ) + response = client.get_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = grafeas.GetOccurrenceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Occurrence) + assert response.name == 'name_value' + assert response.resource_uri == 'resource_uri_value' + assert response.note_name == 'note_name_value' + assert response.kind == common.NoteKind.VULNERABILITY + assert response.remediation == 'remediation_value' + + +def test_get_occurrence_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 = GrafeasClient( + 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 = grafeas.GetOccurrenceRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_occurrence), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_occurrence(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.GetOccurrenceRequest( + name='name_value', + ) + +def test_get_occurrence_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GrafeasClient( + 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_occurrence in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_occurrence] = mock_rpc + request = {} + client.get_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_occurrence(request) + + # Establish that a new wrapper 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_occurrence_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = GrafeasAsyncClient( + 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_occurrence in client._client._transport._wrapped_methods + + # 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_occurrence] = mock_rpc + + request = {} + await client.get_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_occurrence(request) + + # Establish that a new wrapper 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_occurrence_async(transport: str = 'grpc_asyncio', request_type=grafeas.GetOccurrenceRequest): + client = GrafeasAsyncClient( + 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_occurrence), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence( + name='name_value', + resource_uri='resource_uri_value', + note_name='note_name_value', + kind=common.NoteKind.VULNERABILITY, + remediation='remediation_value', + )) + response = await client.get_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = grafeas.GetOccurrenceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Occurrence) + assert response.name == 'name_value' + assert response.resource_uri == 'resource_uri_value' + assert response.note_name == 'note_name_value' + assert response.kind == common.NoteKind.VULNERABILITY + assert response.remediation == 'remediation_value' + + +@pytest.mark.asyncio +async def test_get_occurrence_async_from_dict(): + await test_get_occurrence_async(request_type=dict) + +def test_get_occurrence_field_headers(): + client = GrafeasClient( + 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 = grafeas.GetOccurrenceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_occurrence), + '__call__') as call: + call.return_value = grafeas.Occurrence() + client.get_occurrence(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_occurrence_field_headers_async(): + client = GrafeasAsyncClient( + 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 = grafeas.GetOccurrenceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_occurrence), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence()) + await client.get_occurrence(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_occurrence_flattened(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_occurrence), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Occurrence() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_occurrence( + 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_occurrence_flattened_error(): + client = GrafeasClient( + 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_occurrence( + grafeas.GetOccurrenceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_occurrence_flattened_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_occurrence), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Occurrence() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_occurrence( + 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_occurrence_flattened_error_async(): + client = GrafeasAsyncClient( + 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_occurrence( + grafeas.GetOccurrenceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + grafeas.ListOccurrencesRequest, + dict, +]) +def test_list_occurrences(request_type, transport: str = 'grpc'): + client = GrafeasClient( + 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_occurrences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.ListOccurrencesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_occurrences(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = grafeas.ListOccurrencesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListOccurrencesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_occurrences_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 = GrafeasClient( + 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 = grafeas.ListOccurrencesRequest( + parent='parent_value', + filter='filter_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_occurrences), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_occurrences(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.ListOccurrencesRequest( + parent='parent_value', + filter='filter_value', + page_token='page_token_value', + ) + +def test_list_occurrences_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GrafeasClient( + 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_occurrences in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_occurrences] = mock_rpc + request = {} + client.list_occurrences(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_occurrences(request) + + # Establish that a new wrapper 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_occurrences_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = GrafeasAsyncClient( + 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_occurrences in client._client._transport._wrapped_methods + + # 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_occurrences] = mock_rpc + + request = {} + await client.list_occurrences(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_occurrences(request) + + # Establish that a new wrapper 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_occurrences_async(transport: str = 'grpc_asyncio', request_type=grafeas.ListOccurrencesRequest): + client = GrafeasAsyncClient( + 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_occurrences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.ListOccurrencesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_occurrences(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = grafeas.ListOccurrencesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListOccurrencesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_occurrences_async_from_dict(): + await test_list_occurrences_async(request_type=dict) + +def test_list_occurrences_field_headers(): + client = GrafeasClient( + 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 = grafeas.ListOccurrencesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_occurrences), + '__call__') as call: + call.return_value = grafeas.ListOccurrencesResponse() + client.list_occurrences(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_occurrences_field_headers_async(): + client = GrafeasAsyncClient( + 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 = grafeas.ListOccurrencesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_occurrences), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.ListOccurrencesResponse()) + await client.list_occurrences(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_occurrences_flattened(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_occurrences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.ListOccurrencesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_occurrences( + parent='parent_value', + filter='filter_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].filter + mock_val = 'filter_value' + assert arg == mock_val + + +def test_list_occurrences_flattened_error(): + client = GrafeasClient( + 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_occurrences( + grafeas.ListOccurrencesRequest(), + parent='parent_value', + filter='filter_value', + ) + +@pytest.mark.asyncio +async def test_list_occurrences_flattened_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_occurrences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.ListOccurrencesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.ListOccurrencesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_occurrences( + parent='parent_value', + filter='filter_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].filter + mock_val = 'filter_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_occurrences_flattened_error_async(): + client = GrafeasAsyncClient( + 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_occurrences( + grafeas.ListOccurrencesRequest(), + parent='parent_value', + filter='filter_value', + ) + + +def test_list_occurrences_pager(transport_name: str = "grpc"): + client = GrafeasClient( + 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_occurrences), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + grafeas.ListOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + next_page_token='abc', + ), + grafeas.ListOccurrencesResponse( + occurrences=[], + next_page_token='def', + ), + grafeas.ListOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + ], + next_page_token='ghi', + ), + grafeas.ListOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_occurrences(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, grafeas.Occurrence) + for i in results) +def test_list_occurrences_pages(transport_name: str = "grpc"): + client = GrafeasClient( + 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_occurrences), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + grafeas.ListOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + next_page_token='abc', + ), + grafeas.ListOccurrencesResponse( + occurrences=[], + next_page_token='def', + ), + grafeas.ListOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + ], + next_page_token='ghi', + ), + grafeas.ListOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + ), + RuntimeError, + ) + pages = list(client.list_occurrences(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_occurrences_async_pager(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_occurrences), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + grafeas.ListOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + next_page_token='abc', + ), + grafeas.ListOccurrencesResponse( + occurrences=[], + next_page_token='def', + ), + grafeas.ListOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + ], + next_page_token='ghi', + ), + grafeas.ListOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_occurrences(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, grafeas.Occurrence) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_occurrences_async_pages(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_occurrences), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + grafeas.ListOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + next_page_token='abc', + ), + grafeas.ListOccurrencesResponse( + occurrences=[], + next_page_token='def', + ), + grafeas.ListOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + ], + next_page_token='ghi', + ), + grafeas.ListOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + ), + 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_occurrences(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", [ + grafeas.DeleteOccurrenceRequest, + dict, +]) +def test_delete_occurrence(request_type, transport: str = 'grpc'): + client = GrafeasClient( + 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_occurrence), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = grafeas.DeleteOccurrenceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_occurrence_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 = GrafeasClient( + 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 = grafeas.DeleteOccurrenceRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_occurrence), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_occurrence(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.DeleteOccurrenceRequest( + name='name_value', + ) + +def test_delete_occurrence_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GrafeasClient( + 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_occurrence in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_occurrence] = mock_rpc + request = {} + client.delete_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_occurrence(request) + + # Establish that a new wrapper 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_occurrence_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = GrafeasAsyncClient( + 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_occurrence in client._client._transport._wrapped_methods + + # 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_occurrence] = mock_rpc + + request = {} + await client.delete_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_occurrence(request) + + # Establish that a new wrapper 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_occurrence_async(transport: str = 'grpc_asyncio', request_type=grafeas.DeleteOccurrenceRequest): + client = GrafeasAsyncClient( + 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_occurrence), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = grafeas.DeleteOccurrenceRequest() + 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_occurrence_async_from_dict(): + await test_delete_occurrence_async(request_type=dict) + +def test_delete_occurrence_field_headers(): + client = GrafeasClient( + 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 = grafeas.DeleteOccurrenceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_occurrence), + '__call__') as call: + call.return_value = None + client.delete_occurrence(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_occurrence_field_headers_async(): + client = GrafeasAsyncClient( + 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 = grafeas.DeleteOccurrenceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_occurrence), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_occurrence(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_occurrence_flattened(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_occurrence), + '__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_occurrence( + 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_occurrence_flattened_error(): + client = GrafeasClient( + 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_occurrence( + grafeas.DeleteOccurrenceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_occurrence_flattened_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_occurrence), + '__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_occurrence( + 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_occurrence_flattened_error_async(): + client = GrafeasAsyncClient( + 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_occurrence( + grafeas.DeleteOccurrenceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + grafeas.CreateOccurrenceRequest, + dict, +]) +def test_create_occurrence(request_type, transport: str = 'grpc'): + client = GrafeasClient( + 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_occurrence), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Occurrence( + name='name_value', + resource_uri='resource_uri_value', + note_name='note_name_value', + kind=common.NoteKind.VULNERABILITY, + remediation='remediation_value', + ) + response = client.create_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = grafeas.CreateOccurrenceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Occurrence) + assert response.name == 'name_value' + assert response.resource_uri == 'resource_uri_value' + assert response.note_name == 'note_name_value' + assert response.kind == common.NoteKind.VULNERABILITY + assert response.remediation == 'remediation_value' + + +def test_create_occurrence_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 = GrafeasClient( + 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 = grafeas.CreateOccurrenceRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_occurrence), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_occurrence(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.CreateOccurrenceRequest( + parent='parent_value', + ) + +def test_create_occurrence_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GrafeasClient( + 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_occurrence in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_occurrence] = mock_rpc + request = {} + client.create_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_occurrence(request) + + # Establish that a new wrapper 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_occurrence_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = GrafeasAsyncClient( + 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_occurrence in client._client._transport._wrapped_methods + + # 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_occurrence] = mock_rpc + + request = {} + await client.create_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_occurrence(request) + + # Establish that a new wrapper 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_occurrence_async(transport: str = 'grpc_asyncio', request_type=grafeas.CreateOccurrenceRequest): + client = GrafeasAsyncClient( + 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_occurrence), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence( + name='name_value', + resource_uri='resource_uri_value', + note_name='note_name_value', + kind=common.NoteKind.VULNERABILITY, + remediation='remediation_value', + )) + response = await client.create_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = grafeas.CreateOccurrenceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Occurrence) + assert response.name == 'name_value' + assert response.resource_uri == 'resource_uri_value' + assert response.note_name == 'note_name_value' + assert response.kind == common.NoteKind.VULNERABILITY + assert response.remediation == 'remediation_value' + + +@pytest.mark.asyncio +async def test_create_occurrence_async_from_dict(): + await test_create_occurrence_async(request_type=dict) + +def test_create_occurrence_field_headers(): + client = GrafeasClient( + 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 = grafeas.CreateOccurrenceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_occurrence), + '__call__') as call: + call.return_value = grafeas.Occurrence() + client.create_occurrence(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_occurrence_field_headers_async(): + client = GrafeasAsyncClient( + 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 = grafeas.CreateOccurrenceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_occurrence), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence()) + await client.create_occurrence(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_occurrence_flattened(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_occurrence), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Occurrence() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_occurrence( + parent='parent_value', + occurrence=grafeas.Occurrence(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].occurrence + mock_val = grafeas.Occurrence(name='name_value') + assert arg == mock_val + + +def test_create_occurrence_flattened_error(): + client = GrafeasClient( + 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_occurrence( + grafeas.CreateOccurrenceRequest(), + parent='parent_value', + occurrence=grafeas.Occurrence(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_occurrence_flattened_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_occurrence), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Occurrence() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_occurrence( + parent='parent_value', + occurrence=grafeas.Occurrence(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].occurrence + mock_val = grafeas.Occurrence(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_occurrence_flattened_error_async(): + client = GrafeasAsyncClient( + 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_occurrence( + grafeas.CreateOccurrenceRequest(), + parent='parent_value', + occurrence=grafeas.Occurrence(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + grafeas.BatchCreateOccurrencesRequest, + dict, +]) +def test_batch_create_occurrences(request_type, transport: str = 'grpc'): + client = GrafeasClient( + 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.batch_create_occurrences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.BatchCreateOccurrencesResponse( + ) + response = client.batch_create_occurrences(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = grafeas.BatchCreateOccurrencesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.BatchCreateOccurrencesResponse) + + +def test_batch_create_occurrences_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 = GrafeasClient( + 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 = grafeas.BatchCreateOccurrencesRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_occurrences), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.batch_create_occurrences(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.BatchCreateOccurrencesRequest( + parent='parent_value', + ) + +def test_batch_create_occurrences_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GrafeasClient( + 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.batch_create_occurrences in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.batch_create_occurrences] = mock_rpc + request = {} + client.batch_create_occurrences(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_create_occurrences(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_batch_create_occurrences_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = GrafeasAsyncClient( + 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.batch_create_occurrences in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.batch_create_occurrences] = mock_rpc + + request = {} + await client.batch_create_occurrences(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.batch_create_occurrences(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_batch_create_occurrences_async(transport: str = 'grpc_asyncio', request_type=grafeas.BatchCreateOccurrencesRequest): + client = GrafeasAsyncClient( + 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.batch_create_occurrences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.BatchCreateOccurrencesResponse( + )) + response = await client.batch_create_occurrences(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = grafeas.BatchCreateOccurrencesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.BatchCreateOccurrencesResponse) + + +@pytest.mark.asyncio +async def test_batch_create_occurrences_async_from_dict(): + await test_batch_create_occurrences_async(request_type=dict) + +def test_batch_create_occurrences_field_headers(): + client = GrafeasClient( + 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 = grafeas.BatchCreateOccurrencesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_occurrences), + '__call__') as call: + call.return_value = grafeas.BatchCreateOccurrencesResponse() + client.batch_create_occurrences(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_batch_create_occurrences_field_headers_async(): + client = GrafeasAsyncClient( + 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 = grafeas.BatchCreateOccurrencesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_occurrences), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.BatchCreateOccurrencesResponse()) + await client.batch_create_occurrences(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_batch_create_occurrences_flattened(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_occurrences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.BatchCreateOccurrencesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.batch_create_occurrences( + parent='parent_value', + occurrences=[grafeas.Occurrence(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].occurrences + mock_val = [grafeas.Occurrence(name='name_value')] + assert arg == mock_val + + +def test_batch_create_occurrences_flattened_error(): + client = GrafeasClient( + 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.batch_create_occurrences( + grafeas.BatchCreateOccurrencesRequest(), + parent='parent_value', + occurrences=[grafeas.Occurrence(name='name_value')], + ) + +@pytest.mark.asyncio +async def test_batch_create_occurrences_flattened_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_occurrences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.BatchCreateOccurrencesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.BatchCreateOccurrencesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.batch_create_occurrences( + parent='parent_value', + occurrences=[grafeas.Occurrence(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].occurrences + mock_val = [grafeas.Occurrence(name='name_value')] + assert arg == mock_val + +@pytest.mark.asyncio +async def test_batch_create_occurrences_flattened_error_async(): + client = GrafeasAsyncClient( + 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.batch_create_occurrences( + grafeas.BatchCreateOccurrencesRequest(), + parent='parent_value', + occurrences=[grafeas.Occurrence(name='name_value')], + ) + + +@pytest.mark.parametrize("request_type", [ + grafeas.UpdateOccurrenceRequest, + dict, +]) +def test_update_occurrence(request_type, transport: str = 'grpc'): + client = GrafeasClient( + 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_occurrence), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Occurrence( + name='name_value', + resource_uri='resource_uri_value', + note_name='note_name_value', + kind=common.NoteKind.VULNERABILITY, + remediation='remediation_value', + ) + response = client.update_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = grafeas.UpdateOccurrenceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Occurrence) + assert response.name == 'name_value' + assert response.resource_uri == 'resource_uri_value' + assert response.note_name == 'note_name_value' + assert response.kind == common.NoteKind.VULNERABILITY + assert response.remediation == 'remediation_value' + + +def test_update_occurrence_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 = GrafeasClient( + 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 = grafeas.UpdateOccurrenceRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_occurrence), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_occurrence(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.UpdateOccurrenceRequest( + name='name_value', + ) + +def test_update_occurrence_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GrafeasClient( + 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_occurrence in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_occurrence] = mock_rpc + request = {} + client.update_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_occurrence(request) + + # Establish that a new wrapper 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_occurrence_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = GrafeasAsyncClient( + 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_occurrence in client._client._transport._wrapped_methods + + # 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_occurrence] = mock_rpc + + request = {} + await client.update_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_occurrence(request) + + # Establish that a new wrapper 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_occurrence_async(transport: str = 'grpc_asyncio', request_type=grafeas.UpdateOccurrenceRequest): + client = GrafeasAsyncClient( + 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_occurrence), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence( + name='name_value', + resource_uri='resource_uri_value', + note_name='note_name_value', + kind=common.NoteKind.VULNERABILITY, + remediation='remediation_value', + )) + response = await client.update_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = grafeas.UpdateOccurrenceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Occurrence) + assert response.name == 'name_value' + assert response.resource_uri == 'resource_uri_value' + assert response.note_name == 'note_name_value' + assert response.kind == common.NoteKind.VULNERABILITY + assert response.remediation == 'remediation_value' + + +@pytest.mark.asyncio +async def test_update_occurrence_async_from_dict(): + await test_update_occurrence_async(request_type=dict) + +def test_update_occurrence_field_headers(): + client = GrafeasClient( + 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 = grafeas.UpdateOccurrenceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_occurrence), + '__call__') as call: + call.return_value = grafeas.Occurrence() + client.update_occurrence(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_update_occurrence_field_headers_async(): + client = GrafeasAsyncClient( + 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 = grafeas.UpdateOccurrenceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_occurrence), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence()) + await client.update_occurrence(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_update_occurrence_flattened(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_occurrence), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Occurrence() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_occurrence( + name='name_value', + occurrence=grafeas.Occurrence(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].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].occurrence + mock_val = grafeas.Occurrence(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_occurrence_flattened_error(): + client = GrafeasClient( + 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_occurrence( + grafeas.UpdateOccurrenceRequest(), + name='name_value', + occurrence=grafeas.Occurrence(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_occurrence_flattened_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_occurrence), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Occurrence() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_occurrence( + name='name_value', + occurrence=grafeas.Occurrence(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].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].occurrence + mock_val = grafeas.Occurrence(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_occurrence_flattened_error_async(): + client = GrafeasAsyncClient( + 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_occurrence( + grafeas.UpdateOccurrenceRequest(), + name='name_value', + occurrence=grafeas.Occurrence(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + grafeas.GetOccurrenceNoteRequest, + dict, +]) +def test_get_occurrence_note(request_type, transport: str = 'grpc'): + client = GrafeasClient( + 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_occurrence_note), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Note( + name='name_value', + short_description='short_description_value', + long_description='long_description_value', + kind=common.NoteKind.VULNERABILITY, + related_note_names=['related_note_names_value'], + ) + response = client.get_occurrence_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = grafeas.GetOccurrenceNoteRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Note) + assert response.name == 'name_value' + assert response.short_description == 'short_description_value' + assert response.long_description == 'long_description_value' + assert response.kind == common.NoteKind.VULNERABILITY + assert response.related_note_names == ['related_note_names_value'] + + +def test_get_occurrence_note_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 = GrafeasClient( + 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 = grafeas.GetOccurrenceNoteRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_occurrence_note), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_occurrence_note(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.GetOccurrenceNoteRequest( + name='name_value', + ) + +def test_get_occurrence_note_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GrafeasClient( + 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_occurrence_note in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_occurrence_note] = mock_rpc + request = {} + client.get_occurrence_note(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_occurrence_note(request) + + # Establish that a new wrapper 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_occurrence_note_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = GrafeasAsyncClient( + 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_occurrence_note in client._client._transport._wrapped_methods + + # 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_occurrence_note] = mock_rpc + + request = {} + await client.get_occurrence_note(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_occurrence_note(request) + + # Establish that a new wrapper 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_occurrence_note_async(transport: str = 'grpc_asyncio', request_type=grafeas.GetOccurrenceNoteRequest): + client = GrafeasAsyncClient( + 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_occurrence_note), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note( + name='name_value', + short_description='short_description_value', + long_description='long_description_value', + kind=common.NoteKind.VULNERABILITY, + related_note_names=['related_note_names_value'], + )) + response = await client.get_occurrence_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = grafeas.GetOccurrenceNoteRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Note) + assert response.name == 'name_value' + assert response.short_description == 'short_description_value' + assert response.long_description == 'long_description_value' + assert response.kind == common.NoteKind.VULNERABILITY + assert response.related_note_names == ['related_note_names_value'] + + +@pytest.mark.asyncio +async def test_get_occurrence_note_async_from_dict(): + await test_get_occurrence_note_async(request_type=dict) + +def test_get_occurrence_note_field_headers(): + client = GrafeasClient( + 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 = grafeas.GetOccurrenceNoteRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_occurrence_note), + '__call__') as call: + call.return_value = grafeas.Note() + client.get_occurrence_note(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_occurrence_note_field_headers_async(): + client = GrafeasAsyncClient( + 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 = grafeas.GetOccurrenceNoteRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_occurrence_note), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) + await client.get_occurrence_note(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_occurrence_note_flattened(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_occurrence_note), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Note() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_occurrence_note( + 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_occurrence_note_flattened_error(): + client = GrafeasClient( + 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_occurrence_note( + grafeas.GetOccurrenceNoteRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_occurrence_note_flattened_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_occurrence_note), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Note() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_occurrence_note( + 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_occurrence_note_flattened_error_async(): + client = GrafeasAsyncClient( + 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_occurrence_note( + grafeas.GetOccurrenceNoteRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + grafeas.GetNoteRequest, + dict, +]) +def test_get_note(request_type, transport: str = 'grpc'): + client = GrafeasClient( + 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_note), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Note( + name='name_value', + short_description='short_description_value', + long_description='long_description_value', + kind=common.NoteKind.VULNERABILITY, + related_note_names=['related_note_names_value'], + ) + response = client.get_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = grafeas.GetNoteRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Note) + assert response.name == 'name_value' + assert response.short_description == 'short_description_value' + assert response.long_description == 'long_description_value' + assert response.kind == common.NoteKind.VULNERABILITY + assert response.related_note_names == ['related_note_names_value'] + + +def test_get_note_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 = GrafeasClient( + 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 = grafeas.GetNoteRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_note), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_note(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.GetNoteRequest( + name='name_value', + ) + +def test_get_note_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GrafeasClient( + 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_note in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_note] = mock_rpc + request = {} + client.get_note(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_note(request) + + # Establish that a new wrapper 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_note_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = GrafeasAsyncClient( + 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_note in client._client._transport._wrapped_methods + + # 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_note] = mock_rpc + + request = {} + await client.get_note(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_note(request) + + # Establish that a new wrapper 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_note_async(transport: str = 'grpc_asyncio', request_type=grafeas.GetNoteRequest): + client = GrafeasAsyncClient( + 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_note), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note( + name='name_value', + short_description='short_description_value', + long_description='long_description_value', + kind=common.NoteKind.VULNERABILITY, + related_note_names=['related_note_names_value'], + )) + response = await client.get_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = grafeas.GetNoteRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Note) + assert response.name == 'name_value' + assert response.short_description == 'short_description_value' + assert response.long_description == 'long_description_value' + assert response.kind == common.NoteKind.VULNERABILITY + assert response.related_note_names == ['related_note_names_value'] + + +@pytest.mark.asyncio +async def test_get_note_async_from_dict(): + await test_get_note_async(request_type=dict) + +def test_get_note_field_headers(): + client = GrafeasClient( + 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 = grafeas.GetNoteRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_note), + '__call__') as call: + call.return_value = grafeas.Note() + client.get_note(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_note_field_headers_async(): + client = GrafeasAsyncClient( + 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 = grafeas.GetNoteRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_note), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) + await client.get_note(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_note_flattened(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_note), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Note() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_note( + 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_note_flattened_error(): + client = GrafeasClient( + 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_note( + grafeas.GetNoteRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_note_flattened_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_note), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Note() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_note( + 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_note_flattened_error_async(): + client = GrafeasAsyncClient( + 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_note( + grafeas.GetNoteRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + grafeas.ListNotesRequest, + dict, +]) +def test_list_notes(request_type, transport: str = 'grpc'): + client = GrafeasClient( + 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_notes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.ListNotesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_notes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = grafeas.ListNotesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNotesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_notes_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 = GrafeasClient( + 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 = grafeas.ListNotesRequest( + parent='parent_value', + filter='filter_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_notes), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_notes(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.ListNotesRequest( + parent='parent_value', + filter='filter_value', + page_token='page_token_value', + ) + +def test_list_notes_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GrafeasClient( + 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_notes in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_notes] = mock_rpc + request = {} + client.list_notes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_notes(request) + + # Establish that a new wrapper 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_notes_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = GrafeasAsyncClient( + 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_notes in client._client._transport._wrapped_methods + + # 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_notes] = mock_rpc + + request = {} + await client.list_notes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_notes(request) + + # Establish that a new wrapper 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_notes_async(transport: str = 'grpc_asyncio', request_type=grafeas.ListNotesRequest): + client = GrafeasAsyncClient( + 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_notes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.ListNotesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_notes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = grafeas.ListNotesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNotesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_notes_async_from_dict(): + await test_list_notes_async(request_type=dict) + +def test_list_notes_field_headers(): + client = GrafeasClient( + 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 = grafeas.ListNotesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notes), + '__call__') as call: + call.return_value = grafeas.ListNotesResponse() + client.list_notes(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_notes_field_headers_async(): + client = GrafeasAsyncClient( + 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 = grafeas.ListNotesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notes), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.ListNotesResponse()) + await client.list_notes(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_notes_flattened(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.ListNotesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_notes( + parent='parent_value', + filter='filter_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].filter + mock_val = 'filter_value' + assert arg == mock_val + + +def test_list_notes_flattened_error(): + client = GrafeasClient( + 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_notes( + grafeas.ListNotesRequest(), + parent='parent_value', + filter='filter_value', + ) + +@pytest.mark.asyncio +async def test_list_notes_flattened_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.ListNotesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.ListNotesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_notes( + parent='parent_value', + filter='filter_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].filter + mock_val = 'filter_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_notes_flattened_error_async(): + client = GrafeasAsyncClient( + 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_notes( + grafeas.ListNotesRequest(), + parent='parent_value', + filter='filter_value', + ) + + +def test_list_notes_pager(transport_name: str = "grpc"): + client = GrafeasClient( + 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_notes), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + grafeas.ListNotesResponse( + notes=[ + grafeas.Note(), + grafeas.Note(), + grafeas.Note(), + ], + next_page_token='abc', + ), + grafeas.ListNotesResponse( + notes=[], + next_page_token='def', + ), + grafeas.ListNotesResponse( + notes=[ + grafeas.Note(), + ], + next_page_token='ghi', + ), + grafeas.ListNotesResponse( + notes=[ + grafeas.Note(), + grafeas.Note(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_notes(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, grafeas.Note) + for i in results) +def test_list_notes_pages(transport_name: str = "grpc"): + client = GrafeasClient( + 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_notes), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + grafeas.ListNotesResponse( + notes=[ + grafeas.Note(), + grafeas.Note(), + grafeas.Note(), + ], + next_page_token='abc', + ), + grafeas.ListNotesResponse( + notes=[], + next_page_token='def', + ), + grafeas.ListNotesResponse( + notes=[ + grafeas.Note(), + ], + next_page_token='ghi', + ), + grafeas.ListNotesResponse( + notes=[ + grafeas.Note(), + grafeas.Note(), + ], + ), + RuntimeError, + ) + pages = list(client.list_notes(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_notes_async_pager(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notes), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + grafeas.ListNotesResponse( + notes=[ + grafeas.Note(), + grafeas.Note(), + grafeas.Note(), + ], + next_page_token='abc', + ), + grafeas.ListNotesResponse( + notes=[], + next_page_token='def', + ), + grafeas.ListNotesResponse( + notes=[ + grafeas.Note(), + ], + next_page_token='ghi', + ), + grafeas.ListNotesResponse( + notes=[ + grafeas.Note(), + grafeas.Note(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_notes(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, grafeas.Note) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_notes_async_pages(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notes), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + grafeas.ListNotesResponse( + notes=[ + grafeas.Note(), + grafeas.Note(), + grafeas.Note(), + ], + next_page_token='abc', + ), + grafeas.ListNotesResponse( + notes=[], + next_page_token='def', + ), + grafeas.ListNotesResponse( + notes=[ + grafeas.Note(), + ], + next_page_token='ghi', + ), + grafeas.ListNotesResponse( + notes=[ + grafeas.Note(), + grafeas.Note(), + ], + ), + 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_notes(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", [ + grafeas.DeleteNoteRequest, + dict, +]) +def test_delete_note(request_type, transport: str = 'grpc'): + client = GrafeasClient( + 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_note), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = grafeas.DeleteNoteRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_note_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 = GrafeasClient( + 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 = grafeas.DeleteNoteRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_note), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_note(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.DeleteNoteRequest( + name='name_value', + ) + +def test_delete_note_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GrafeasClient( + 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_note in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_note] = mock_rpc + request = {} + client.delete_note(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_note(request) + + # Establish that a new wrapper 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_note_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = GrafeasAsyncClient( + 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_note in client._client._transport._wrapped_methods + + # 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_note] = mock_rpc + + request = {} + await client.delete_note(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_note(request) + + # Establish that a new wrapper 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_note_async(transport: str = 'grpc_asyncio', request_type=grafeas.DeleteNoteRequest): + client = GrafeasAsyncClient( + 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_note), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = grafeas.DeleteNoteRequest() + 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_note_async_from_dict(): + await test_delete_note_async(request_type=dict) + +def test_delete_note_field_headers(): + client = GrafeasClient( + 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 = grafeas.DeleteNoteRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_note), + '__call__') as call: + call.return_value = None + client.delete_note(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_note_field_headers_async(): + client = GrafeasAsyncClient( + 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 = grafeas.DeleteNoteRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_note), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_note(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_note_flattened(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_note), + '__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_note( + 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_note_flattened_error(): + client = GrafeasClient( + 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_note( + grafeas.DeleteNoteRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_note_flattened_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_note), + '__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_note( + 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_note_flattened_error_async(): + client = GrafeasAsyncClient( + 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_note( + grafeas.DeleteNoteRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + grafeas.CreateNoteRequest, + dict, +]) +def test_create_note(request_type, transport: str = 'grpc'): + client = GrafeasClient( + 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_note), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Note( + name='name_value', + short_description='short_description_value', + long_description='long_description_value', + kind=common.NoteKind.VULNERABILITY, + related_note_names=['related_note_names_value'], + ) + response = client.create_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = grafeas.CreateNoteRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Note) + assert response.name == 'name_value' + assert response.short_description == 'short_description_value' + assert response.long_description == 'long_description_value' + assert response.kind == common.NoteKind.VULNERABILITY + assert response.related_note_names == ['related_note_names_value'] + + +def test_create_note_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 = GrafeasClient( + 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 = grafeas.CreateNoteRequest( + parent='parent_value', + note_id='note_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_note), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_note(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.CreateNoteRequest( + parent='parent_value', + note_id='note_id_value', + ) + +def test_create_note_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GrafeasClient( + 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_note in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_note] = mock_rpc + request = {} + client.create_note(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_note(request) + + # Establish that a new wrapper 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_note_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = GrafeasAsyncClient( + 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_note in client._client._transport._wrapped_methods + + # 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_note] = mock_rpc + + request = {} + await client.create_note(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_note(request) + + # Establish that a new wrapper 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_note_async(transport: str = 'grpc_asyncio', request_type=grafeas.CreateNoteRequest): + client = GrafeasAsyncClient( + 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_note), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note( + name='name_value', + short_description='short_description_value', + long_description='long_description_value', + kind=common.NoteKind.VULNERABILITY, + related_note_names=['related_note_names_value'], + )) + response = await client.create_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = grafeas.CreateNoteRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Note) + assert response.name == 'name_value' + assert response.short_description == 'short_description_value' + assert response.long_description == 'long_description_value' + assert response.kind == common.NoteKind.VULNERABILITY + assert response.related_note_names == ['related_note_names_value'] + + +@pytest.mark.asyncio +async def test_create_note_async_from_dict(): + await test_create_note_async(request_type=dict) + +def test_create_note_field_headers(): + client = GrafeasClient( + 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 = grafeas.CreateNoteRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_note), + '__call__') as call: + call.return_value = grafeas.Note() + client.create_note(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_note_field_headers_async(): + client = GrafeasAsyncClient( + 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 = grafeas.CreateNoteRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_note), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) + await client.create_note(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_note_flattened(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_note), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Note() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_note( + parent='parent_value', + note_id='note_id_value', + note=grafeas.Note(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].note_id + mock_val = 'note_id_value' + assert arg == mock_val + arg = args[0].note + mock_val = grafeas.Note(name='name_value') + assert arg == mock_val + + +def test_create_note_flattened_error(): + client = GrafeasClient( + 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_note( + grafeas.CreateNoteRequest(), + parent='parent_value', + note_id='note_id_value', + note=grafeas.Note(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_note_flattened_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_note), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Note() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_note( + parent='parent_value', + note_id='note_id_value', + note=grafeas.Note(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].note_id + mock_val = 'note_id_value' + assert arg == mock_val + arg = args[0].note + mock_val = grafeas.Note(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_note_flattened_error_async(): + client = GrafeasAsyncClient( + 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_note( + grafeas.CreateNoteRequest(), + parent='parent_value', + note_id='note_id_value', + note=grafeas.Note(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + grafeas.BatchCreateNotesRequest, + dict, +]) +def test_batch_create_notes(request_type, transport: str = 'grpc'): + client = GrafeasClient( + 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.batch_create_notes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.BatchCreateNotesResponse( + ) + response = client.batch_create_notes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = grafeas.BatchCreateNotesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.BatchCreateNotesResponse) + + +def test_batch_create_notes_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 = GrafeasClient( + 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 = grafeas.BatchCreateNotesRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_notes), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.batch_create_notes(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.BatchCreateNotesRequest( + parent='parent_value', + ) + +def test_batch_create_notes_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GrafeasClient( + 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.batch_create_notes in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.batch_create_notes] = mock_rpc + request = {} + client.batch_create_notes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_create_notes(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_batch_create_notes_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = GrafeasAsyncClient( + 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.batch_create_notes in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.batch_create_notes] = mock_rpc + + request = {} + await client.batch_create_notes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.batch_create_notes(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_batch_create_notes_async(transport: str = 'grpc_asyncio', request_type=grafeas.BatchCreateNotesRequest): + client = GrafeasAsyncClient( + 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.batch_create_notes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.BatchCreateNotesResponse( + )) + response = await client.batch_create_notes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = grafeas.BatchCreateNotesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.BatchCreateNotesResponse) + + +@pytest.mark.asyncio +async def test_batch_create_notes_async_from_dict(): + await test_batch_create_notes_async(request_type=dict) + +def test_batch_create_notes_field_headers(): + client = GrafeasClient( + 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 = grafeas.BatchCreateNotesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_notes), + '__call__') as call: + call.return_value = grafeas.BatchCreateNotesResponse() + client.batch_create_notes(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_batch_create_notes_field_headers_async(): + client = GrafeasAsyncClient( + 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 = grafeas.BatchCreateNotesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_notes), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.BatchCreateNotesResponse()) + await client.batch_create_notes(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_batch_create_notes_flattened(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_notes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.BatchCreateNotesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.batch_create_notes( + parent='parent_value', + notes={'key_value': grafeas.Note(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].notes + mock_val = {'key_value': grafeas.Note(name='name_value')} + assert arg == mock_val + + +def test_batch_create_notes_flattened_error(): + client = GrafeasClient( + 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.batch_create_notes( + grafeas.BatchCreateNotesRequest(), + parent='parent_value', + notes={'key_value': grafeas.Note(name='name_value')}, + ) + +@pytest.mark.asyncio +async def test_batch_create_notes_flattened_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_notes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.BatchCreateNotesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.BatchCreateNotesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.batch_create_notes( + parent='parent_value', + notes={'key_value': grafeas.Note(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].notes + mock_val = {'key_value': grafeas.Note(name='name_value')} + assert arg == mock_val + +@pytest.mark.asyncio +async def test_batch_create_notes_flattened_error_async(): + client = GrafeasAsyncClient( + 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.batch_create_notes( + grafeas.BatchCreateNotesRequest(), + parent='parent_value', + notes={'key_value': grafeas.Note(name='name_value')}, + ) + + +@pytest.mark.parametrize("request_type", [ + grafeas.UpdateNoteRequest, + dict, +]) +def test_update_note(request_type, transport: str = 'grpc'): + client = GrafeasClient( + 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_note), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Note( + name='name_value', + short_description='short_description_value', + long_description='long_description_value', + kind=common.NoteKind.VULNERABILITY, + related_note_names=['related_note_names_value'], + ) + response = client.update_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = grafeas.UpdateNoteRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Note) + assert response.name == 'name_value' + assert response.short_description == 'short_description_value' + assert response.long_description == 'long_description_value' + assert response.kind == common.NoteKind.VULNERABILITY + assert response.related_note_names == ['related_note_names_value'] + + +def test_update_note_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 = GrafeasClient( + 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 = grafeas.UpdateNoteRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_note), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_note(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.UpdateNoteRequest( + name='name_value', + ) + +def test_update_note_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GrafeasClient( + 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_note in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_note] = mock_rpc + request = {} + client.update_note(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_note(request) + + # Establish that a new wrapper 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_note_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = GrafeasAsyncClient( + 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_note in client._client._transport._wrapped_methods + + # 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_note] = mock_rpc + + request = {} + await client.update_note(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_note(request) + + # Establish that a new wrapper 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_note_async(transport: str = 'grpc_asyncio', request_type=grafeas.UpdateNoteRequest): + client = GrafeasAsyncClient( + 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_note), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note( + name='name_value', + short_description='short_description_value', + long_description='long_description_value', + kind=common.NoteKind.VULNERABILITY, + related_note_names=['related_note_names_value'], + )) + response = await client.update_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = grafeas.UpdateNoteRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Note) + assert response.name == 'name_value' + assert response.short_description == 'short_description_value' + assert response.long_description == 'long_description_value' + assert response.kind == common.NoteKind.VULNERABILITY + assert response.related_note_names == ['related_note_names_value'] + + +@pytest.mark.asyncio +async def test_update_note_async_from_dict(): + await test_update_note_async(request_type=dict) + +def test_update_note_field_headers(): + client = GrafeasClient( + 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 = grafeas.UpdateNoteRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_note), + '__call__') as call: + call.return_value = grafeas.Note() + client.update_note(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_update_note_field_headers_async(): + client = GrafeasAsyncClient( + 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 = grafeas.UpdateNoteRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_note), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) + await client.update_note(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_update_note_flattened(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_note), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Note() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_note( + name='name_value', + note=grafeas.Note(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].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].note + mock_val = grafeas.Note(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_note_flattened_error(): + client = GrafeasClient( + 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_note( + grafeas.UpdateNoteRequest(), + name='name_value', + note=grafeas.Note(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_note_flattened_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_note), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Note() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_note( + name='name_value', + note=grafeas.Note(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].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].note + mock_val = grafeas.Note(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_note_flattened_error_async(): + client = GrafeasAsyncClient( + 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_note( + grafeas.UpdateNoteRequest(), + name='name_value', + note=grafeas.Note(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + grafeas.ListNoteOccurrencesRequest, + dict, +]) +def test_list_note_occurrences(request_type, transport: str = 'grpc'): + client = GrafeasClient( + 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_note_occurrences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.ListNoteOccurrencesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_note_occurrences(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = grafeas.ListNoteOccurrencesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNoteOccurrencesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_note_occurrences_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 = GrafeasClient( + 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 = grafeas.ListNoteOccurrencesRequest( + name='name_value', + filter='filter_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_note_occurrences), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_note_occurrences(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.ListNoteOccurrencesRequest( + name='name_value', + filter='filter_value', + page_token='page_token_value', + ) + +def test_list_note_occurrences_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GrafeasClient( + 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_note_occurrences in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_note_occurrences] = mock_rpc + request = {} + client.list_note_occurrences(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_note_occurrences(request) + + # Establish that a new wrapper 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_note_occurrences_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached 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 = GrafeasAsyncClient( + 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_note_occurrences in client._client._transport._wrapped_methods + + # 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_note_occurrences] = mock_rpc + + request = {} + await client.list_note_occurrences(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_note_occurrences(request) + + # Establish that a new wrapper 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_note_occurrences_async(transport: str = 'grpc_asyncio', request_type=grafeas.ListNoteOccurrencesRequest): + client = GrafeasAsyncClient( + 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_note_occurrences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.ListNoteOccurrencesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_note_occurrences(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = grafeas.ListNoteOccurrencesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNoteOccurrencesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_note_occurrences_async_from_dict(): + await test_list_note_occurrences_async(request_type=dict) + +def test_list_note_occurrences_field_headers(): + client = GrafeasClient( + 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 = grafeas.ListNoteOccurrencesRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_note_occurrences), + '__call__') as call: + call.return_value = grafeas.ListNoteOccurrencesResponse() + client.list_note_occurrences(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_list_note_occurrences_field_headers_async(): + client = GrafeasAsyncClient( + 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 = grafeas.ListNoteOccurrencesRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_note_occurrences), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.ListNoteOccurrencesResponse()) + await client.list_note_occurrences(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_list_note_occurrences_flattened(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_note_occurrences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.ListNoteOccurrencesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_note_occurrences( + name='name_value', + filter='filter_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 + arg = args[0].filter + mock_val = 'filter_value' + assert arg == mock_val + + +def test_list_note_occurrences_flattened_error(): + client = GrafeasClient( + 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_note_occurrences( + grafeas.ListNoteOccurrencesRequest(), + name='name_value', + filter='filter_value', + ) + +@pytest.mark.asyncio +async def test_list_note_occurrences_flattened_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_note_occurrences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.ListNoteOccurrencesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.ListNoteOccurrencesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_note_occurrences( + name='name_value', + filter='filter_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 + arg = args[0].filter + mock_val = 'filter_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_note_occurrences_flattened_error_async(): + client = GrafeasAsyncClient( + 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_note_occurrences( + grafeas.ListNoteOccurrencesRequest(), + name='name_value', + filter='filter_value', + ) + + +def test_list_note_occurrences_pager(transport_name: str = "grpc"): + client = GrafeasClient( + 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_note_occurrences), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + grafeas.ListNoteOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + next_page_token='abc', + ), + grafeas.ListNoteOccurrencesResponse( + occurrences=[], + next_page_token='def', + ), + grafeas.ListNoteOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + ], + next_page_token='ghi', + ), + grafeas.ListNoteOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('name', ''), + )), + ) + pager = client.list_note_occurrences(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, grafeas.Occurrence) + for i in results) +def test_list_note_occurrences_pages(transport_name: str = "grpc"): + client = GrafeasClient( + 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_note_occurrences), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + grafeas.ListNoteOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + next_page_token='abc', + ), + grafeas.ListNoteOccurrencesResponse( + occurrences=[], + next_page_token='def', + ), + grafeas.ListNoteOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + ], + next_page_token='ghi', + ), + grafeas.ListNoteOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + ), + RuntimeError, + ) + pages = list(client.list_note_occurrences(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_note_occurrences_async_pager(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_note_occurrences), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + grafeas.ListNoteOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + next_page_token='abc', + ), + grafeas.ListNoteOccurrencesResponse( + occurrences=[], + next_page_token='def', + ), + grafeas.ListNoteOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + ], + next_page_token='ghi', + ), + grafeas.ListNoteOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_note_occurrences(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, grafeas.Occurrence) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_note_occurrences_async_pages(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_note_occurrences), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + grafeas.ListNoteOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + next_page_token='abc', + ), + grafeas.ListNoteOccurrencesResponse( + occurrences=[], + next_page_token='def', + ), + grafeas.ListNoteOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + ], + next_page_token='ghi', + ), + grafeas.ListNoteOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + ), + 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_note_occurrences(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_occurrence_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 = GrafeasClient( + 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_occurrence in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_occurrence] = mock_rpc + + request = {} + client.get_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_occurrence(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_occurrence_rest_required_fields(request_type=grafeas.GetOccurrenceRequest): + transport_class = transports.GrafeasRestTransport + + 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_occurrence._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_occurrence._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 = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = grafeas.Occurrence() + # 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 = grafeas.Occurrence.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_occurrence(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_occurrence_rest_unset_required_fields(): + transport = transports.GrafeasRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_occurrence._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_occurrence_rest_flattened(): + client = GrafeasClient( + 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 = grafeas.Occurrence() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/occurrences/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 = grafeas.Occurrence.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_occurrence(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/occurrences/*}" % client.transport._host, args[1]) + + +def test_get_occurrence_rest_flattened_error(transport: str = 'rest'): + client = GrafeasClient( + 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_occurrence( + grafeas.GetOccurrenceRequest(), + name='name_value', + ) + + +def test_list_occurrences_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 = GrafeasClient( + 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_occurrences in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_occurrences] = mock_rpc + + request = {} + client.list_occurrences(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_occurrences(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_occurrences_rest_required_fields(request_type=grafeas.ListOccurrencesRequest): + transport_class = transports.GrafeasRestTransport + + 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_occurrences._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_occurrences._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = grafeas.ListOccurrencesResponse() + # 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 = grafeas.ListOccurrencesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_occurrences(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_occurrences_rest_unset_required_fields(): + transport = transports.GrafeasRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_occurrences._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_occurrences_rest_flattened(): + client = GrafeasClient( + 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 = grafeas.ListOccurrencesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + filter='filter_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 = grafeas.ListOccurrencesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_occurrences(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*}/occurrences" % client.transport._host, args[1]) + + +def test_list_occurrences_rest_flattened_error(transport: str = 'rest'): + client = GrafeasClient( + 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_occurrences( + grafeas.ListOccurrencesRequest(), + parent='parent_value', + filter='filter_value', + ) + + +def test_list_occurrences_rest_pager(transport: str = 'rest'): + client = GrafeasClient( + 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 = ( + grafeas.ListOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + next_page_token='abc', + ), + grafeas.ListOccurrencesResponse( + occurrences=[], + next_page_token='def', + ), + grafeas.ListOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + ], + next_page_token='ghi', + ), + grafeas.ListOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(grafeas.ListOccurrencesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1'} + + pager = client.list_occurrences(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, grafeas.Occurrence) + for i in results) + + pages = list(client.list_occurrences(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_delete_occurrence_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 = GrafeasClient( + 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_occurrence in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_occurrence] = mock_rpc + + request = {} + client.delete_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_occurrence(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_occurrence_rest_required_fields(request_type=grafeas.DeleteOccurrenceRequest): + transport_class = transports.GrafeasRestTransport + + 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_occurrence._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_occurrence._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 = GrafeasClient( + 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_occurrence(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_occurrence_rest_unset_required_fields(): + transport = transports.GrafeasRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_occurrence._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_delete_occurrence_rest_flattened(): + client = GrafeasClient( + 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': 'projects/sample1/occurrences/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_occurrence(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/occurrences/*}" % client.transport._host, args[1]) + + +def test_delete_occurrence_rest_flattened_error(transport: str = 'rest'): + client = GrafeasClient( + 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_occurrence( + grafeas.DeleteOccurrenceRequest(), + name='name_value', + ) + + +def test_create_occurrence_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 = GrafeasClient( + 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_occurrence in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_occurrence] = mock_rpc + + request = {} + client.create_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_occurrence(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_occurrence_rest_required_fields(request_type=grafeas.CreateOccurrenceRequest): + transport_class = transports.GrafeasRestTransport + + 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_occurrence._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_occurrence._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 = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = grafeas.Occurrence() + # 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 = grafeas.Occurrence.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_occurrence(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_occurrence_rest_unset_required_fields(): + transport = transports.GrafeasRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_occurrence._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "occurrence", ))) + + +def test_create_occurrence_rest_flattened(): + client = GrafeasClient( + 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 = grafeas.Occurrence() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + occurrence=grafeas.Occurrence(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 = grafeas.Occurrence.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_occurrence(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*}/occurrences" % client.transport._host, args[1]) + + +def test_create_occurrence_rest_flattened_error(transport: str = 'rest'): + client = GrafeasClient( + 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_occurrence( + grafeas.CreateOccurrenceRequest(), + parent='parent_value', + occurrence=grafeas.Occurrence(name='name_value'), + ) + + +def test_batch_create_occurrences_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 = GrafeasClient( + 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.batch_create_occurrences in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.batch_create_occurrences] = mock_rpc + + request = {} + client.batch_create_occurrences(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_create_occurrences(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_batch_create_occurrences_rest_required_fields(request_type=grafeas.BatchCreateOccurrencesRequest): + transport_class = transports.GrafeasRestTransport + + 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()).batch_create_occurrences._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()).batch_create_occurrences._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 = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = grafeas.BatchCreateOccurrencesResponse() + # 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 = grafeas.BatchCreateOccurrencesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.batch_create_occurrences(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_batch_create_occurrences_rest_unset_required_fields(): + transport = transports.GrafeasRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.batch_create_occurrences._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "occurrences", ))) + + +def test_batch_create_occurrences_rest_flattened(): + client = GrafeasClient( + 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 = grafeas.BatchCreateOccurrencesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + occurrences=[grafeas.Occurrence(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 = grafeas.BatchCreateOccurrencesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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.batch_create_occurrences(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*}/occurrences:batchCreate" % client.transport._host, args[1]) + + +def test_batch_create_occurrences_rest_flattened_error(transport: str = 'rest'): + client = GrafeasClient( + 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.batch_create_occurrences( + grafeas.BatchCreateOccurrencesRequest(), + parent='parent_value', + occurrences=[grafeas.Occurrence(name='name_value')], + ) + + +def test_update_occurrence_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 = GrafeasClient( + 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_occurrence in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_occurrence] = mock_rpc + + request = {} + client.update_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_occurrence(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_occurrence_rest_required_fields(request_type=grafeas.UpdateOccurrenceRequest): + transport_class = transports.GrafeasRestTransport + + 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()).update_occurrence._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()).update_occurrence._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 + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = grafeas.Occurrence() + # 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 = grafeas.Occurrence.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_occurrence(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_occurrence_rest_unset_required_fields(): + transport = transports.GrafeasRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_occurrence._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("name", "occurrence", ))) + + +def test_update_occurrence_rest_flattened(): + client = GrafeasClient( + 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 = grafeas.Occurrence() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/occurrences/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + occurrence=grafeas.Occurrence(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 = grafeas.Occurrence.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_occurrence(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/occurrences/*}" % client.transport._host, args[1]) + + +def test_update_occurrence_rest_flattened_error(transport: str = 'rest'): + client = GrafeasClient( + 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_occurrence( + grafeas.UpdateOccurrenceRequest(), + name='name_value', + occurrence=grafeas.Occurrence(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_get_occurrence_note_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 = GrafeasClient( + 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_occurrence_note in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_occurrence_note] = mock_rpc + + request = {} + client.get_occurrence_note(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_occurrence_note(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_occurrence_note_rest_required_fields(request_type=grafeas.GetOccurrenceNoteRequest): + transport_class = transports.GrafeasRestTransport + + 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_occurrence_note._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_occurrence_note._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 = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = grafeas.Note() + # 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 = grafeas.Note.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_occurrence_note(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_occurrence_note_rest_unset_required_fields(): + transport = transports.GrafeasRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_occurrence_note._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_occurrence_note_rest_flattened(): + client = GrafeasClient( + 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 = grafeas.Note() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/occurrences/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 = grafeas.Note.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_occurrence_note(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/occurrences/*}/notes" % client.transport._host, args[1]) + + +def test_get_occurrence_note_rest_flattened_error(transport: str = 'rest'): + client = GrafeasClient( + 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_occurrence_note( + grafeas.GetOccurrenceNoteRequest(), + name='name_value', + ) + + +def test_get_note_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 = GrafeasClient( + 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_note in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_note] = mock_rpc + + request = {} + client.get_note(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_note(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_note_rest_required_fields(request_type=grafeas.GetNoteRequest): + transport_class = transports.GrafeasRestTransport + + 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_note._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_note._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 = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = grafeas.Note() + # 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 = grafeas.Note.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_note(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_note_rest_unset_required_fields(): + transport = transports.GrafeasRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_note._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_note_rest_flattened(): + client = GrafeasClient( + 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 = grafeas.Note() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/notes/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 = grafeas.Note.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_note(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/notes/*}" % client.transport._host, args[1]) + + +def test_get_note_rest_flattened_error(transport: str = 'rest'): + client = GrafeasClient( + 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_note( + grafeas.GetNoteRequest(), + name='name_value', + ) + + +def test_list_notes_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 = GrafeasClient( + 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_notes in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_notes] = mock_rpc + + request = {} + client.list_notes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_notes(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_notes_rest_required_fields(request_type=grafeas.ListNotesRequest): + transport_class = transports.GrafeasRestTransport + + 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_notes._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_notes._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = grafeas.ListNotesResponse() + # 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 = grafeas.ListNotesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_notes(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_notes_rest_unset_required_fields(): + transport = transports.GrafeasRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_notes._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_notes_rest_flattened(): + client = GrafeasClient( + 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 = grafeas.ListNotesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + filter='filter_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 = grafeas.ListNotesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_notes(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*}/notes" % client.transport._host, args[1]) + + +def test_list_notes_rest_flattened_error(transport: str = 'rest'): + client = GrafeasClient( + 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_notes( + grafeas.ListNotesRequest(), + parent='parent_value', + filter='filter_value', + ) + + +def test_list_notes_rest_pager(transport: str = 'rest'): + client = GrafeasClient( + 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 = ( + grafeas.ListNotesResponse( + notes=[ + grafeas.Note(), + grafeas.Note(), + grafeas.Note(), + ], + next_page_token='abc', + ), + grafeas.ListNotesResponse( + notes=[], + next_page_token='def', + ), + grafeas.ListNotesResponse( + notes=[ + grafeas.Note(), + ], + next_page_token='ghi', + ), + grafeas.ListNotesResponse( + notes=[ + grafeas.Note(), + grafeas.Note(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(grafeas.ListNotesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1'} + + pager = client.list_notes(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, grafeas.Note) + for i in results) + + pages = list(client.list_notes(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_delete_note_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 = GrafeasClient( + 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_note in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_note] = mock_rpc + + request = {} + client.delete_note(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_note(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_note_rest_required_fields(request_type=grafeas.DeleteNoteRequest): + transport_class = transports.GrafeasRestTransport + + 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_note._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_note._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 = GrafeasClient( + 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_note(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_note_rest_unset_required_fields(): + transport = transports.GrafeasRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_note._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_delete_note_rest_flattened(): + client = GrafeasClient( + 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': 'projects/sample1/notes/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_note(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/notes/*}" % client.transport._host, args[1]) + + +def test_delete_note_rest_flattened_error(transport: str = 'rest'): + client = GrafeasClient( + 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_note( + grafeas.DeleteNoteRequest(), + name='name_value', + ) + + +def test_create_note_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 = GrafeasClient( + 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_note in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_note] = mock_rpc + + request = {} + client.create_note(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_note(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_note_rest_required_fields(request_type=grafeas.CreateNoteRequest): + transport_class = transports.GrafeasRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["note_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 "noteId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_note._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "noteId" in jsonified_request + assert jsonified_request["noteId"] == request_init["note_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["noteId"] = 'note_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_note._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("note_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 "noteId" in jsonified_request + assert jsonified_request["noteId"] == 'note_id_value' + + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = grafeas.Note() + # 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 = grafeas.Note.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_note(request) + + expected_params = [ + ( + "noteId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_note_rest_unset_required_fields(): + transport = transports.GrafeasRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_note._get_unset_required_fields({}) + assert set(unset_fields) == (set(("noteId", )) & set(("parent", "noteId", "note", ))) + + +def test_create_note_rest_flattened(): + client = GrafeasClient( + 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 = grafeas.Note() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + note_id='note_id_value', + note=grafeas.Note(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 = grafeas.Note.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_note(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*}/notes" % client.transport._host, args[1]) + + +def test_create_note_rest_flattened_error(transport: str = 'rest'): + client = GrafeasClient( + 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_note( + grafeas.CreateNoteRequest(), + parent='parent_value', + note_id='note_id_value', + note=grafeas.Note(name='name_value'), + ) + + +def test_batch_create_notes_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 = GrafeasClient( + 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.batch_create_notes in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.batch_create_notes] = mock_rpc + + request = {} + client.batch_create_notes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_create_notes(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_batch_create_notes_rest_required_fields(request_type=grafeas.BatchCreateNotesRequest): + transport_class = transports.GrafeasRestTransport + + 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()).batch_create_notes._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()).batch_create_notes._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 = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = grafeas.BatchCreateNotesResponse() + # 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 = grafeas.BatchCreateNotesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.batch_create_notes(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_batch_create_notes_rest_unset_required_fields(): + transport = transports.GrafeasRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.batch_create_notes._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "notes", ))) + + +def test_batch_create_notes_rest_flattened(): + client = GrafeasClient( + 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 = grafeas.BatchCreateNotesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + notes={'key_value': grafeas.Note(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 = grafeas.BatchCreateNotesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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.batch_create_notes(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*}/notes:batchCreate" % client.transport._host, args[1]) + + +def test_batch_create_notes_rest_flattened_error(transport: str = 'rest'): + client = GrafeasClient( + 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.batch_create_notes( + grafeas.BatchCreateNotesRequest(), + parent='parent_value', + notes={'key_value': grafeas.Note(name='name_value')}, + ) + + +def test_update_note_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 = GrafeasClient( + 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_note in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_note] = mock_rpc + + request = {} + client.update_note(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_note(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_note_rest_required_fields(request_type=grafeas.UpdateNoteRequest): + transport_class = transports.GrafeasRestTransport + + 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()).update_note._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()).update_note._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 + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = grafeas.Note() + # 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 = grafeas.Note.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_note(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_note_rest_unset_required_fields(): + transport = transports.GrafeasRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_note._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("name", "note", ))) + + +def test_update_note_rest_flattened(): + client = GrafeasClient( + 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 = grafeas.Note() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/notes/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + note=grafeas.Note(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 = grafeas.Note.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_note(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/notes/*}" % client.transport._host, args[1]) + + +def test_update_note_rest_flattened_error(transport: str = 'rest'): + client = GrafeasClient( + 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_note( + grafeas.UpdateNoteRequest(), + name='name_value', + note=grafeas.Note(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_list_note_occurrences_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 = GrafeasClient( + 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_note_occurrences in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_note_occurrences] = mock_rpc + + request = {} + client.list_note_occurrences(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_note_occurrences(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_note_occurrences_rest_required_fields(request_type=grafeas.ListNoteOccurrencesRequest): + transport_class = transports.GrafeasRestTransport + + 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()).list_note_occurrences._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()).list_note_occurrences._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = grafeas.ListNoteOccurrencesResponse() + # 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 = grafeas.ListNoteOccurrencesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_note_occurrences(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_note_occurrences_rest_unset_required_fields(): + transport = transports.GrafeasRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_note_occurrences._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("name", ))) + + +def test_list_note_occurrences_rest_flattened(): + client = GrafeasClient( + 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 = grafeas.ListNoteOccurrencesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/notes/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + filter='filter_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 = grafeas.ListNoteOccurrencesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_note_occurrences(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/notes/*}/occurrences" % client.transport._host, args[1]) + + +def test_list_note_occurrences_rest_flattened_error(transport: str = 'rest'): + client = GrafeasClient( + 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_note_occurrences( + grafeas.ListNoteOccurrencesRequest(), + name='name_value', + filter='filter_value', + ) + + +def test_list_note_occurrences_rest_pager(transport: str = 'rest'): + client = GrafeasClient( + 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 = ( + grafeas.ListNoteOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + next_page_token='abc', + ), + grafeas.ListNoteOccurrencesResponse( + occurrences=[], + next_page_token='def', + ), + grafeas.ListNoteOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + ], + next_page_token='ghi', + ), + grafeas.ListNoteOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(grafeas.ListNoteOccurrencesResponse.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 = {'name': 'projects/sample1/notes/sample2'} + + pager = client.list_note_occurrences(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, grafeas.Occurrence) + for i in results) + + pages = list(client.list_note_occurrences(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.GrafeasGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.GrafeasGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = GrafeasClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.GrafeasGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = GrafeasClient( + 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 = GrafeasClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.GrafeasGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = GrafeasClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.GrafeasGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = GrafeasClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.GrafeasGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.GrafeasGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.GrafeasGrpcTransport, + transports.GrafeasGrpcAsyncIOTransport, + transports.GrafeasRestTransport, +]) +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 = GrafeasClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = GrafeasClient( + 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_occurrence_empty_call_grpc(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_occurrence), + '__call__') as call: + call.return_value = grafeas.Occurrence() + client.get_occurrence(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.GetOccurrenceRequest() + + assert args[0] == request_msg + + +# This 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_occurrences_empty_call_grpc(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_occurrences), + '__call__') as call: + call.return_value = grafeas.ListOccurrencesResponse() + client.list_occurrences(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.ListOccurrencesRequest() + + assert args[0] == request_msg + + +# This 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_occurrence_empty_call_grpc(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_occurrence), + '__call__') as call: + call.return_value = None + client.delete_occurrence(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.DeleteOccurrenceRequest() + + assert args[0] == request_msg + + +# This 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_occurrence_empty_call_grpc(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_occurrence), + '__call__') as call: + call.return_value = grafeas.Occurrence() + client.create_occurrence(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.CreateOccurrenceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_batch_create_occurrences_empty_call_grpc(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_occurrences), + '__call__') as call: + call.return_value = grafeas.BatchCreateOccurrencesResponse() + client.batch_create_occurrences(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.BatchCreateOccurrencesRequest() + + assert args[0] == request_msg + + +# This 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_occurrence_empty_call_grpc(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_occurrence), + '__call__') as call: + call.return_value = grafeas.Occurrence() + client.update_occurrence(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.UpdateOccurrenceRequest() + + assert args[0] == request_msg + + +# This 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_occurrence_note_empty_call_grpc(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_occurrence_note), + '__call__') as call: + call.return_value = grafeas.Note() + client.get_occurrence_note(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.GetOccurrenceNoteRequest() + + assert args[0] == request_msg + + +# This 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_note_empty_call_grpc(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_note), + '__call__') as call: + call.return_value = grafeas.Note() + client.get_note(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.GetNoteRequest() + + assert args[0] == request_msg + + +# This 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_notes_empty_call_grpc(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_notes), + '__call__') as call: + call.return_value = grafeas.ListNotesResponse() + client.list_notes(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.ListNotesRequest() + + assert args[0] == request_msg + + +# This 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_note_empty_call_grpc(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_note), + '__call__') as call: + call.return_value = None + client.delete_note(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.DeleteNoteRequest() + + assert args[0] == request_msg + + +# This 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_note_empty_call_grpc(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_note), + '__call__') as call: + call.return_value = grafeas.Note() + client.create_note(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.CreateNoteRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_batch_create_notes_empty_call_grpc(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_notes), + '__call__') as call: + call.return_value = grafeas.BatchCreateNotesResponse() + client.batch_create_notes(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.BatchCreateNotesRequest() + + assert args[0] == request_msg + + +# This 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_note_empty_call_grpc(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_note), + '__call__') as call: + call.return_value = grafeas.Note() + client.update_note(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.UpdateNoteRequest() + + assert args[0] == request_msg + + +# This 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_note_occurrences_empty_call_grpc(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_note_occurrences), + '__call__') as call: + call.return_value = grafeas.ListNoteOccurrencesResponse() + client.list_note_occurrences(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.ListNoteOccurrencesRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = GrafeasAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = GrafeasAsyncClient( + 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_occurrence_empty_call_grpc_asyncio(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_occurrence), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence( + name='name_value', + resource_uri='resource_uri_value', + note_name='note_name_value', + kind=common.NoteKind.VULNERABILITY, + remediation='remediation_value', + )) + await client.get_occurrence(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.GetOccurrenceRequest() + + assert args[0] == request_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_occurrences_empty_call_grpc_asyncio(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_occurrences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.ListOccurrencesResponse( + next_page_token='next_page_token_value', + )) + await client.list_occurrences(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.ListOccurrencesRequest() + + assert args[0] == request_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_occurrence_empty_call_grpc_asyncio(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_occurrence), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_occurrence(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.DeleteOccurrenceRequest() + + assert args[0] == request_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_occurrence_empty_call_grpc_asyncio(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_occurrence), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence( + name='name_value', + resource_uri='resource_uri_value', + note_name='note_name_value', + kind=common.NoteKind.VULNERABILITY, + remediation='remediation_value', + )) + await client.create_occurrence(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.CreateOccurrenceRequest() + + assert args[0] == request_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_batch_create_occurrences_empty_call_grpc_asyncio(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_occurrences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.BatchCreateOccurrencesResponse( + )) + await client.batch_create_occurrences(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.BatchCreateOccurrencesRequest() + + assert args[0] == request_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_occurrence_empty_call_grpc_asyncio(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_occurrence), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence( + name='name_value', + resource_uri='resource_uri_value', + note_name='note_name_value', + kind=common.NoteKind.VULNERABILITY, + remediation='remediation_value', + )) + await client.update_occurrence(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.UpdateOccurrenceRequest() + + assert args[0] == request_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_occurrence_note_empty_call_grpc_asyncio(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_occurrence_note), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note( + name='name_value', + short_description='short_description_value', + long_description='long_description_value', + kind=common.NoteKind.VULNERABILITY, + related_note_names=['related_note_names_value'], + )) + await client.get_occurrence_note(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.GetOccurrenceNoteRequest() + + assert args[0] == request_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_note_empty_call_grpc_asyncio(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_note), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note( + name='name_value', + short_description='short_description_value', + long_description='long_description_value', + kind=common.NoteKind.VULNERABILITY, + related_note_names=['related_note_names_value'], + )) + await client.get_note(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.GetNoteRequest() + + assert args[0] == request_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_notes_empty_call_grpc_asyncio(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_notes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.ListNotesResponse( + next_page_token='next_page_token_value', + )) + await client.list_notes(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.ListNotesRequest() + + assert args[0] == request_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_note_empty_call_grpc_asyncio(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_note), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_note(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.DeleteNoteRequest() + + assert args[0] == request_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_note_empty_call_grpc_asyncio(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_note), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note( + name='name_value', + short_description='short_description_value', + long_description='long_description_value', + kind=common.NoteKind.VULNERABILITY, + related_note_names=['related_note_names_value'], + )) + await client.create_note(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.CreateNoteRequest() + + assert args[0] == request_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_batch_create_notes_empty_call_grpc_asyncio(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_notes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.BatchCreateNotesResponse( + )) + await client.batch_create_notes(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.BatchCreateNotesRequest() + + assert args[0] == request_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_note_empty_call_grpc_asyncio(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_note), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note( + name='name_value', + short_description='short_description_value', + long_description='long_description_value', + kind=common.NoteKind.VULNERABILITY, + related_note_names=['related_note_names_value'], + )) + await client.update_note(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.UpdateNoteRequest() + + assert args[0] == request_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_note_occurrences_empty_call_grpc_asyncio(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_note_occurrences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.ListNoteOccurrencesResponse( + next_page_token='next_page_token_value', + )) + await client.list_note_occurrences(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.ListNoteOccurrencesRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = GrafeasClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_occurrence_rest_bad_request(request_type=grafeas.GetOccurrenceRequest): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/occurrences/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_occurrence(request) + + +@pytest.mark.parametrize("request_type", [ + grafeas.GetOccurrenceRequest, + dict, +]) +def test_get_occurrence_rest_call_success(request_type): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/occurrences/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 = grafeas.Occurrence( + name='name_value', + resource_uri='resource_uri_value', + note_name='note_name_value', + kind=common.NoteKind.VULNERABILITY, + remediation='remediation_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 = grafeas.Occurrence.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_occurrence(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Occurrence) + assert response.name == 'name_value' + assert response.resource_uri == 'resource_uri_value' + assert response.note_name == 'note_name_value' + assert response.kind == common.NoteKind.VULNERABILITY + assert response.remediation == 'remediation_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_occurrence_rest_interceptors(null_interceptor): + transport = transports.GrafeasRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), + ) + client = GrafeasClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.GrafeasRestInterceptor, "post_get_occurrence") as post, \ + mock.patch.object(transports.GrafeasRestInterceptor, "pre_get_occurrence") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = grafeas.GetOccurrenceRequest.pb(grafeas.GetOccurrenceRequest()) + 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 = grafeas.Occurrence.to_json(grafeas.Occurrence()) + req.return_value.content = return_value + + request = grafeas.GetOccurrenceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = grafeas.Occurrence() + + client.get_occurrence(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_occurrences_rest_bad_request(request_type=grafeas.ListOccurrencesRequest): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/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_occurrences(request) + + +@pytest.mark.parametrize("request_type", [ + grafeas.ListOccurrencesRequest, + dict, +]) +def test_list_occurrences_rest_call_success(request_type): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = grafeas.ListOccurrencesResponse( + 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 = grafeas.ListOccurrencesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_occurrences(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListOccurrencesPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_occurrences_rest_interceptors(null_interceptor): + transport = transports.GrafeasRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), + ) + client = GrafeasClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.GrafeasRestInterceptor, "post_list_occurrences") as post, \ + mock.patch.object(transports.GrafeasRestInterceptor, "pre_list_occurrences") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = grafeas.ListOccurrencesRequest.pb(grafeas.ListOccurrencesRequest()) + 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 = grafeas.ListOccurrencesResponse.to_json(grafeas.ListOccurrencesResponse()) + req.return_value.content = return_value + + request = grafeas.ListOccurrencesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = grafeas.ListOccurrencesResponse() + + client.list_occurrences(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_occurrence_rest_bad_request(request_type=grafeas.DeleteOccurrenceRequest): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/occurrences/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_occurrence(request) + + +@pytest.mark.parametrize("request_type", [ + grafeas.DeleteOccurrenceRequest, + dict, +]) +def test_delete_occurrence_rest_call_success(request_type): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/occurrences/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_occurrence(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_occurrence_rest_interceptors(null_interceptor): + transport = transports.GrafeasRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), + ) + client = GrafeasClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.GrafeasRestInterceptor, "pre_delete_occurrence") as pre: + pre.assert_not_called() + pb_message = grafeas.DeleteOccurrenceRequest.pb(grafeas.DeleteOccurrenceRequest()) + 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 = grafeas.DeleteOccurrenceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_occurrence(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_create_occurrence_rest_bad_request(request_type=grafeas.CreateOccurrenceRequest): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/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_occurrence(request) + + +@pytest.mark.parametrize("request_type", [ + grafeas.CreateOccurrenceRequest, + dict, +]) +def test_create_occurrence_rest_call_success(request_type): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1'} + request_init["occurrence"] = {'name': 'name_value', 'resource_uri': 'resource_uri_value', 'note_name': 'note_name_value', 'kind': 1, 'remediation': 'remediation_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'vulnerability': {'type_': 'type__value', 'severity': 1, 'cvss_score': 0.1082, 'cvssv3': {'base_score': 0.1046, 'exploitability_score': 0.21580000000000002, 'impact_score': 0.1273, 'attack_vector': 1, 'attack_complexity': 1, 'authentication': 1, 'privileges_required': 1, 'user_interaction': 1, 'scope': 1, 'confidentiality_impact': 1, 'integrity_impact': 1, 'availability_impact': 1}, 'package_issue': [{'affected_cpe_uri': 'affected_cpe_uri_value', 'affected_package': 'affected_package_value', 'affected_version': {'epoch': 527, 'name': 'name_value', 'revision': 'revision_value', 'inclusive': True, 'kind': 1, 'full_name': 'full_name_value'}, 'fixed_cpe_uri': 'fixed_cpe_uri_value', 'fixed_package': 'fixed_package_value', 'fixed_version': {}, 'fix_available': True, 'package_type': 'package_type_value', 'effective_severity': 1, 'file_location': [{'file_path': 'file_path_value'}]}], 'short_description': 'short_description_value', 'long_description': 'long_description_value', 'related_urls': [{'url': 'url_value', 'label': 'label_value'}], 'effective_severity': 1, 'fix_available': True, 'cvss_version': 1, 'cvss_v2': {}, 'vex_assessment': {'cve': 'cve_value', 'vulnerability_id': 'vulnerability_id_value', 'related_uris': {}, 'note_name': 'note_name_value', 'state': 1, 'impacts': ['impacts_value1', 'impacts_value2'], 'remediations': [{'remediation_type': 1, 'details': 'details_value', 'remediation_uri': {}}], 'justification': {'justification_type': 1, 'details': 'details_value'}}, 'extra_details': 'extra_details_value'}, 'build': {'provenance': {'id': 'id_value', 'project_id': 'project_id_value', 'commands': [{'name': 'name_value', 'env': ['env_value1', 'env_value2'], 'args': ['args_value1', 'args_value2'], 'dir_': 'dir__value', 'id': 'id_value', 'wait_for': ['wait_for_value1', 'wait_for_value2']}], 'built_artifacts': [{'checksum': 'checksum_value', 'id': 'id_value', 'names': ['names_value1', 'names_value2']}], 'create_time': {}, 'start_time': {}, 'end_time': {}, 'creator': 'creator_value', 'logs_uri': 'logs_uri_value', 'source_provenance': {'artifact_storage_source_uri': 'artifact_storage_source_uri_value', 'file_hashes': {}, 'context': {'cloud_repo': {'repo_id': {'project_repo_id': {'project_id': 'project_id_value', 'repo_name': 'repo_name_value'}, 'uid': 'uid_value'}, 'revision_id': 'revision_id_value', 'alias_context': {'kind': 1, 'name': 'name_value'}}, 'gerrit': {'host_uri': 'host_uri_value', 'gerrit_project': 'gerrit_project_value', 'revision_id': 'revision_id_value', 'alias_context': {}}, 'git': {'url': 'url_value', 'revision_id': 'revision_id_value'}, 'labels': {}}, 'additional_contexts': {}}, 'trigger_id': 'trigger_id_value', 'build_options': {}, 'builder_version': 'builder_version_value'}, 'provenance_bytes': 'provenance_bytes_value', 'intoto_provenance': {'builder_config': {'id': 'id_value'}, 'recipe': {'type_': 'type__value', 'defined_in_material': 1971, 'entry_point': 'entry_point_value', 'arguments': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}], 'environment': {}}, 'metadata': {'build_invocation_id': 'build_invocation_id_value', 'build_started_on': {}, 'build_finished_on': {}, 'completeness': {'arguments': True, 'environment': True, 'materials': True}, 'reproducible': True}, 'materials': ['materials_value1', 'materials_value2']}, 'intoto_statement': {'type_': 'type__value', 'subject': [{'name': 'name_value', 'digest': {}}], 'predicate_type': 'predicate_type_value', 'provenance': {}, 'slsa_provenance': {'builder': {'id': 'id_value'}, 'recipe': {'type_': 'type__value', 'defined_in_material': 1971, 'entry_point': 'entry_point_value', 'arguments': {}, 'environment': {}}, 'metadata': {'build_invocation_id': 'build_invocation_id_value', 'build_started_on': {}, 'build_finished_on': {}, 'completeness': {'arguments': True, 'environment': True, 'materials': True}, 'reproducible': True}, 'materials': [{'uri': 'uri_value', 'digest': {}}]}, 'slsa_provenance_zero_two': {'builder': {'id': 'id_value'}, 'build_type': 'build_type_value', 'invocation': {'config_source': {'uri': 'uri_value', 'digest': {}, 'entry_point': 'entry_point_value'}, 'parameters': {'fields': {}}, 'environment': {}}, 'build_config': {}, 'metadata': {'build_invocation_id': 'build_invocation_id_value', 'build_started_on': {}, 'build_finished_on': {}, 'completeness': {'parameters': True, 'environment': True, 'materials': True}, 'reproducible': True}, 'materials': [{'uri': 'uri_value', 'digest': {}}]}}, 'in_toto_slsa_provenance_v1': {'type_': 'type__value', 'subject': {}, 'predicate_type': 'predicate_type_value', 'predicate': {'build_definition': {'build_type': 'build_type_value', 'external_parameters': {}, 'internal_parameters': {}, 'resolved_dependencies': [{'name': 'name_value', 'uri': 'uri_value', 'digest': {}, 'content': b'content_blob', 'download_location': 'download_location_value', 'media_type': 'media_type_value', 'annotations': {}}]}, 'run_details': {'builder': {'id': 'id_value', 'version': {}, 'builder_dependencies': {}}, 'metadata': {'invocation_id': 'invocation_id_value', 'started_on': {}, 'finished_on': {}}, 'byproducts': {}}}}}, 'image': {'fingerprint': {'v1_name': 'v1_name_value', 'v2_blob': ['v2_blob_value1', 'v2_blob_value2'], 'v2_name': 'v2_name_value'}, 'distance': 843, 'layer_info': [{'directive': 'directive_value', 'arguments': 'arguments_value'}], 'base_resource_url': 'base_resource_url_value'}, 'package': {'name': 'name_value', 'location': [{'cpe_uri': 'cpe_uri_value', 'version': {}, 'path': 'path_value'}], 'package_type': 'package_type_value', 'cpe_uri': 'cpe_uri_value', 'architecture': 1, 'license_': {'expression': 'expression_value', 'comments': 'comments_value'}, 'version': {}}, 'deployment': {'user_email': 'user_email_value', 'deploy_time': {}, 'undeploy_time': {}, 'config': 'config_value', 'address': 'address_value', 'resource_uri': ['resource_uri_value1', 'resource_uri_value2'], 'platform': 1}, 'discovery': {'continuous_analysis': 1, 'analysis_status': 1, 'analysis_completed': {'analysis_type': ['analysis_type_value1', 'analysis_type_value2']}, 'analysis_error': [{'code': 411, 'message': 'message_value', 'details': {}}], 'analysis_status_error': {}, 'cpe': 'cpe_value', 'last_scan_time': {}, 'archive_time': {}, 'sbom_status': {'sbom_state': 1, 'error': 'error_value'}, 'vulnerability_attestation': {'last_attempt_time': {}, 'state': 1, 'error': 'error_value'}}, 'attestation': {'serialized_payload': b'serialized_payload_blob', 'signatures': [{'signature': b'signature_blob', 'public_key_id': 'public_key_id_value'}], 'jwts': [{'compact_jwt': 'compact_jwt_value'}]}, 'upgrade': {'package': 'package_value', 'parsed_version': {}, 'distribution': {'cpe_uri': 'cpe_uri_value', 'classification': 'classification_value', 'severity': 'severity_value', 'cve': ['cve_value1', 'cve_value2']}, 'windows_update': {'identity': {'update_id': 'update_id_value', 'revision': 879}, 'title': 'title_value', 'description': 'description_value', 'categories': [{'category_id': 'category_id_value', 'name': 'name_value'}], 'kb_article_ids': ['kb_article_ids_value1', 'kb_article_ids_value2'], 'support_url': 'support_url_value', 'last_published_timestamp': {}}}, 'compliance': {'non_compliant_files': [{'path': 'path_value', 'display_command': 'display_command_value', 'reason': 'reason_value'}], 'non_compliance_reason': 'non_compliance_reason_value', 'version': {'cpe_uri': 'cpe_uri_value', 'benchmark_document': 'benchmark_document_value', 'version': 'version_value'}}, 'dsse_attestation': {'envelope': {'payload': b'payload_blob', 'payload_type': 'payload_type_value', 'signatures': [{'sig': b'sig_blob', 'keyid': 'keyid_value'}]}, 'statement': {}}, 'sbom_reference': {'payload': {'type_': 'type__value', 'predicate_type': 'predicate_type_value', 'subject': {}, 'predicate': {'referrer_id': 'referrer_id_value', 'location': 'location_value', 'mime_type': 'mime_type_value', 'digest': {}}}, 'payload_type': 'payload_type_value', 'signatures': {}}, 'envelope': {}} + # 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 = grafeas.CreateOccurrenceRequest.meta.fields["occurrence"] + + 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["occurrence"].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["occurrence"][field])): + del request_init["occurrence"][field][i][subfield] + else: + del request_init["occurrence"][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 = grafeas.Occurrence( + name='name_value', + resource_uri='resource_uri_value', + note_name='note_name_value', + kind=common.NoteKind.VULNERABILITY, + remediation='remediation_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 = grafeas.Occurrence.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_occurrence(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Occurrence) + assert response.name == 'name_value' + assert response.resource_uri == 'resource_uri_value' + assert response.note_name == 'note_name_value' + assert response.kind == common.NoteKind.VULNERABILITY + assert response.remediation == 'remediation_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_occurrence_rest_interceptors(null_interceptor): + transport = transports.GrafeasRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), + ) + client = GrafeasClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.GrafeasRestInterceptor, "post_create_occurrence") as post, \ + mock.patch.object(transports.GrafeasRestInterceptor, "pre_create_occurrence") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = grafeas.CreateOccurrenceRequest.pb(grafeas.CreateOccurrenceRequest()) + 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 = grafeas.Occurrence.to_json(grafeas.Occurrence()) + req.return_value.content = return_value + + request = grafeas.CreateOccurrenceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = grafeas.Occurrence() + + client.create_occurrence(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_batch_create_occurrences_rest_bad_request(request_type=grafeas.BatchCreateOccurrencesRequest): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/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.batch_create_occurrences(request) + + +@pytest.mark.parametrize("request_type", [ + grafeas.BatchCreateOccurrencesRequest, + dict, +]) +def test_batch_create_occurrences_rest_call_success(request_type): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = grafeas.BatchCreateOccurrencesResponse( + ) + + # 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 = grafeas.BatchCreateOccurrencesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.batch_create_occurrences(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.BatchCreateOccurrencesResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_create_occurrences_rest_interceptors(null_interceptor): + transport = transports.GrafeasRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), + ) + client = GrafeasClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.GrafeasRestInterceptor, "post_batch_create_occurrences") as post, \ + mock.patch.object(transports.GrafeasRestInterceptor, "pre_batch_create_occurrences") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = grafeas.BatchCreateOccurrencesRequest.pb(grafeas.BatchCreateOccurrencesRequest()) + 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 = grafeas.BatchCreateOccurrencesResponse.to_json(grafeas.BatchCreateOccurrencesResponse()) + req.return_value.content = return_value + + request = grafeas.BatchCreateOccurrencesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = grafeas.BatchCreateOccurrencesResponse() + + client.batch_create_occurrences(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_occurrence_rest_bad_request(request_type=grafeas.UpdateOccurrenceRequest): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/occurrences/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_occurrence(request) + + +@pytest.mark.parametrize("request_type", [ + grafeas.UpdateOccurrenceRequest, + dict, +]) +def test_update_occurrence_rest_call_success(request_type): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/occurrences/sample2'} + request_init["occurrence"] = {'name': 'name_value', 'resource_uri': 'resource_uri_value', 'note_name': 'note_name_value', 'kind': 1, 'remediation': 'remediation_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'vulnerability': {'type_': 'type__value', 'severity': 1, 'cvss_score': 0.1082, 'cvssv3': {'base_score': 0.1046, 'exploitability_score': 0.21580000000000002, 'impact_score': 0.1273, 'attack_vector': 1, 'attack_complexity': 1, 'authentication': 1, 'privileges_required': 1, 'user_interaction': 1, 'scope': 1, 'confidentiality_impact': 1, 'integrity_impact': 1, 'availability_impact': 1}, 'package_issue': [{'affected_cpe_uri': 'affected_cpe_uri_value', 'affected_package': 'affected_package_value', 'affected_version': {'epoch': 527, 'name': 'name_value', 'revision': 'revision_value', 'inclusive': True, 'kind': 1, 'full_name': 'full_name_value'}, 'fixed_cpe_uri': 'fixed_cpe_uri_value', 'fixed_package': 'fixed_package_value', 'fixed_version': {}, 'fix_available': True, 'package_type': 'package_type_value', 'effective_severity': 1, 'file_location': [{'file_path': 'file_path_value'}]}], 'short_description': 'short_description_value', 'long_description': 'long_description_value', 'related_urls': [{'url': 'url_value', 'label': 'label_value'}], 'effective_severity': 1, 'fix_available': True, 'cvss_version': 1, 'cvss_v2': {}, 'vex_assessment': {'cve': 'cve_value', 'vulnerability_id': 'vulnerability_id_value', 'related_uris': {}, 'note_name': 'note_name_value', 'state': 1, 'impacts': ['impacts_value1', 'impacts_value2'], 'remediations': [{'remediation_type': 1, 'details': 'details_value', 'remediation_uri': {}}], 'justification': {'justification_type': 1, 'details': 'details_value'}}, 'extra_details': 'extra_details_value'}, 'build': {'provenance': {'id': 'id_value', 'project_id': 'project_id_value', 'commands': [{'name': 'name_value', 'env': ['env_value1', 'env_value2'], 'args': ['args_value1', 'args_value2'], 'dir_': 'dir__value', 'id': 'id_value', 'wait_for': ['wait_for_value1', 'wait_for_value2']}], 'built_artifacts': [{'checksum': 'checksum_value', 'id': 'id_value', 'names': ['names_value1', 'names_value2']}], 'create_time': {}, 'start_time': {}, 'end_time': {}, 'creator': 'creator_value', 'logs_uri': 'logs_uri_value', 'source_provenance': {'artifact_storage_source_uri': 'artifact_storage_source_uri_value', 'file_hashes': {}, 'context': {'cloud_repo': {'repo_id': {'project_repo_id': {'project_id': 'project_id_value', 'repo_name': 'repo_name_value'}, 'uid': 'uid_value'}, 'revision_id': 'revision_id_value', 'alias_context': {'kind': 1, 'name': 'name_value'}}, 'gerrit': {'host_uri': 'host_uri_value', 'gerrit_project': 'gerrit_project_value', 'revision_id': 'revision_id_value', 'alias_context': {}}, 'git': {'url': 'url_value', 'revision_id': 'revision_id_value'}, 'labels': {}}, 'additional_contexts': {}}, 'trigger_id': 'trigger_id_value', 'build_options': {}, 'builder_version': 'builder_version_value'}, 'provenance_bytes': 'provenance_bytes_value', 'intoto_provenance': {'builder_config': {'id': 'id_value'}, 'recipe': {'type_': 'type__value', 'defined_in_material': 1971, 'entry_point': 'entry_point_value', 'arguments': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}], 'environment': {}}, 'metadata': {'build_invocation_id': 'build_invocation_id_value', 'build_started_on': {}, 'build_finished_on': {}, 'completeness': {'arguments': True, 'environment': True, 'materials': True}, 'reproducible': True}, 'materials': ['materials_value1', 'materials_value2']}, 'intoto_statement': {'type_': 'type__value', 'subject': [{'name': 'name_value', 'digest': {}}], 'predicate_type': 'predicate_type_value', 'provenance': {}, 'slsa_provenance': {'builder': {'id': 'id_value'}, 'recipe': {'type_': 'type__value', 'defined_in_material': 1971, 'entry_point': 'entry_point_value', 'arguments': {}, 'environment': {}}, 'metadata': {'build_invocation_id': 'build_invocation_id_value', 'build_started_on': {}, 'build_finished_on': {}, 'completeness': {'arguments': True, 'environment': True, 'materials': True}, 'reproducible': True}, 'materials': [{'uri': 'uri_value', 'digest': {}}]}, 'slsa_provenance_zero_two': {'builder': {'id': 'id_value'}, 'build_type': 'build_type_value', 'invocation': {'config_source': {'uri': 'uri_value', 'digest': {}, 'entry_point': 'entry_point_value'}, 'parameters': {'fields': {}}, 'environment': {}}, 'build_config': {}, 'metadata': {'build_invocation_id': 'build_invocation_id_value', 'build_started_on': {}, 'build_finished_on': {}, 'completeness': {'parameters': True, 'environment': True, 'materials': True}, 'reproducible': True}, 'materials': [{'uri': 'uri_value', 'digest': {}}]}}, 'in_toto_slsa_provenance_v1': {'type_': 'type__value', 'subject': {}, 'predicate_type': 'predicate_type_value', 'predicate': {'build_definition': {'build_type': 'build_type_value', 'external_parameters': {}, 'internal_parameters': {}, 'resolved_dependencies': [{'name': 'name_value', 'uri': 'uri_value', 'digest': {}, 'content': b'content_blob', 'download_location': 'download_location_value', 'media_type': 'media_type_value', 'annotations': {}}]}, 'run_details': {'builder': {'id': 'id_value', 'version': {}, 'builder_dependencies': {}}, 'metadata': {'invocation_id': 'invocation_id_value', 'started_on': {}, 'finished_on': {}}, 'byproducts': {}}}}}, 'image': {'fingerprint': {'v1_name': 'v1_name_value', 'v2_blob': ['v2_blob_value1', 'v2_blob_value2'], 'v2_name': 'v2_name_value'}, 'distance': 843, 'layer_info': [{'directive': 'directive_value', 'arguments': 'arguments_value'}], 'base_resource_url': 'base_resource_url_value'}, 'package': {'name': 'name_value', 'location': [{'cpe_uri': 'cpe_uri_value', 'version': {}, 'path': 'path_value'}], 'package_type': 'package_type_value', 'cpe_uri': 'cpe_uri_value', 'architecture': 1, 'license_': {'expression': 'expression_value', 'comments': 'comments_value'}, 'version': {}}, 'deployment': {'user_email': 'user_email_value', 'deploy_time': {}, 'undeploy_time': {}, 'config': 'config_value', 'address': 'address_value', 'resource_uri': ['resource_uri_value1', 'resource_uri_value2'], 'platform': 1}, 'discovery': {'continuous_analysis': 1, 'analysis_status': 1, 'analysis_completed': {'analysis_type': ['analysis_type_value1', 'analysis_type_value2']}, 'analysis_error': [{'code': 411, 'message': 'message_value', 'details': {}}], 'analysis_status_error': {}, 'cpe': 'cpe_value', 'last_scan_time': {}, 'archive_time': {}, 'sbom_status': {'sbom_state': 1, 'error': 'error_value'}, 'vulnerability_attestation': {'last_attempt_time': {}, 'state': 1, 'error': 'error_value'}}, 'attestation': {'serialized_payload': b'serialized_payload_blob', 'signatures': [{'signature': b'signature_blob', 'public_key_id': 'public_key_id_value'}], 'jwts': [{'compact_jwt': 'compact_jwt_value'}]}, 'upgrade': {'package': 'package_value', 'parsed_version': {}, 'distribution': {'cpe_uri': 'cpe_uri_value', 'classification': 'classification_value', 'severity': 'severity_value', 'cve': ['cve_value1', 'cve_value2']}, 'windows_update': {'identity': {'update_id': 'update_id_value', 'revision': 879}, 'title': 'title_value', 'description': 'description_value', 'categories': [{'category_id': 'category_id_value', 'name': 'name_value'}], 'kb_article_ids': ['kb_article_ids_value1', 'kb_article_ids_value2'], 'support_url': 'support_url_value', 'last_published_timestamp': {}}}, 'compliance': {'non_compliant_files': [{'path': 'path_value', 'display_command': 'display_command_value', 'reason': 'reason_value'}], 'non_compliance_reason': 'non_compliance_reason_value', 'version': {'cpe_uri': 'cpe_uri_value', 'benchmark_document': 'benchmark_document_value', 'version': 'version_value'}}, 'dsse_attestation': {'envelope': {'payload': b'payload_blob', 'payload_type': 'payload_type_value', 'signatures': [{'sig': b'sig_blob', 'keyid': 'keyid_value'}]}, 'statement': {}}, 'sbom_reference': {'payload': {'type_': 'type__value', 'predicate_type': 'predicate_type_value', 'subject': {}, 'predicate': {'referrer_id': 'referrer_id_value', 'location': 'location_value', 'mime_type': 'mime_type_value', 'digest': {}}}, 'payload_type': 'payload_type_value', 'signatures': {}}, 'envelope': {}} + # 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 = grafeas.UpdateOccurrenceRequest.meta.fields["occurrence"] + + 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["occurrence"].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["occurrence"][field])): + del request_init["occurrence"][field][i][subfield] + else: + del request_init["occurrence"][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 = grafeas.Occurrence( + name='name_value', + resource_uri='resource_uri_value', + note_name='note_name_value', + kind=common.NoteKind.VULNERABILITY, + remediation='remediation_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 = grafeas.Occurrence.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_occurrence(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Occurrence) + assert response.name == 'name_value' + assert response.resource_uri == 'resource_uri_value' + assert response.note_name == 'note_name_value' + assert response.kind == common.NoteKind.VULNERABILITY + assert response.remediation == 'remediation_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_occurrence_rest_interceptors(null_interceptor): + transport = transports.GrafeasRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), + ) + client = GrafeasClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.GrafeasRestInterceptor, "post_update_occurrence") as post, \ + mock.patch.object(transports.GrafeasRestInterceptor, "pre_update_occurrence") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = grafeas.UpdateOccurrenceRequest.pb(grafeas.UpdateOccurrenceRequest()) + 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 = grafeas.Occurrence.to_json(grafeas.Occurrence()) + req.return_value.content = return_value + + request = grafeas.UpdateOccurrenceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = grafeas.Occurrence() + + client.update_occurrence(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_occurrence_note_rest_bad_request(request_type=grafeas.GetOccurrenceNoteRequest): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/occurrences/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_occurrence_note(request) + + +@pytest.mark.parametrize("request_type", [ + grafeas.GetOccurrenceNoteRequest, + dict, +]) +def test_get_occurrence_note_rest_call_success(request_type): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/occurrences/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 = grafeas.Note( + name='name_value', + short_description='short_description_value', + long_description='long_description_value', + kind=common.NoteKind.VULNERABILITY, + related_note_names=['related_note_names_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 = grafeas.Note.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_occurrence_note(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Note) + assert response.name == 'name_value' + assert response.short_description == 'short_description_value' + assert response.long_description == 'long_description_value' + assert response.kind == common.NoteKind.VULNERABILITY + assert response.related_note_names == ['related_note_names_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_occurrence_note_rest_interceptors(null_interceptor): + transport = transports.GrafeasRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), + ) + client = GrafeasClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.GrafeasRestInterceptor, "post_get_occurrence_note") as post, \ + mock.patch.object(transports.GrafeasRestInterceptor, "pre_get_occurrence_note") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = grafeas.GetOccurrenceNoteRequest.pb(grafeas.GetOccurrenceNoteRequest()) + 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 = grafeas.Note.to_json(grafeas.Note()) + req.return_value.content = return_value + + request = grafeas.GetOccurrenceNoteRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = grafeas.Note() + + client.get_occurrence_note(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_note_rest_bad_request(request_type=grafeas.GetNoteRequest): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/notes/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_note(request) + + +@pytest.mark.parametrize("request_type", [ + grafeas.GetNoteRequest, + dict, +]) +def test_get_note_rest_call_success(request_type): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/notes/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 = grafeas.Note( + name='name_value', + short_description='short_description_value', + long_description='long_description_value', + kind=common.NoteKind.VULNERABILITY, + related_note_names=['related_note_names_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 = grafeas.Note.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_note(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Note) + assert response.name == 'name_value' + assert response.short_description == 'short_description_value' + assert response.long_description == 'long_description_value' + assert response.kind == common.NoteKind.VULNERABILITY + assert response.related_note_names == ['related_note_names_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_note_rest_interceptors(null_interceptor): + transport = transports.GrafeasRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), + ) + client = GrafeasClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.GrafeasRestInterceptor, "post_get_note") as post, \ + mock.patch.object(transports.GrafeasRestInterceptor, "pre_get_note") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = grafeas.GetNoteRequest.pb(grafeas.GetNoteRequest()) + 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 = grafeas.Note.to_json(grafeas.Note()) + req.return_value.content = return_value + + request = grafeas.GetNoteRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = grafeas.Note() + + client.get_note(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_notes_rest_bad_request(request_type=grafeas.ListNotesRequest): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/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_notes(request) + + +@pytest.mark.parametrize("request_type", [ + grafeas.ListNotesRequest, + dict, +]) +def test_list_notes_rest_call_success(request_type): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = grafeas.ListNotesResponse( + 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 = grafeas.ListNotesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_notes(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNotesPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_notes_rest_interceptors(null_interceptor): + transport = transports.GrafeasRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), + ) + client = GrafeasClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.GrafeasRestInterceptor, "post_list_notes") as post, \ + mock.patch.object(transports.GrafeasRestInterceptor, "pre_list_notes") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = grafeas.ListNotesRequest.pb(grafeas.ListNotesRequest()) + 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 = grafeas.ListNotesResponse.to_json(grafeas.ListNotesResponse()) + req.return_value.content = return_value + + request = grafeas.ListNotesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = grafeas.ListNotesResponse() + + client.list_notes(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_note_rest_bad_request(request_type=grafeas.DeleteNoteRequest): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/notes/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_note(request) + + +@pytest.mark.parametrize("request_type", [ + grafeas.DeleteNoteRequest, + dict, +]) +def test_delete_note_rest_call_success(request_type): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/notes/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_note(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_note_rest_interceptors(null_interceptor): + transport = transports.GrafeasRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), + ) + client = GrafeasClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.GrafeasRestInterceptor, "pre_delete_note") as pre: + pre.assert_not_called() + pb_message = grafeas.DeleteNoteRequest.pb(grafeas.DeleteNoteRequest()) + 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 = grafeas.DeleteNoteRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_note(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_create_note_rest_bad_request(request_type=grafeas.CreateNoteRequest): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/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_note(request) + + +@pytest.mark.parametrize("request_type", [ + grafeas.CreateNoteRequest, + dict, +]) +def test_create_note_rest_call_success(request_type): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1'} + request_init["note"] = {'name': 'name_value', 'short_description': 'short_description_value', 'long_description': 'long_description_value', 'kind': 1, 'related_url': [{'url': 'url_value', 'label': 'label_value'}], 'expiration_time': {'seconds': 751, 'nanos': 543}, 'create_time': {}, 'update_time': {}, 'related_note_names': ['related_note_names_value1', 'related_note_names_value2'], 'vulnerability': {'cvss_score': 0.1082, 'severity': 1, 'details': [{'severity_name': 'severity_name_value', 'description': 'description_value', 'package_type': 'package_type_value', 'affected_cpe_uri': 'affected_cpe_uri_value', 'affected_package': 'affected_package_value', 'affected_version_start': {'epoch': 527, 'name': 'name_value', 'revision': 'revision_value', 'inclusive': True, 'kind': 1, 'full_name': 'full_name_value'}, 'affected_version_end': {}, 'fixed_cpe_uri': 'fixed_cpe_uri_value', 'fixed_package': 'fixed_package_value', 'fixed_version': {}, 'is_obsolete': True, 'source_update_time': {}, 'source': 'source_value', 'vendor': 'vendor_value'}], 'cvss_v3': {'base_score': 0.1046, 'exploitability_score': 0.21580000000000002, 'impact_score': 0.1273, 'attack_vector': 1, 'attack_complexity': 1, 'privileges_required': 1, 'user_interaction': 1, 'scope': 1, 'confidentiality_impact': 1, 'integrity_impact': 1, 'availability_impact': 1}, 'windows_details': [{'cpe_uri': 'cpe_uri_value', 'name': 'name_value', 'description': 'description_value', 'fixing_kbs': [{'name': 'name_value', 'url': 'url_value'}]}], 'source_update_time': {}, 'cvss_version': 1, 'cvss_v2': {'base_score': 0.1046, 'exploitability_score': 0.21580000000000002, 'impact_score': 0.1273, 'attack_vector': 1, 'attack_complexity': 1, 'authentication': 1, 'privileges_required': 1, 'user_interaction': 1, 'scope': 1, 'confidentiality_impact': 1, 'integrity_impact': 1, 'availability_impact': 1}}, 'build': {'builder_version': 'builder_version_value'}, 'image': {'resource_url': 'resource_url_value', 'fingerprint': {'v1_name': 'v1_name_value', 'v2_blob': ['v2_blob_value1', 'v2_blob_value2'], 'v2_name': 'v2_name_value'}}, 'package': {'name': 'name_value', 'distribution': [{'cpe_uri': 'cpe_uri_value', 'architecture': 1, 'latest_version': {}, 'maintainer': 'maintainer_value', 'url': 'url_value', 'description': 'description_value'}], 'package_type': 'package_type_value', 'cpe_uri': 'cpe_uri_value', 'architecture': 1, 'version': {}, 'maintainer': 'maintainer_value', 'url': 'url_value', 'description': 'description_value', 'license_': {'expression': 'expression_value', 'comments': 'comments_value'}, 'digest': [{'algo': 'algo_value', 'digest_bytes': b'digest_bytes_blob'}]}, 'deployment': {'resource_uri': ['resource_uri_value1', 'resource_uri_value2']}, 'discovery': {'analysis_kind': 1}, 'attestation': {'hint': {'human_readable_name': 'human_readable_name_value'}}, 'upgrade': {'package': 'package_value', 'version': {}, 'distributions': [{'cpe_uri': 'cpe_uri_value', 'classification': 'classification_value', 'severity': 'severity_value', 'cve': ['cve_value1', 'cve_value2']}], 'windows_update': {'identity': {'update_id': 'update_id_value', 'revision': 879}, 'title': 'title_value', 'description': 'description_value', 'categories': [{'category_id': 'category_id_value', 'name': 'name_value'}], 'kb_article_ids': ['kb_article_ids_value1', 'kb_article_ids_value2'], 'support_url': 'support_url_value', 'last_published_timestamp': {}}}, 'compliance': {'title': 'title_value', 'description': 'description_value', 'version': [{'cpe_uri': 'cpe_uri_value', 'benchmark_document': 'benchmark_document_value', 'version': 'version_value'}], 'rationale': 'rationale_value', 'remediation': 'remediation_value', 'cis_benchmark': {'profile_level': 1384, 'severity': 1}, 'scan_instructions': b'scan_instructions_blob', 'impact': 'impact_value'}, 'dsse_attestation': {'hint': {'human_readable_name': 'human_readable_name_value'}}, 'vulnerability_assessment': {'title': 'title_value', 'short_description': 'short_description_value', 'long_description': 'long_description_value', 'language_code': 'language_code_value', 'publisher': {'name': 'name_value', 'issuing_authority': 'issuing_authority_value', 'publisher_namespace': 'publisher_namespace_value'}, 'product': {'name': 'name_value', 'id': 'id_value', 'generic_uri': 'generic_uri_value'}, 'assessment': {'cve': 'cve_value', 'vulnerability_id': 'vulnerability_id_value', 'short_description': 'short_description_value', 'long_description': 'long_description_value', 'related_uris': {}, 'state': 1, 'impacts': ['impacts_value1', 'impacts_value2'], 'justification': {'justification_type': 1, 'details': 'details_value'}, 'remediations': [{'remediation_type': 1, 'details': 'details_value', 'remediation_uri': {}}]}}, 'sbom_reference': {'format_': 'format__value', 'version': 'version_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 = grafeas.CreateNoteRequest.meta.fields["note"] + + 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["note"].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["note"][field])): + del request_init["note"][field][i][subfield] + else: + del request_init["note"][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 = grafeas.Note( + name='name_value', + short_description='short_description_value', + long_description='long_description_value', + kind=common.NoteKind.VULNERABILITY, + related_note_names=['related_note_names_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 = grafeas.Note.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_note(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Note) + assert response.name == 'name_value' + assert response.short_description == 'short_description_value' + assert response.long_description == 'long_description_value' + assert response.kind == common.NoteKind.VULNERABILITY + assert response.related_note_names == ['related_note_names_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_note_rest_interceptors(null_interceptor): + transport = transports.GrafeasRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), + ) + client = GrafeasClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.GrafeasRestInterceptor, "post_create_note") as post, \ + mock.patch.object(transports.GrafeasRestInterceptor, "pre_create_note") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = grafeas.CreateNoteRequest.pb(grafeas.CreateNoteRequest()) + 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 = grafeas.Note.to_json(grafeas.Note()) + req.return_value.content = return_value + + request = grafeas.CreateNoteRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = grafeas.Note() + + client.create_note(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_batch_create_notes_rest_bad_request(request_type=grafeas.BatchCreateNotesRequest): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/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.batch_create_notes(request) + + +@pytest.mark.parametrize("request_type", [ + grafeas.BatchCreateNotesRequest, + dict, +]) +def test_batch_create_notes_rest_call_success(request_type): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = grafeas.BatchCreateNotesResponse( + ) + + # 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 = grafeas.BatchCreateNotesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.batch_create_notes(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.BatchCreateNotesResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_create_notes_rest_interceptors(null_interceptor): + transport = transports.GrafeasRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), + ) + client = GrafeasClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.GrafeasRestInterceptor, "post_batch_create_notes") as post, \ + mock.patch.object(transports.GrafeasRestInterceptor, "pre_batch_create_notes") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = grafeas.BatchCreateNotesRequest.pb(grafeas.BatchCreateNotesRequest()) + 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 = grafeas.BatchCreateNotesResponse.to_json(grafeas.BatchCreateNotesResponse()) + req.return_value.content = return_value + + request = grafeas.BatchCreateNotesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = grafeas.BatchCreateNotesResponse() + + client.batch_create_notes(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_note_rest_bad_request(request_type=grafeas.UpdateNoteRequest): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/notes/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_note(request) + + +@pytest.mark.parametrize("request_type", [ + grafeas.UpdateNoteRequest, + dict, +]) +def test_update_note_rest_call_success(request_type): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/notes/sample2'} + request_init["note"] = {'name': 'name_value', 'short_description': 'short_description_value', 'long_description': 'long_description_value', 'kind': 1, 'related_url': [{'url': 'url_value', 'label': 'label_value'}], 'expiration_time': {'seconds': 751, 'nanos': 543}, 'create_time': {}, 'update_time': {}, 'related_note_names': ['related_note_names_value1', 'related_note_names_value2'], 'vulnerability': {'cvss_score': 0.1082, 'severity': 1, 'details': [{'severity_name': 'severity_name_value', 'description': 'description_value', 'package_type': 'package_type_value', 'affected_cpe_uri': 'affected_cpe_uri_value', 'affected_package': 'affected_package_value', 'affected_version_start': {'epoch': 527, 'name': 'name_value', 'revision': 'revision_value', 'inclusive': True, 'kind': 1, 'full_name': 'full_name_value'}, 'affected_version_end': {}, 'fixed_cpe_uri': 'fixed_cpe_uri_value', 'fixed_package': 'fixed_package_value', 'fixed_version': {}, 'is_obsolete': True, 'source_update_time': {}, 'source': 'source_value', 'vendor': 'vendor_value'}], 'cvss_v3': {'base_score': 0.1046, 'exploitability_score': 0.21580000000000002, 'impact_score': 0.1273, 'attack_vector': 1, 'attack_complexity': 1, 'privileges_required': 1, 'user_interaction': 1, 'scope': 1, 'confidentiality_impact': 1, 'integrity_impact': 1, 'availability_impact': 1}, 'windows_details': [{'cpe_uri': 'cpe_uri_value', 'name': 'name_value', 'description': 'description_value', 'fixing_kbs': [{'name': 'name_value', 'url': 'url_value'}]}], 'source_update_time': {}, 'cvss_version': 1, 'cvss_v2': {'base_score': 0.1046, 'exploitability_score': 0.21580000000000002, 'impact_score': 0.1273, 'attack_vector': 1, 'attack_complexity': 1, 'authentication': 1, 'privileges_required': 1, 'user_interaction': 1, 'scope': 1, 'confidentiality_impact': 1, 'integrity_impact': 1, 'availability_impact': 1}}, 'build': {'builder_version': 'builder_version_value'}, 'image': {'resource_url': 'resource_url_value', 'fingerprint': {'v1_name': 'v1_name_value', 'v2_blob': ['v2_blob_value1', 'v2_blob_value2'], 'v2_name': 'v2_name_value'}}, 'package': {'name': 'name_value', 'distribution': [{'cpe_uri': 'cpe_uri_value', 'architecture': 1, 'latest_version': {}, 'maintainer': 'maintainer_value', 'url': 'url_value', 'description': 'description_value'}], 'package_type': 'package_type_value', 'cpe_uri': 'cpe_uri_value', 'architecture': 1, 'version': {}, 'maintainer': 'maintainer_value', 'url': 'url_value', 'description': 'description_value', 'license_': {'expression': 'expression_value', 'comments': 'comments_value'}, 'digest': [{'algo': 'algo_value', 'digest_bytes': b'digest_bytes_blob'}]}, 'deployment': {'resource_uri': ['resource_uri_value1', 'resource_uri_value2']}, 'discovery': {'analysis_kind': 1}, 'attestation': {'hint': {'human_readable_name': 'human_readable_name_value'}}, 'upgrade': {'package': 'package_value', 'version': {}, 'distributions': [{'cpe_uri': 'cpe_uri_value', 'classification': 'classification_value', 'severity': 'severity_value', 'cve': ['cve_value1', 'cve_value2']}], 'windows_update': {'identity': {'update_id': 'update_id_value', 'revision': 879}, 'title': 'title_value', 'description': 'description_value', 'categories': [{'category_id': 'category_id_value', 'name': 'name_value'}], 'kb_article_ids': ['kb_article_ids_value1', 'kb_article_ids_value2'], 'support_url': 'support_url_value', 'last_published_timestamp': {}}}, 'compliance': {'title': 'title_value', 'description': 'description_value', 'version': [{'cpe_uri': 'cpe_uri_value', 'benchmark_document': 'benchmark_document_value', 'version': 'version_value'}], 'rationale': 'rationale_value', 'remediation': 'remediation_value', 'cis_benchmark': {'profile_level': 1384, 'severity': 1}, 'scan_instructions': b'scan_instructions_blob', 'impact': 'impact_value'}, 'dsse_attestation': {'hint': {'human_readable_name': 'human_readable_name_value'}}, 'vulnerability_assessment': {'title': 'title_value', 'short_description': 'short_description_value', 'long_description': 'long_description_value', 'language_code': 'language_code_value', 'publisher': {'name': 'name_value', 'issuing_authority': 'issuing_authority_value', 'publisher_namespace': 'publisher_namespace_value'}, 'product': {'name': 'name_value', 'id': 'id_value', 'generic_uri': 'generic_uri_value'}, 'assessment': {'cve': 'cve_value', 'vulnerability_id': 'vulnerability_id_value', 'short_description': 'short_description_value', 'long_description': 'long_description_value', 'related_uris': {}, 'state': 1, 'impacts': ['impacts_value1', 'impacts_value2'], 'justification': {'justification_type': 1, 'details': 'details_value'}, 'remediations': [{'remediation_type': 1, 'details': 'details_value', 'remediation_uri': {}}]}}, 'sbom_reference': {'format_': 'format__value', 'version': 'version_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 = grafeas.UpdateNoteRequest.meta.fields["note"] + + 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["note"].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["note"][field])): + del request_init["note"][field][i][subfield] + else: + del request_init["note"][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 = grafeas.Note( + name='name_value', + short_description='short_description_value', + long_description='long_description_value', + kind=common.NoteKind.VULNERABILITY, + related_note_names=['related_note_names_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 = grafeas.Note.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_note(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Note) + assert response.name == 'name_value' + assert response.short_description == 'short_description_value' + assert response.long_description == 'long_description_value' + assert response.kind == common.NoteKind.VULNERABILITY + assert response.related_note_names == ['related_note_names_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_note_rest_interceptors(null_interceptor): + transport = transports.GrafeasRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), + ) + client = GrafeasClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.GrafeasRestInterceptor, "post_update_note") as post, \ + mock.patch.object(transports.GrafeasRestInterceptor, "pre_update_note") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = grafeas.UpdateNoteRequest.pb(grafeas.UpdateNoteRequest()) + 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 = grafeas.Note.to_json(grafeas.Note()) + req.return_value.content = return_value + + request = grafeas.UpdateNoteRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = grafeas.Note() + + client.update_note(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_note_occurrences_rest_bad_request(request_type=grafeas.ListNoteOccurrencesRequest): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/notes/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_note_occurrences(request) + + +@pytest.mark.parametrize("request_type", [ + grafeas.ListNoteOccurrencesRequest, + dict, +]) +def test_list_note_occurrences_rest_call_success(request_type): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/notes/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 = grafeas.ListNoteOccurrencesResponse( + 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 = grafeas.ListNoteOccurrencesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_note_occurrences(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNoteOccurrencesPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_note_occurrences_rest_interceptors(null_interceptor): + transport = transports.GrafeasRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), + ) + client = GrafeasClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.GrafeasRestInterceptor, "post_list_note_occurrences") as post, \ + mock.patch.object(transports.GrafeasRestInterceptor, "pre_list_note_occurrences") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = grafeas.ListNoteOccurrencesRequest.pb(grafeas.ListNoteOccurrencesRequest()) + 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 = grafeas.ListNoteOccurrencesResponse.to_json(grafeas.ListNoteOccurrencesResponse()) + req.return_value.content = return_value + + request = grafeas.ListNoteOccurrencesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = grafeas.ListNoteOccurrencesResponse() + + client.list_note_occurrences(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + +def test_initialize_client_w_rest(): + client = GrafeasClient( + 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_occurrence_empty_call_rest(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_occurrence), + '__call__') as call: + client.get_occurrence(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.GetOccurrenceRequest() + + assert args[0] == request_msg + + +# This 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_occurrences_empty_call_rest(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_occurrences), + '__call__') as call: + client.list_occurrences(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.ListOccurrencesRequest() + + assert args[0] == request_msg + + +# This 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_occurrence_empty_call_rest(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_occurrence), + '__call__') as call: + client.delete_occurrence(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.DeleteOccurrenceRequest() + + assert args[0] == request_msg + + +# This 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_occurrence_empty_call_rest(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_occurrence), + '__call__') as call: + client.create_occurrence(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.CreateOccurrenceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_batch_create_occurrences_empty_call_rest(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_occurrences), + '__call__') as call: + client.batch_create_occurrences(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.BatchCreateOccurrencesRequest() + + assert args[0] == request_msg + + +# This 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_occurrence_empty_call_rest(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_occurrence), + '__call__') as call: + client.update_occurrence(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.UpdateOccurrenceRequest() + + assert args[0] == request_msg + + +# This 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_occurrence_note_empty_call_rest(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_occurrence_note), + '__call__') as call: + client.get_occurrence_note(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.GetOccurrenceNoteRequest() + + assert args[0] == request_msg + + +# This 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_note_empty_call_rest(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_note), + '__call__') as call: + client.get_note(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.GetNoteRequest() + + assert args[0] == request_msg + + +# This 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_notes_empty_call_rest(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_notes), + '__call__') as call: + client.list_notes(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.ListNotesRequest() + + assert args[0] == request_msg + + +# This 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_note_empty_call_rest(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_note), + '__call__') as call: + client.delete_note(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.DeleteNoteRequest() + + assert args[0] == request_msg + + +# This 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_note_empty_call_rest(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_note), + '__call__') as call: + client.create_note(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.CreateNoteRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_batch_create_notes_empty_call_rest(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_notes), + '__call__') as call: + client.batch_create_notes(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.BatchCreateNotesRequest() + + assert args[0] == request_msg + + +# This 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_note_empty_call_rest(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_note), + '__call__') as call: + client.update_note(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.UpdateNoteRequest() + + assert args[0] == request_msg + + +# This 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_note_occurrences_empty_call_rest(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_note_occurrences), + '__call__') as call: + client.list_note_occurrences(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.ListNoteOccurrencesRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.GrafeasGrpcTransport, + ) + +def test_grafeas_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.GrafeasTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_grafeas_base_transport(): + # Instantiate the base transport. + with mock.patch('grafeas.grafeas_v1.services.grafeas.transports.GrafeasTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.GrafeasTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_occurrence', + 'list_occurrences', + 'delete_occurrence', + 'create_occurrence', + 'batch_create_occurrences', + 'update_occurrence', + 'get_occurrence_note', + 'get_note', + 'list_notes', + 'delete_note', + 'create_note', + 'batch_create_notes', + 'update_note', + 'list_note_occurrences', + ) + 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_grafeas_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('grafeas.grafeas_v1.services.grafeas.transports.GrafeasTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.GrafeasTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( +), + quota_project_id="octopus", + ) + + +def test_grafeas_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('grafeas.grafeas_v1.services.grafeas.transports.GrafeasTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.GrafeasTransport() + adc.assert_called_once() + + +def test_grafeas_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) + GrafeasClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.GrafeasGrpcTransport, + transports.GrafeasGrpcAsyncIOTransport, + ], +) +def test_grafeas_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=(), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.GrafeasGrpcTransport, + transports.GrafeasGrpcAsyncIOTransport, + transports.GrafeasRestTransport, + ], +) +def test_grafeas_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.GrafeasGrpcTransport, grpc_helpers), + (transports.GrafeasGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_grafeas_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( + "containeranalysis.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( +), + scopes=["1", "2"], + default_host="containeranalysis.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.GrafeasGrpcTransport, transports.GrafeasGrpcAsyncIOTransport]) +def test_grafeas_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_grafeas_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.GrafeasRestTransport ( + 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_grafeas_host_no_port(transport_name): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='containeranalysis.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'containeranalysis.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://containeranalysis.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_grafeas_host_with_port(transport_name): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='containeranalysis.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'containeranalysis.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://containeranalysis.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_grafeas_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = GrafeasClient( + credentials=creds1, + transport=transport_name, + ) + client2 = GrafeasClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_occurrence._session + session2 = client2.transport.get_occurrence._session + assert session1 != session2 + session1 = client1.transport.list_occurrences._session + session2 = client2.transport.list_occurrences._session + assert session1 != session2 + session1 = client1.transport.delete_occurrence._session + session2 = client2.transport.delete_occurrence._session + assert session1 != session2 + session1 = client1.transport.create_occurrence._session + session2 = client2.transport.create_occurrence._session + assert session1 != session2 + session1 = client1.transport.batch_create_occurrences._session + session2 = client2.transport.batch_create_occurrences._session + assert session1 != session2 + session1 = client1.transport.update_occurrence._session + session2 = client2.transport.update_occurrence._session + assert session1 != session2 + session1 = client1.transport.get_occurrence_note._session + session2 = client2.transport.get_occurrence_note._session + assert session1 != session2 + session1 = client1.transport.get_note._session + session2 = client2.transport.get_note._session + assert session1 != session2 + session1 = client1.transport.list_notes._session + session2 = client2.transport.list_notes._session + assert session1 != session2 + session1 = client1.transport.delete_note._session + session2 = client2.transport.delete_note._session + assert session1 != session2 + session1 = client1.transport.create_note._session + session2 = client2.transport.create_note._session + assert session1 != session2 + session1 = client1.transport.batch_create_notes._session + session2 = client2.transport.batch_create_notes._session + assert session1 != session2 + session1 = client1.transport.update_note._session + session2 = client2.transport.update_note._session + assert session1 != session2 + session1 = client1.transport.list_note_occurrences._session + session2 = client2.transport.list_note_occurrences._session + assert session1 != session2 +def test_grafeas_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.GrafeasGrpcTransport( + 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_grafeas_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.GrafeasGrpcAsyncIOTransport( + 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.GrafeasGrpcTransport, transports.GrafeasGrpcAsyncIOTransport]) +def test_grafeas_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.GrafeasGrpcTransport, transports.GrafeasGrpcAsyncIOTransport]) +def test_grafeas_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_note_path(): + project = "squid" + note = "clam" + expected = "projects/{project}/notes/{note}".format(project=project, note=note, ) + actual = GrafeasClient.note_path(project, note) + assert expected == actual + + +def test_parse_note_path(): + expected = { + "project": "whelk", + "note": "octopus", + } + path = GrafeasClient.note_path(**expected) + + # Check that the path construction is reversible. + actual = GrafeasClient.parse_note_path(path) + assert expected == actual + +def test_occurrence_path(): + project = "oyster" + occurrence = "nudibranch" + expected = "projects/{project}/occurrences/{occurrence}".format(project=project, occurrence=occurrence, ) + actual = GrafeasClient.occurrence_path(project, occurrence) + assert expected == actual + + +def test_parse_occurrence_path(): + expected = { + "project": "cuttlefish", + "occurrence": "mussel", + } + path = GrafeasClient.occurrence_path(**expected) + + # Check that the path construction is reversible. + actual = GrafeasClient.parse_occurrence_path(path) + assert expected == actual + +def test_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = GrafeasClient.project_path(project) + assert expected == actual + + +def test_parse_project_path(): + expected = { + "project": "nautilus", + } + path = GrafeasClient.project_path(**expected) + + # Check that the path construction is reversible. + actual = GrafeasClient.parse_project_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "scallop" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = GrafeasClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "abalone", + } + path = GrafeasClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = GrafeasClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "squid" + expected = "folders/{folder}".format(folder=folder, ) + actual = GrafeasClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + path = GrafeasClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = GrafeasClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "whelk" + expected = "organizations/{organization}".format(organization=organization, ) + actual = GrafeasClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + path = GrafeasClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = GrafeasClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "oyster" + expected = "projects/{project}".format(project=project, ) + actual = GrafeasClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + path = GrafeasClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = GrafeasClient.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 = GrafeasClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "winkle", + "location": "nautilus", + } + path = GrafeasClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = GrafeasClient.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.GrafeasTransport, '_prep_wrapped_messages') as prep: + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.GrafeasTransport, '_prep_wrapped_messages') as prep: + transport_class = GrafeasClient.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 = GrafeasClient( + 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 = GrafeasAsyncClient( + 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 = GrafeasClient( + 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 = GrafeasClient( + 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", [ + (GrafeasClient, transports.GrafeasGrpcTransport), + (GrafeasAsyncClient, transports.GrafeasGrpcAsyncIOTransport), +]) +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 677f56373df451268e446e6568dae8c0d4993916 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Thu, 12 Dec 2024 18:56:08 +0000 Subject: [PATCH 2/4] update post processing for grafeas --- .../unique-grafeas-client.yaml | 29 ++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/scripts/client-post-processing/unique-grafeas-client.yaml b/scripts/client-post-processing/unique-grafeas-client.yaml index 7e4a3403eec4..6c9a62a03ad6 100644 --- a/scripts/client-post-processing/unique-grafeas-client.yaml +++ b/scripts/client-post-processing/unique-grafeas-client.yaml @@ -1515,7 +1515,7 @@ replacements: \ str: The universe domain used by the client instance. \ """ \ return self._universe_domain\n - after: "}" + after: "}\n" count: 1 - paths: [ packages/grafeas/grafeas/grafeas_v1/services/grafeas/client.py @@ -1608,6 +1608,10 @@ replacements: \ # 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\( @@ -1669,6 +1673,29 @@ replacements: \ 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 `grafeas_v1.GrafeasClient`.", + \ extra=\{ + \ "serviceName": "grafeas.v1.Grafeas", + \ "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": "grafeas.v1.Grafeas", + \ "credentialsType": None, + \ \}, + \ \) after: | \n def __init__( From 7bc3d6211f9918e81b017ddbabd9d02184b12de4 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Thu, 12 Dec 2024 19:04:08 +0000 Subject: [PATCH 3/4] =?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 | 33 - .../v1/MANIFEST.in | 2 - .../v1/README.rst | 49 - .../v1/docs/_static/custom.css | 3 - .../v1/docs/conf.py | 376 - .../v1/docs/index.rst | 7 - .../maps_platform_datasets.rst | 10 - .../mapsplatformdatasets_v1/services_.rst | 6 - .../docs/mapsplatformdatasets_v1/types_.rst | 6 - .../maps/mapsplatformdatasets/__init__.py | 55 - .../mapsplatformdatasets/gapic_version.py | 16 - .../google/maps/mapsplatformdatasets/py.typed | 2 - .../maps/mapsplatformdatasets_v1/__init__.py | 56 - .../gapic_metadata.json | 118 - .../mapsplatformdatasets_v1/gapic_version.py | 16 - .../maps/mapsplatformdatasets_v1/py.typed | 2 - .../services/__init__.py | 15 - .../maps_platform_datasets/__init__.py | 22 - .../maps_platform_datasets/async_client.py | 941 -- .../services/maps_platform_datasets/client.py | 1271 -- .../services/maps_platform_datasets/pagers.py | 307 - .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../maps_platform_datasets/transports/base.py | 254 - .../maps_platform_datasets/transports/grpc.py | 480 - .../transports/grpc_asyncio.py | 552 - .../maps_platform_datasets/transports/rest.py | 1051 -- .../transports/rest_base.py | 336 - .../mapsplatformdatasets_v1/types/__init__.py | 52 - .../types/data_source.py | 97 - .../mapsplatformdatasets_v1/types/dataset.py | 236 - .../types/maps_platform_datasets.py | 265 - .../types/maps_platform_datasets_service.py | 26 - .../v1/mypy.ini | 3 - .../v1/noxfile.py | 280 - ..._platform_datasets_create_dataset_async.py | 52 - ...s_platform_datasets_create_dataset_sync.py | 52 - ..._platform_datasets_delete_dataset_async.py | 50 - ...s_platform_datasets_delete_dataset_sync.py | 50 - ...orm_datasets_fetch_dataset_errors_async.py | 53 - ...form_datasets_fetch_dataset_errors_sync.py | 53 - ...aps_platform_datasets_get_dataset_async.py | 52 - ...maps_platform_datasets_get_dataset_sync.py | 52 - ...s_platform_datasets_list_datasets_async.py | 53 - ...ps_platform_datasets_list_datasets_sync.py | 53 - ..._datasets_update_dataset_metadata_async.py | 51 - ...m_datasets_update_dataset_metadata_sync.py | 51 - ...a_google.maps.mapsplatformdatasets.v1.json | 991 -- .../fixup_mapsplatformdatasets_v1_keywords.py | 181 - .../v1/setup.py | 98 - .../v1/testing/constraints-3.10.txt | 6 - .../v1/testing/constraints-3.11.txt | 6 - .../v1/testing/constraints-3.12.txt | 6 - .../v1/testing/constraints-3.13.txt | 6 - .../v1/testing/constraints-3.7.txt | 10 - .../v1/testing/constraints-3.8.txt | 6 - .../v1/testing/constraints-3.9.txt | 6 - .../v1/tests/__init__.py | 16 - .../v1/tests/unit/__init__.py | 16 - .../v1/tests/unit/gapic/__init__.py | 16 - .../gapic/mapsplatformdatasets_v1/__init__.py | 16 - .../test_maps_platform_datasets.py | 6115 -------- .../google-maps-places/v1/.coveragerc | 13 - owl-bot-staging/google-maps-places/v1/.flake8 | 33 - .../google-maps-places/v1/MANIFEST.in | 2 - .../google-maps-places/v1/README.rst | 49 - .../v1/docs/_static/custom.css | 3 - .../google-maps-places/v1/docs/conf.py | 376 - .../google-maps-places/v1/docs/index.rst | 7 - .../v1/docs/places_v1/places.rst | 6 - .../v1/docs/places_v1/services_.rst | 6 - .../v1/docs/places_v1/types_.rst | 6 - .../v1/google/maps/places/__init__.py | 83 - .../v1/google/maps/places/gapic_version.py | 16 - .../v1/google/maps/places/py.typed | 2 - .../v1/google/maps/places_v1/__init__.py | 84 - .../google/maps/places_v1/gapic_metadata.json | 103 - .../v1/google/maps/places_v1/gapic_version.py | 16 - .../v1/google/maps/places_v1/py.typed | 2 - .../maps/places_v1/services/__init__.py | 15 - .../places_v1/services/places/__init__.py | 22 - .../places_v1/services/places/async_client.py | 724 - .../maps/places_v1/services/places/client.py | 1085 -- .../services/places/transports/README.rst | 9 - .../services/places/transports/__init__.py | 38 - .../services/places/transports/base.py | 210 - .../services/places/transports/grpc.py | 457 - .../places/transports/grpc_asyncio.py | 497 - .../services/places/transports/rest.py | 946 -- .../services/places/transports/rest_base.py | 307 - .../google/maps/places_v1/types/__init__.py | 108 - .../maps/places_v1/types/attribution.py | 65 - .../maps/places_v1/types/content_block.py | 68 - .../places_v1/types/contextual_content.py | 218 - .../maps/places_v1/types/ev_charging.py | 176 - .../maps/places_v1/types/fuel_options.py | 143 - .../google/maps/places_v1/types/geometry.py | 58 - .../v1/google/maps/places_v1/types/photo.py | 69 - .../v1/google/maps/places_v1/types/place.py | 1286 -- .../maps/places_v1/types/places_service.py | 1340 -- .../google/maps/places_v1/types/polyline.py | 62 - .../maps/places_v1/types/price_range.py | 59 - .../google/maps/places_v1/types/reference.py | 60 - .../v1/google/maps/places_v1/types/review.py | 94 - .../maps/places_v1/types/route_modifiers.py | 76 - .../places_v1/types/routing_preference.py | 71 - .../maps/places_v1/types/routing_summary.py | 95 - .../maps/places_v1/types/travel_mode.py | 63 - .../google-maps-places/v1/mypy.ini | 3 - .../google-maps-places/v1/noxfile.py | 280 - ...erated_places_autocomplete_places_async.py | 52 - ...nerated_places_autocomplete_places_sync.py | 52 - ..._generated_places_get_photo_media_async.py | 52 - ...1_generated_places_get_photo_media_sync.py | 52 - ...ces_v1_generated_places_get_place_async.py | 52 - ...aces_v1_generated_places_get_place_sync.py | 52 - ...v1_generated_places_search_nearby_async.py | 55 - ..._v1_generated_places_search_nearby_sync.py | 55 - ...s_v1_generated_places_search_text_async.py | 52 - ...es_v1_generated_places_search_text_sync.py | 52 - ...nippet_metadata_google.maps.places.v1.json | 796 - .../v1/scripts/fixup_places_v1_keywords.py | 180 - .../google-maps-places/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 | 7 - .../v1/testing/constraints-3.7.txt | 11 - .../v1/testing/constraints-3.8.txt | 7 - .../v1/testing/constraints-3.9.txt | 7 - .../google-maps-places/v1/tests/__init__.py | 16 - .../v1/tests/unit/__init__.py | 16 - .../v1/tests/unit/gapic/__init__.py | 16 - .../v1/tests/unit/gapic/places_v1/__init__.py | 16 - .../tests/unit/gapic/places_v1/test_places.py | 4467 ------ .../v1/.coveragerc | 13 - .../google-maps-routeoptimization/v1/.flake8 | 33 - .../v1/MANIFEST.in | 2 - .../v1/README.rst | 49 - .../v1/docs/_static/custom.css | 3 - .../v1/docs/conf.py | 376 - .../v1/docs/index.rst | 7 - .../route_optimization.rst | 6 - .../docs/routeoptimization_v1/services_.rst | 6 - .../v1/docs/routeoptimization_v1/types_.rst | 6 - .../google/maps/routeoptimization/__init__.py | 81 - .../maps/routeoptimization/gapic_version.py | 16 - .../v1/google/maps/routeoptimization/py.typed | 2 - .../maps/routeoptimization_v1/__init__.py | 82 - .../routeoptimization_v1/gapic_metadata.json | 58 - .../routeoptimization_v1/gapic_version.py | 16 - .../google/maps/routeoptimization_v1/py.typed | 2 - .../routeoptimization_v1/services/__init__.py | 15 - .../services/route_optimization/__init__.py | 22 - .../route_optimization/async_client.py | 576 - .../services/route_optimization/client.py | 905 -- .../route_optimization/transports/README.rst | 9 - .../route_optimization/transports/__init__.py | 38 - .../route_optimization/transports/base.py | 198 - .../route_optimization/transports/grpc.py | 471 - .../transports/grpc_asyncio.py | 510 - .../route_optimization/transports/rest.py | 692 - .../transports/rest_base.py | 221 - .../routeoptimization_v1/types/__init__.py | 74 - .../types/route_optimization_service.py | 3776 ----- .../google-maps-routeoptimization/v1/mypy.ini | 3 - .../v1/noxfile.py | 280 - ...optimization_batch_optimize_tours_async.py | 63 - ..._optimization_batch_optimize_tours_sync.py | 63 - ...route_optimization_optimize_tours_async.py | 52 - ..._route_optimization_optimize_tours_sync.py | 52 - ...data_google.maps.routeoptimization.v1.json | 321 - .../fixup_routeoptimization_v1_keywords.py | 177 - .../google-maps-routeoptimization/v1/setup.py | 98 - .../v1/testing/constraints-3.10.txt | 6 - .../v1/testing/constraints-3.11.txt | 6 - .../v1/testing/constraints-3.12.txt | 6 - .../v1/testing/constraints-3.13.txt | 6 - .../v1/testing/constraints-3.7.txt | 10 - .../v1/testing/constraints-3.8.txt | 6 - .../v1/testing/constraints-3.9.txt | 6 - .../v1/tests/__init__.py | 16 - .../v1/tests/unit/__init__.py | 16 - .../v1/tests/unit/gapic/__init__.py | 16 - .../gapic/routeoptimization_v1/__init__.py | 16 - .../test_route_optimization.py | 2698 ---- .../google-maps-routing/v2/.coveragerc | 13 - .../google-maps-routing/v2/.flake8 | 33 - .../google-maps-routing/v2/MANIFEST.in | 2 - .../google-maps-routing/v2/README.rst | 49 - .../v2/docs/_static/custom.css | 3 - .../google-maps-routing/v2/docs/conf.py | 376 - .../google-maps-routing/v2/docs/index.rst | 7 - .../v2/docs/routing_v2/routes.rst | 6 - .../v2/docs/routing_v2/services_.rst | 6 - .../v2/docs/routing_v2/types_.rst | 6 - .../v2/google/maps/routing/__init__.py | 115 - .../v2/google/maps/routing/gapic_version.py | 16 - .../v2/google/maps/routing/py.typed | 2 - .../v2/google/maps/routing_v2/__init__.py | 116 - .../maps/routing_v2/gapic_metadata.json | 58 - .../google/maps/routing_v2/gapic_version.py | 16 - .../v2/google/maps/routing_v2/py.typed | 2 - .../maps/routing_v2/services/__init__.py | 15 - .../routing_v2/services/routes/__init__.py | 22 - .../services/routes/async_client.py | 486 - .../maps/routing_v2/services/routes/client.py | 813 -- .../services/routes/transports/README.rst | 9 - .../services/routes/transports/__init__.py | 38 - .../services/routes/transports/base.py | 167 - .../services/routes/transports/grpc.py | 446 - .../routes/transports/grpc_asyncio.py | 471 - .../services/routes/transports/rest.py | 465 - .../services/routes/transports/rest_base.py | 185 - .../google/maps/routing_v2/types/__init__.py | 154 - .../maps/routing_v2/types/fallback_info.py | 105 - .../routing_v2/types/geocoding_results.py | 127 - .../maps/routing_v2/types/localized_time.py | 58 - .../google/maps/routing_v2/types/location.py | 63 - .../google/maps/routing_v2/types/maneuver.py | 103 - .../types/navigation_instruction.py | 58 - .../google/maps/routing_v2/types/polyline.py | 113 - .../maps/routing_v2/types/polyline_details.py | 150 - .../v2/google/maps/routing_v2/types/route.py | 799 - .../maps/routing_v2/types/route_label.py | 62 - .../maps/routing_v2/types/route_modifiers.py | 98 - .../routing_v2/types/route_travel_mode.py | 63 - .../maps/routing_v2/types/routes_service.py | 748 - .../routing_v2/types/routing_preference.py | 71 - .../types/speed_reading_interval.py | 92 - .../google/maps/routing_v2/types/toll_info.py | 57 - .../maps/routing_v2/types/toll_passes.py | 376 - .../maps/routing_v2/types/traffic_model.py | 64 - .../google/maps/routing_v2/types/transit.py | 259 - .../routing_v2/types/transit_preferences.py | 97 - .../v2/google/maps/routing_v2/types/units.py | 49 - .../routing_v2/types/vehicle_emission_type.py | 56 - .../maps/routing_v2/types/vehicle_info.py | 51 - .../google/maps/routing_v2/types/waypoint.py | 126 - .../google-maps-routing/v2/mypy.ini | 3 - .../google-maps-routing/v2/noxfile.py | 280 - ...rated_routes_compute_route_matrix_async.py | 52 - ...erated_routes_compute_route_matrix_sync.py | 52 - ...2_generated_routes_compute_routes_async.py | 51 - ...v2_generated_routes_compute_routes_sync.py | 51 - ...ippet_metadata_google.maps.routing.v2.json | 321 - .../v2/scripts/fixup_routing_v2_keywords.py | 177 - .../google-maps-routing/v2/setup.py | 99 - .../v2/testing/constraints-3.10.txt | 7 - .../v2/testing/constraints-3.11.txt | 7 - .../v2/testing/constraints-3.12.txt | 7 - .../v2/testing/constraints-3.13.txt | 7 - .../v2/testing/constraints-3.7.txt | 11 - .../v2/testing/constraints-3.8.txt | 7 - .../v2/testing/constraints-3.9.txt | 7 - .../google-maps-routing/v2/tests/__init__.py | 16 - .../v2/tests/unit/__init__.py | 16 - .../v2/tests/unit/gapic/__init__.py | 16 - .../tests/unit/gapic/routing_v2/__init__.py | 16 - .../unit/gapic/routing_v2/test_routes.py | 2336 --- .../google-maps-solar/v1/.coveragerc | 13 - owl-bot-staging/google-maps-solar/v1/.flake8 | 33 - .../google-maps-solar/v1/MANIFEST.in | 2 - .../google-maps-solar/v1/README.rst | 49 - .../v1/docs/_static/custom.css | 3 - .../google-maps-solar/v1/docs/conf.py | 376 - .../google-maps-solar/v1/docs/index.rst | 7 - .../v1/docs/solar_v1/services_.rst | 6 - .../v1/docs/solar_v1/solar.rst | 6 - .../v1/docs/solar_v1/types_.rst | 6 - .../v1/google/maps/solar/__init__.py | 69 - .../v1/google/maps/solar/gapic_version.py | 16 - .../v1/google/maps/solar/py.typed | 2 - .../v1/google/maps/solar_v1/__init__.py | 70 - .../google/maps/solar_v1/gapic_metadata.json | 73 - .../v1/google/maps/solar_v1/gapic_version.py | 16 - .../v1/google/maps/solar_v1/py.typed | 2 - .../google/maps/solar_v1/services/__init__.py | 15 - .../maps/solar_v1/services/solar/__init__.py | 22 - .../solar_v1/services/solar/async_client.py | 549 - .../maps/solar_v1/services/solar/client.py | 876 -- .../services/solar/transports/README.rst | 9 - .../services/solar/transports/__init__.py | 38 - .../services/solar/transports/base.py | 210 - .../services/solar/transports/grpc.py | 404 - .../services/solar/transports/grpc_asyncio.py | 461 - .../services/solar/transports/rest.py | 694 - .../services/solar/transports/rest_base.py | 203 - .../v1/google/maps/solar_v1/types/__init__.py | 62 - .../maps/solar_v1/types/solar_service.py | 1306 -- owl-bot-staging/google-maps-solar/v1/mypy.ini | 3 - .../google-maps-solar/v1/noxfile.py | 280 - ...snippet_metadata_google.maps.solar.v1.json | 474 - ...ar_find_closest_building_insights_async.py | 51 - ...lar_find_closest_building_insights_sync.py | 51 - ...1_generated_solar_get_data_layers_async.py | 52 - ...v1_generated_solar_get_data_layers_sync.py | 52 - ...r_v1_generated_solar_get_geo_tiff_async.py | 52 - ...ar_v1_generated_solar_get_geo_tiff_sync.py | 52 - .../v1/scripts/fixup_solar_v1_keywords.py | 178 - owl-bot-staging/google-maps-solar/v1/setup.py | 98 - .../v1/testing/constraints-3.10.txt | 6 - .../v1/testing/constraints-3.11.txt | 6 - .../v1/testing/constraints-3.12.txt | 6 - .../v1/testing/constraints-3.13.txt | 6 - .../v1/testing/constraints-3.7.txt | 10 - .../v1/testing/constraints-3.8.txt | 6 - .../v1/testing/constraints-3.9.txt | 6 - .../google-maps-solar/v1/tests/__init__.py | 16 - .../v1/tests/unit/__init__.py | 16 - .../v1/tests/unit/gapic/__init__.py | 16 - .../v1/tests/unit/gapic/solar_v1/__init__.py | 16 - .../tests/unit/gapic/solar_v1/test_solar.py | 2872 ---- .../v1beta/.coveragerc | 13 - .../v1beta/.flake8 | 33 - .../v1beta/MANIFEST.in | 2 - .../v1beta/README.rst | 49 - .../v1beta/docs/_static/custom.css | 3 - .../v1beta/docs/conf.py | 376 - .../v1beta/docs/index.rst | 7 - .../account_issue_service.rst | 10 - .../account_tax_service.rst | 10 - .../accounts_service.rst | 10 - .../autofeed_settings_service.rst | 6 - .../business_identity_service.rst | 6 - .../business_info_service.rst | 6 - .../email_preferences_service.rst | 6 - .../homepage_service.rst | 6 - .../online_return_policy_service.rst | 10 - .../programs_service.rst | 10 - .../regions_service.rst | 10 - .../merchant_accounts_v1beta/services_.rst | 20 - .../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 - .../shopping/merchant_accounts/__init__.py | 271 - .../merchant_accounts/gapic_version.py | 16 - .../shopping/merchant_accounts/py.typed | 2 - .../merchant_accounts_v1beta/__init__.py | 272 - .../gapic_metadata.json | 969 -- .../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 | 381 - .../services/account_issue_service/client.py | 725 - .../services/account_issue_service/pagers.py | 166 - .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../account_issue_service/transports/base.py | 154 - .../account_issue_service/transports/grpc.py | 348 - .../transports/grpc_asyncio.py | 368 - .../account_issue_service/transports/rest.py | 326 - .../transports/rest_base.py | 128 - .../services/account_tax_service/__init__.py | 22 - .../account_tax_service/async_client.py | 616 - .../services/account_tax_service/client.py | 949 -- .../services/account_tax_service/pagers.py | 166 - .../account_tax_service/transports/README.rst | 9 - .../transports/__init__.py | 38 - .../account_tax_service/transports/base.py | 183 - .../account_tax_service/transports/grpc.py | 408 - .../transports/grpc_asyncio.py | 438 - .../account_tax_service/transports/rest.py | 648 - .../transports/rest_base.py | 213 - .../services/accounts_service/__init__.py | 22 - .../services/accounts_service/async_client.py | 886 -- .../services/accounts_service/client.py | 1236 -- .../services/accounts_service/pagers.py | 305 - .../accounts_service/transports/README.rst | 9 - .../accounts_service/transports/__init__.py | 38 - .../accounts_service/transports/base.py | 225 - .../accounts_service/transports/grpc.py | 502 - .../transports/grpc_asyncio.py | 547 - .../accounts_service/transports/rest.py | 1040 -- .../accounts_service/transports/rest_base.py | 326 - .../autofeed_settings_service/__init__.py | 22 - .../autofeed_settings_service/async_client.py | 487 - .../autofeed_settings_service/client.py | 821 -- .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../transports/base.py | 168 - .../transports/grpc.py | 375 - .../transports/grpc_asyncio.py | 400 - .../transports/rest.py | 488 - .../transports/rest_base.py | 175 - .../business_identity_service/__init__.py | 22 - .../business_identity_service/async_client.py | 482 - .../business_identity_service/client.py | 816 -- .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../transports/base.py | 168 - .../transports/grpc.py | 376 - .../transports/grpc_asyncio.py | 401 - .../transports/rest.py | 486 - .../transports/rest_base.py | 175 - .../business_info_service/__init__.py | 22 - .../business_info_service/async_client.py | 482 - .../services/business_info_service/client.py | 816 -- .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../business_info_service/transports/base.py | 168 - .../business_info_service/transports/grpc.py | 374 - .../transports/grpc_asyncio.py | 399 - .../business_info_service/transports/rest.py | 483 - .../transports/rest_base.py | 175 - .../email_preferences_service/__init__.py | 22 - .../email_preferences_service/async_client.py | 505 - .../email_preferences_service/client.py | 839 -- .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../transports/base.py | 168 - .../transports/grpc.py | 391 - .../transports/grpc_asyncio.py | 416 - .../transports/rest.py | 494 - .../transports/rest_base.py | 175 - .../services/homepage_service/__init__.py | 22 - .../services/homepage_service/async_client.py | 652 - .../services/homepage_service/client.py | 986 -- .../homepage_service/transports/README.rst | 9 - .../homepage_service/transports/__init__.py | 38 - .../homepage_service/transports/base.py | 197 - .../homepage_service/transports/grpc.py | 440 - .../transports/grpc_asyncio.py | 475 - .../homepage_service/transports/rest.py | 786 - .../homepage_service/transports/rest_base.py | 270 - .../online_return_policy_service/__init__.py | 22 - .../async_client.py | 495 - .../online_return_policy_service/client.py | 829 -- .../online_return_policy_service/pagers.py | 166 - .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../transports/base.py | 168 - .../transports/grpc.py | 380 - .../transports/grpc_asyncio.py | 405 - .../transports/rest.py | 492 - .../transports/rest_base.py | 165 - .../services/programs_service/__init__.py | 22 - .../services/programs_service/async_client.py | 732 - .../services/programs_service/client.py | 1064 -- .../services/programs_service/pagers.py | 166 - .../programs_service/transports/README.rst | 9 - .../programs_service/transports/__init__.py | 38 - .../programs_service/transports/base.py | 196 - .../programs_service/transports/grpc.py | 438 - .../transports/grpc_asyncio.py | 473 - .../programs_service/transports/rest.py | 825 -- .../programs_service/transports/rest_base.py | 259 - .../services/regions_service/__init__.py | 22 - .../services/regions_service/async_client.py | 838 -- .../services/regions_service/client.py | 1178 -- .../services/regions_service/pagers.py | 166 - .../regions_service/transports/README.rst | 9 - .../regions_service/transports/__init__.py | 38 - .../regions_service/transports/base.py | 211 - .../regions_service/transports/grpc.py | 460 - .../transports/grpc_asyncio.py | 500 - .../regions_service/transports/rest.py | 916 -- .../regions_service/transports/rest_base.py | 297 - .../shipping_settings_service/__init__.py | 22 - .../shipping_settings_service/async_client.py | 456 - .../shipping_settings_service/client.py | 791 - .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../transports/base.py | 168 - .../transports/grpc.py | 376 - .../transports/grpc_asyncio.py | 401 - .../transports/rest.py | 485 - .../transports/rest_base.py | 175 - .../__init__.py | 22 - .../async_client.py | 530 - .../client.py | 882 -- .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../transports/base.py | 168 - .../transports/grpc.py | 376 - .../transports/grpc_asyncio.py | 401 - .../transports/rest.py | 537 - .../transports/rest_base.py | 165 - .../terms_of_service_service/__init__.py | 22 - .../terms_of_service_service/async_client.py | 537 - .../terms_of_service_service/client.py | 880 -- .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../transports/base.py | 183 - .../transports/grpc.py | 404 - .../transports/grpc_asyncio.py | 434 - .../transports/rest.py | 584 - .../transports/rest_base.py | 203 - .../services/user_service/__init__.py | 22 - .../services/user_service/async_client.py | 818 -- .../services/user_service/client.py | 1158 -- .../services/user_service/pagers.py | 166 - .../user_service/transports/README.rst | 9 - .../user_service/transports/__init__.py | 38 - .../services/user_service/transports/base.py | 212 - .../services/user_service/transports/grpc.py | 456 - .../user_service/transports/grpc_asyncio.py | 496 - .../services/user_service/transports/rest.py | 895 -- .../user_service/transports/rest_base.py | 298 - .../types/__init__.py | 248 - .../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/businessidentity.py | 204 - .../types/businessinfo.py | 148 - .../types/customerservice.py | 74 - .../types/emailpreferences.py | 121 - .../types/homepage.py | 139 - .../types/online_return_policy.py | 405 - .../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 | 280 - ...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 - ...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 - ...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 - ...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 - ..._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 | 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 | 7284 ---------- ...fixup_merchant_accounts_v1beta_keywords.py | 220 - .../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 | 7 - .../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 | 2368 --- .../test_account_tax_service.py | 3745 ----- .../test_accounts_service.py | 5584 ------- .../test_autofeed_settings_service.py | 2836 ---- .../test_business_identity_service.py | 2822 ---- .../test_business_info_service.py | 2840 ---- .../test_email_preferences_service.py | 2824 ---- .../test_homepage_service.py | 3903 ----- .../test_online_return_policy_service.py | 3064 ---- .../test_programs_service.py | 4373 ------ .../test_regions_service.py | 5154 ------- .../test_shipping_settings_service.py | 2679 ---- ...erms_of_service_agreement_state_service.py | 2800 ---- .../test_terms_of_service_service.py | 3277 ----- .../test_user_service.py | 5164 ------- .../v1beta/.coveragerc | 13 - .../v1beta/.flake8 | 33 - .../v1beta/MANIFEST.in | 2 - .../v1beta/README.rst | 49 - .../v1beta/docs/_static/custom.css | 3 - .../v1beta/docs/conf.py | 376 - .../v1beta/docs/index.rst | 7 - .../conversion_sources_service.rst | 10 - .../merchant_conversions_v1beta/services_.rst | 6 - .../merchant_conversions_v1beta/types_.rst | 6 - .../shopping/merchant_conversions/__init__.py | 49 - .../merchant_conversions/gapic_version.py | 16 - .../shopping/merchant_conversions/py.typed | 2 - .../merchant_conversions_v1beta/__init__.py | 50 - .../gapic_metadata.json | 118 - .../gapic_version.py | 16 - .../merchant_conversions_v1beta/py.typed | 2 - .../services/__init__.py | 15 - .../conversion_sources_service/__init__.py | 22 - .../async_client.py | 928 -- .../conversion_sources_service/client.py | 1259 -- .../conversion_sources_service/pagers.py | 166 - .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../transports/base.py | 225 - .../transports/grpc.py | 488 - .../transports/grpc_asyncio.py | 533 - .../transports/rest.py | 1067 -- .../transports/rest_base.py | 344 - .../types/__init__.py | 42 - .../types/conversionsources.py | 484 - .../v1beta/mypy.ini | 3 - .../v1beta/noxfile.py | 280 - ..._service_create_conversion_source_async.py | 56 - ...s_service_create_conversion_source_sync.py | 56 - ..._service_delete_conversion_source_async.py | 50 - ...s_service_delete_conversion_source_sync.py | 50 - ...ces_service_get_conversion_source_async.py | 52 - ...rces_service_get_conversion_source_sync.py | 52 - ...s_service_list_conversion_sources_async.py | 53 - ...es_service_list_conversion_sources_sync.py | 53 - ...ervice_undelete_conversion_source_async.py | 52 - ...service_undelete_conversion_source_sync.py | 52 - ..._service_update_conversion_source_async.py | 55 - ...s_service_update_conversion_source_sync.py | 55 - ....shopping.merchant.conversions.v1beta.json | 983 -- ...up_merchant_conversions_v1beta_keywords.py | 181 - .../v1beta/setup.py | 98 - .../v1beta/testing/constraints-3.10.txt | 6 - .../v1beta/testing/constraints-3.11.txt | 6 - .../v1beta/testing/constraints-3.12.txt | 6 - .../v1beta/testing/constraints-3.13.txt | 6 - .../v1beta/testing/constraints-3.7.txt | 10 - .../v1beta/testing/constraints-3.8.txt | 6 - .../v1beta/testing/constraints-3.9.txt | 6 - .../v1beta/tests/__init__.py | 16 - .../v1beta/tests/unit/__init__.py | 16 - .../v1beta/tests/unit/gapic/__init__.py | 16 - .../merchant_conversions_v1beta/__init__.py | 16 - .../test_conversion_sources_service.py | 5664 -------- .../v1beta/.coveragerc | 13 - .../v1beta/.flake8 | 33 - .../v1beta/MANIFEST.in | 2 - .../v1beta/README.rst | 49 - .../v1beta/docs/_static/custom.css | 3 - .../v1beta/docs/conf.py | 376 - .../v1beta/docs/index.rst | 7 - .../data_sources_service.rst | 10 - .../file_uploads_service.rst | 6 - .../merchant_datasources_v1beta/services_.rst | 7 - .../merchant_datasources_v1beta/types_.rst | 6 - .../shopping/merchant_datasources/__init__.py | 65 - .../merchant_datasources/gapic_version.py | 16 - .../shopping/merchant_datasources/py.typed | 2 - .../merchant_datasources_v1beta/__init__.py | 66 - .../gapic_metadata.json | 152 - .../gapic_version.py | 16 - .../merchant_datasources_v1beta/py.typed | 2 - .../services/__init__.py | 15 - .../services/data_sources_service/__init__.py | 22 - .../data_sources_service/async_client.py | 913 -- .../services/data_sources_service/client.py | 1244 -- .../services/data_sources_service/pagers.py | 166 - .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../data_sources_service/transports/base.py | 225 - .../data_sources_service/transports/grpc.py | 493 - .../transports/grpc_asyncio.py | 538 - .../data_sources_service/transports/rest.py | 1016 -- .../transports/rest_base.py | 344 - .../services/file_uploads_service/__init__.py | 22 - .../file_uploads_service/async_client.py | 372 - .../services/file_uploads_service/client.py | 707 - .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../file_uploads_service/transports/base.py | 154 - .../file_uploads_service/transports/grpc.py | 348 - .../transports/grpc_asyncio.py | 368 - .../file_uploads_service/transports/rest.py | 334 - .../transports/rest_base.py | 128 - .../types/__init__.py | 60 - .../types/datasources.py | 351 - .../types/datasourcetypes.py | 372 - .../types/fileinputs.py | 201 - .../types/fileuploads.py | 205 - .../v1beta/mypy.ini | 3 - .../v1beta/noxfile.py | 280 - ...ources_service_create_data_source_async.py | 57 - ...sources_service_create_data_source_sync.py | 57 - ...ources_service_delete_data_source_async.py | 50 - ...sources_service_delete_data_source_sync.py | 50 - ...sources_service_fetch_data_source_async.py | 50 - ..._sources_service_fetch_data_source_sync.py | 50 - ...a_sources_service_get_data_source_async.py | 52 - ...ta_sources_service_get_data_source_sync.py | 52 - ...sources_service_list_data_sources_async.py | 53 - ..._sources_service_list_data_sources_sync.py | 53 - ...ources_service_update_data_source_async.py | 56 - ...sources_service_update_data_source_sync.py | 56 - ...e_uploads_service_get_file_upload_async.py | 52 - ...le_uploads_service_get_file_upload_sync.py | 52 - ....shopping.merchant.datasources.v1beta.json | 1138 -- ...up_merchant_datasources_v1beta_keywords.py | 182 - .../v1beta/setup.py | 98 - .../v1beta/testing/constraints-3.10.txt | 6 - .../v1beta/testing/constraints-3.11.txt | 6 - .../v1beta/testing/constraints-3.12.txt | 6 - .../v1beta/testing/constraints-3.13.txt | 6 - .../v1beta/testing/constraints-3.7.txt | 10 - .../v1beta/testing/constraints-3.8.txt | 6 - .../v1beta/testing/constraints-3.9.txt | 6 - .../v1beta/tests/__init__.py | 16 - .../v1beta/tests/unit/__init__.py | 16 - .../v1beta/tests/unit/gapic/__init__.py | 16 - .../merchant_datasources_v1beta/__init__.py | 16 - .../test_data_sources_service.py | 5650 -------- .../test_file_uploads_service.py | 2121 --- .../v1beta/.coveragerc | 13 - .../v1beta/.flake8 | 33 - .../v1beta/MANIFEST.in | 2 - .../v1beta/README.rst | 49 - .../v1beta/docs/_static/custom.css | 3 - .../v1beta/docs/conf.py | 376 - .../v1beta/docs/index.rst | 7 - .../local_inventory_service.rst | 10 - .../regional_inventory_service.rst | 10 - .../merchant_inventories_v1beta/services_.rst | 7 - .../merchant_inventories_v1beta/types_.rst | 6 - .../shopping/merchant_inventories/__init__.py | 51 - .../merchant_inventories/gapic_version.py | 16 - .../shopping/merchant_inventories/py.typed | 2 - .../merchant_inventories_v1beta/__init__.py | 52 - .../gapic_metadata.json | 137 - .../gapic_version.py | 16 - .../merchant_inventories_v1beta/py.typed | 2 - .../services/__init__.py | 15 - .../local_inventory_service/__init__.py | 22 - .../local_inventory_service/async_client.py | 585 - .../local_inventory_service/client.py | 919 -- .../local_inventory_service/pagers.py | 166 - .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../transports/base.py | 183 - .../transports/grpc.py | 419 - .../transports/grpc_asyncio.py | 449 - .../transports/rest.py | 594 - .../transports/rest_base.py | 213 - .../regional_inventory_service/__init__.py | 22 - .../async_client.py | 591 - .../regional_inventory_service/client.py | 925 -- .../regional_inventory_service/pagers.py | 166 - .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../transports/base.py | 183 - .../transports/grpc.py | 420 - .../transports/grpc_asyncio.py | 450 - .../transports/rest.py | 598 - .../transports/rest_base.py | 213 - .../types/__init__.py | 42 - .../types/localinventory.py | 281 - .../types/regionalinventory.py | 236 - .../v1beta/mypy.ini | 3 - .../v1beta/noxfile.py | 280 - ...ry_service_delete_local_inventory_async.py | 50 - ...ory_service_delete_local_inventory_sync.py | 50 - ...ry_service_insert_local_inventory_async.py | 56 - ...ory_service_insert_local_inventory_sync.py | 56 - ...ry_service_list_local_inventories_async.py | 53 - ...ory_service_list_local_inventories_sync.py | 53 - ...service_delete_regional_inventory_async.py | 50 - ..._service_delete_regional_inventory_sync.py | 50 - ...service_insert_regional_inventory_async.py | 56 - ..._service_insert_regional_inventory_sync.py | 56 - ...service_list_regional_inventories_async.py | 53 - ..._service_list_regional_inventories_sync.py | 53 - ....shopping.merchant.inventories.v1beta.json | 953 -- ...up_merchant_inventories_v1beta_keywords.py | 181 - .../v1beta/setup.py | 99 - .../v1beta/testing/constraints-3.10.txt | 7 - .../v1beta/testing/constraints-3.11.txt | 7 - .../v1beta/testing/constraints-3.12.txt | 7 - .../v1beta/testing/constraints-3.13.txt | 7 - .../v1beta/testing/constraints-3.7.txt | 11 - .../v1beta/testing/constraints-3.8.txt | 7 - .../v1beta/testing/constraints-3.9.txt | 7 - .../v1beta/tests/__init__.py | 16 - .../v1beta/tests/unit/__init__.py | 16 - .../v1beta/tests/unit/gapic/__init__.py | 16 - .../merchant_inventories_v1beta/__init__.py | 16 - .../test_local_inventory_service.py | 3612 ----- .../test_regional_inventory_service.py | 3584 ----- .../v1beta/.coveragerc | 13 - .../v1beta/.flake8 | 33 - .../v1beta/MANIFEST.in | 2 - .../v1beta/README.rst | 49 - .../v1beta/docs/_static/custom.css | 3 - .../v1beta/docs/conf.py | 376 - .../v1beta/docs/index.rst | 7 - .../lfp_inventory_service.rst | 6 - .../merchant_lfp_v1beta/lfp_sale_service.rst | 6 - .../merchant_lfp_v1beta/lfp_store_service.rst | 10 - .../docs/merchant_lfp_v1beta/services_.rst | 8 - .../docs/merchant_lfp_v1beta/types_.rst | 6 - .../google/shopping/merchant_lfp/__init__.py | 55 - .../shopping/merchant_lfp/gapic_version.py | 16 - .../google/shopping/merchant_lfp/py.typed | 2 - .../shopping/merchant_lfp_v1beta/__init__.py | 56 - .../merchant_lfp_v1beta/gapic_metadata.json | 156 - .../merchant_lfp_v1beta/gapic_version.py | 16 - .../shopping/merchant_lfp_v1beta/py.typed | 2 - .../merchant_lfp_v1beta/services/__init__.py | 15 - .../lfp_inventory_service/__init__.py | 22 - .../lfp_inventory_service/async_client.py | 357 - .../services/lfp_inventory_service/client.py | 693 - .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../lfp_inventory_service/transports/base.py | 154 - .../lfp_inventory_service/transports/grpc.py | 351 - .../transports/grpc_asyncio.py | 371 - .../lfp_inventory_service/transports/rest.py | 331 - .../transports/rest_base.py | 138 - .../services/lfp_sale_service/__init__.py | 22 - .../services/lfp_sale_service/async_client.py | 357 - .../services/lfp_sale_service/client.py | 693 - .../lfp_sale_service/transports/README.rst | 9 - .../lfp_sale_service/transports/__init__.py | 38 - .../lfp_sale_service/transports/base.py | 154 - .../lfp_sale_service/transports/grpc.py | 349 - .../transports/grpc_asyncio.py | 369 - .../lfp_sale_service/transports/rest.py | 332 - .../lfp_sale_service/transports/rest_base.py | 138 - .../services/lfp_store_service/__init__.py | 22 - .../lfp_store_service/async_client.py | 714 - .../services/lfp_store_service/client.py | 1046 -- .../services/lfp_store_service/pagers.py | 166 - .../lfp_store_service/transports/README.rst | 9 - .../lfp_store_service/transports/__init__.py | 38 - .../lfp_store_service/transports/base.py | 197 - .../lfp_store_service/transports/grpc.py | 431 - .../transports/grpc_asyncio.py | 466 - .../lfp_store_service/transports/rest.py | 756 - .../lfp_store_service/transports/rest_base.py | 250 - .../merchant_lfp_v1beta/types/__init__.py | 44 - .../merchant_lfp_v1beta/types/lfpinventory.py | 200 - .../merchant_lfp_v1beta/types/lfpsale.py | 165 - .../merchant_lfp_v1beta/types/lfpstore.py | 308 - .../v1beta/mypy.ini | 3 - .../v1beta/noxfile.py | 280 - ...tory_service_insert_lfp_inventory_async.py | 61 - ...ntory_service_insert_lfp_inventory_sync.py | 61 - ..._lfp_sale_service_insert_lfp_sale_async.py | 62 - ...d_lfp_sale_service_insert_lfp_sale_sync.py | 62 - ...fp_store_service_delete_lfp_store_async.py | 50 - ...lfp_store_service_delete_lfp_store_sync.py | 50 - ...d_lfp_store_service_get_lfp_store_async.py | 52 - ...ed_lfp_store_service_get_lfp_store_sync.py | 52 - ...fp_store_service_insert_lfp_store_async.py | 58 - ...lfp_store_service_insert_lfp_store_sync.py | 58 - ...lfp_store_service_list_lfp_stores_async.py | 54 - ..._lfp_store_service_list_lfp_stores_sync.py | 54 - ...a_google.shopping.merchant.lfp.v1beta.json | 967 -- .../fixup_merchant_lfp_v1beta_keywords.py | 181 - .../v1beta/setup.py | 99 - .../v1beta/testing/constraints-3.10.txt | 7 - .../v1beta/testing/constraints-3.11.txt | 7 - .../v1beta/testing/constraints-3.12.txt | 7 - .../v1beta/testing/constraints-3.13.txt | 7 - .../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 - .../gapic/merchant_lfp_v1beta/__init__.py | 16 - .../test_lfp_inventory_service.py | 2095 --- .../test_lfp_sale_service.py | 2077 --- .../test_lfp_store_service.py | 4514 ------ .../v1beta/.coveragerc | 13 - .../v1beta/.flake8 | 33 - .../v1beta/MANIFEST.in | 2 - .../v1beta/README.rst | 49 - .../v1beta/docs/_static/custom.css | 3 - .../v1beta/docs/conf.py | 376 - .../v1beta/docs/index.rst | 7 - .../notifications_api_service.rst | 10 - .../services_.rst | 6 - .../merchant_notifications_v1beta/types_.rst | 6 - .../merchant_notifications/__init__.py | 49 - .../merchant_notifications/gapic_version.py | 16 - .../shopping/merchant_notifications/py.typed | 2 - .../merchant_notifications_v1beta/__init__.py | 50 - .../gapic_metadata.json | 103 - .../gapic_version.py | 16 - .../merchant_notifications_v1beta/py.typed | 2 - .../services/__init__.py | 15 - .../notifications_api_service/__init__.py | 22 - .../notifications_api_service/async_client.py | 836 -- .../notifications_api_service/client.py | 1167 -- .../notifications_api_service/pagers.py | 166 - .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../transports/base.py | 211 - .../transports/grpc.py | 475 - .../transports/grpc_asyncio.py | 515 - .../transports/rest.py | 909 -- .../transports/rest_base.py | 297 - .../types/__init__.py | 42 - .../types/notificationsapi.py | 424 - .../v1beta/mypy.ini | 3 - .../v1beta/noxfile.py | 280 - ..._create_notification_subscription_async.py | 56 - ...e_create_notification_subscription_sync.py | 56 - ..._delete_notification_subscription_async.py | 50 - ...e_delete_notification_subscription_sync.py | 50 - ...ice_get_notification_subscription_async.py | 52 - ...vice_get_notification_subscription_sync.py | 52 - ...e_list_notification_subscriptions_async.py | 53 - ...ce_list_notification_subscriptions_sync.py | 53 - ..._update_notification_subscription_async.py | 55 - ...e_update_notification_subscription_sync.py | 55 - ...hopping.merchant.notifications.v1beta.json | 830 -- ..._merchant_notifications_v1beta_keywords.py | 180 - .../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 | 7 - .../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_notifications_v1beta/__init__.py | 16 - .../test_notifications_api_service.py | 5136 ------- .../v1beta/.coveragerc | 13 - .../v1beta/.flake8 | 33 - .../v1beta/MANIFEST.in | 2 - .../v1beta/README.rst | 49 - .../v1beta/docs/_static/custom.css | 3 - .../v1beta/docs/conf.py | 376 - .../v1beta/docs/index.rst | 7 - .../promotions_service.rst | 10 - .../merchant_promotions_v1beta/services_.rst | 6 - .../merchant_promotions_v1beta/types_.rst | 6 - .../shopping/merchant_promotions/__init__.py | 51 - .../merchant_promotions/gapic_version.py | 16 - .../shopping/merchant_promotions/py.typed | 2 - .../merchant_promotions_v1beta/__init__.py | 52 - .../gapic_metadata.json | 73 - .../gapic_version.py | 16 - .../merchant_promotions_v1beta/py.typed | 2 - .../services/__init__.py | 15 - .../services/promotions_service/__init__.py | 22 - .../promotions_service/async_client.py | 612 - .../services/promotions_service/client.py | 946 -- .../services/promotions_service/pagers.py | 166 - .../promotions_service/transports/README.rst | 9 - .../promotions_service/transports/__init__.py | 38 - .../promotions_service/transports/base.py | 182 - .../promotions_service/transports/grpc.py | 411 - .../transports/grpc_asyncio.py | 441 - .../promotions_service/transports/rest.py | 657 - .../transports/rest_base.py | 212 - .../types/__init__.py | 46 - .../types/promotions.py | 277 - .../types/promotions_common.py | 671 - .../v1beta/mypy.ini | 3 - .../v1beta/noxfile.py | 280 - ..._promotions_service_get_promotion_async.py | 52 - ...d_promotions_service_get_promotion_sync.py | 52 - ...omotions_service_insert_promotion_async.py | 60 - ...romotions_service_insert_promotion_sync.py | 60 - ...romotions_service_list_promotions_async.py | 53 - ...promotions_service_list_promotions_sync.py | 53 - ...e.shopping.merchant.promotions.v1beta.json | 490 - ...xup_merchant_promotions_v1beta_keywords.py | 178 - .../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 | 7 - .../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_promotions_v1beta/__init__.py | 16 - .../test_promotions_service.py | 3614 ----- .../v1beta/.coveragerc | 13 - .../v1beta/.flake8 | 33 - .../v1beta/MANIFEST.in | 2 - .../v1beta/README.rst | 49 - .../v1beta/docs/_static/custom.css | 3 - .../v1beta/docs/conf.py | 376 - .../v1beta/docs/index.rst | 7 - .../merchant_quota_v1beta/quota_service.rst | 10 - .../docs/merchant_quota_v1beta/services_.rst | 6 - .../docs/merchant_quota_v1beta/types_.rst | 6 - .../shopping/merchant_quota/__init__.py | 35 - .../shopping/merchant_quota/gapic_version.py | 16 - .../google/shopping/merchant_quota/py.typed | 2 - .../merchant_quota_v1beta/__init__.py | 36 - .../merchant_quota_v1beta/gapic_metadata.json | 43 - .../merchant_quota_v1beta/gapic_version.py | 16 - .../shopping/merchant_quota_v1beta/py.typed | 2 - .../services/__init__.py | 15 - .../services/quota_service/__init__.py | 22 - .../services/quota_service/async_client.py | 384 - .../services/quota_service/client.py | 719 - .../services/quota_service/pagers.py | 166 - .../quota_service/transports/README.rst | 9 - .../quota_service/transports/__init__.py | 38 - .../services/quota_service/transports/base.py | 154 - .../services/quota_service/transports/grpc.py | 349 - .../quota_service/transports/grpc_asyncio.py | 369 - .../services/quota_service/transports/rest.py | 330 - .../quota_service/transports/rest_base.py | 128 - .../merchant_quota_v1beta/types/__init__.py | 28 - .../merchant_quota_v1beta/types/quota.py | 184 - .../v1beta/mypy.ini | 3 - .../v1beta/noxfile.py | 280 - ...d_quota_service_list_quota_groups_async.py | 53 - ...ed_quota_service_list_quota_groups_sync.py | 53 - ...google.shopping.merchant.quota.v1beta.json | 176 - .../fixup_merchant_quota_v1beta_keywords.py | 176 - .../v1beta/setup.py | 98 - .../v1beta/testing/constraints-3.10.txt | 6 - .../v1beta/testing/constraints-3.11.txt | 6 - .../v1beta/testing/constraints-3.12.txt | 6 - .../v1beta/testing/constraints-3.13.txt | 6 - .../v1beta/testing/constraints-3.7.txt | 10 - .../v1beta/testing/constraints-3.8.txt | 6 - .../v1beta/testing/constraints-3.9.txt | 6 - .../v1beta/tests/__init__.py | 16 - .../v1beta/tests/unit/__init__.py | 16 - .../v1beta/tests/unit/gapic/__init__.py | 16 - .../gapic/merchant_quota_v1beta/__init__.py | 16 - .../test_quota_service.py | 2347 --- .../v1beta/.coveragerc | 13 - .../v1beta/.flake8 | 33 - .../v1beta/MANIFEST.in | 2 - .../v1beta/README.rst | 49 - .../v1beta/docs/_static/custom.css | 3 - .../v1beta/docs/conf.py | 376 - .../v1beta/docs/index.rst | 7 - .../report_service.rst | 10 - .../merchant_reports_v1beta/services_.rst | 6 - .../docs/merchant_reports_v1beta/types_.rst | 6 - .../shopping/merchant_reports/__init__.py | 63 - .../merchant_reports/gapic_version.py | 16 - .../google/shopping/merchant_reports/py.typed | 2 - .../merchant_reports_v1beta/__init__.py | 64 - .../gapic_metadata.json | 43 - .../merchant_reports_v1beta/gapic_version.py | 16 - .../shopping/merchant_reports_v1beta/py.typed | 2 - .../services/__init__.py | 15 - .../services/report_service/__init__.py | 22 - .../services/report_service/async_client.py | 385 - .../services/report_service/client.py | 711 - .../services/report_service/pagers.py | 166 - .../report_service/transports/README.rst | 9 - .../report_service/transports/__init__.py | 38 - .../report_service/transports/base.py | 154 - .../report_service/transports/grpc.py | 352 - .../report_service/transports/grpc_asyncio.py | 372 - .../report_service/transports/rest.py | 333 - .../report_service/transports/rest_base.py | 138 - .../merchant_reports_v1beta/types/__init__.py | 56 - .../merchant_reports_v1beta/types/reports.py | 2521 ---- .../v1beta/mypy.ini | 3 - .../v1beta/noxfile.py | 280 - ...a_generated_report_service_search_async.py | 54 - ...ta_generated_report_service_search_sync.py | 54 - ...ogle.shopping.merchant.reports.v1beta.json | 176 - .../fixup_merchant_reports_v1beta_keywords.py | 176 - .../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 | 7 - .../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 - .../gapic/merchant_reports_v1beta/__init__.py | 16 - .../test_report_service.py | 2333 --- owl-bot-staging/grafeas/v1/.coveragerc | 13 - owl-bot-staging/grafeas/v1/.flake8 | 33 - owl-bot-staging/grafeas/v1/MANIFEST.in | 2 - owl-bot-staging/grafeas/v1/README.rst | 49 - .../grafeas/v1/docs/_static/custom.css | 3 - owl-bot-staging/grafeas/v1/docs/conf.py | 376 - .../grafeas/v1/docs/grafeas_v1/grafeas.rst | 10 - .../grafeas/v1/docs/grafeas_v1/services_.rst | 6 - .../grafeas/v1/docs/grafeas_v1/types_.rst | 6 - owl-bot-staging/grafeas/v1/docs/index.rst | 7 - .../grafeas/v1/grafeas/grafeas/__init__.py | 211 - .../v1/grafeas/grafeas/gapic_version.py | 16 - .../grafeas/v1/grafeas/grafeas/py.typed | 2 - .../grafeas/v1/grafeas/grafeas_v1/__init__.py | 212 - .../v1/grafeas/grafeas_v1/gapic_metadata.json | 238 - .../v1/grafeas/grafeas_v1/gapic_version.py | 16 - .../grafeas/v1/grafeas/grafeas_v1/py.typed | 2 - .../grafeas/grafeas_v1/services/__init__.py | 15 - .../grafeas_v1/services/grafeas/__init__.py | 22 - .../services/grafeas/async_client.py | 1886 --- .../grafeas_v1/services/grafeas/client.py | 2225 --- .../grafeas_v1/services/grafeas/pagers.py | 444 - .../services/grafeas/transports/README.rst | 9 - .../services/grafeas/transports/__init__.py | 38 - .../services/grafeas/transports/base.py | 416 - .../services/grafeas/transports/grpc.py | 708 - .../grafeas/transports/grpc_asyncio.py | 873 -- .../services/grafeas/transports/rest.py | 2241 --- .../services/grafeas/transports/rest_base.py | 732 - .../v1/grafeas/grafeas_v1/types/__init__.py | 244 - .../grafeas/grafeas_v1/types/attestation.py | 148 - .../v1/grafeas/grafeas_v1/types/build.py | 115 - .../v1/grafeas/grafeas_v1/types/common.py | 295 - .../v1/grafeas/grafeas_v1/types/compliance.py | 215 - .../v1/grafeas/grafeas_v1/types/cvss.py | 464 - .../v1/grafeas/grafeas_v1/types/deployment.py | 125 - .../v1/grafeas/grafeas_v1/types/discovery.py | 281 - .../grafeas_v1/types/dsse_attestation.py | 102 - .../v1/grafeas/grafeas_v1/types/grafeas.py | 921 -- .../v1/grafeas/grafeas_v1/types/image.py | 158 - .../grafeas_v1/types/intoto_provenance.py | 248 - .../grafeas_v1/types/intoto_statement.py | 353 - .../v1/grafeas/grafeas_v1/types/package.py | 378 - .../v1/grafeas/grafeas_v1/types/provenance.py | 597 - .../v1/grafeas/grafeas_v1/types/sbom.py | 171 - .../v1/grafeas/grafeas_v1/types/severity.py | 56 - .../grafeas_v1/types/slsa_provenance.py | 258 - .../types/slsa_provenance_zero_two.py | 242 - .../v1/grafeas/grafeas_v1/types/upgrade.py | 266 - .../v1/grafeas/grafeas_v1/types/vex.py | 384 - .../grafeas/grafeas_v1/types/vulnerability.py | 594 - owl-bot-staging/grafeas/v1/mypy.ini | 3 - owl-bot-staging/grafeas/v1/noxfile.py | 280 - ...erated_grafeas_batch_create_notes_async.py | 52 - ...nerated_grafeas_batch_create_notes_sync.py | 52 - ..._grafeas_batch_create_occurrences_async.py | 52 - ...d_grafeas_batch_create_occurrences_sync.py | 52 - ..._v1_generated_grafeas_create_note_async.py | 53 - ...s_v1_generated_grafeas_create_note_sync.py | 53 - ...nerated_grafeas_create_occurrence_async.py | 52 - ...enerated_grafeas_create_occurrence_sync.py | 52 - ..._v1_generated_grafeas_delete_note_async.py | 50 - ...s_v1_generated_grafeas_delete_note_sync.py | 50 - ...nerated_grafeas_delete_occurrence_async.py | 50 - ...enerated_grafeas_delete_occurrence_sync.py | 50 - ...sis_v1_generated_grafeas_get_note_async.py | 52 - ...ysis_v1_generated_grafeas_get_note_sync.py | 52 - ..._generated_grafeas_get_occurrence_async.py | 52 - ...rated_grafeas_get_occurrence_note_async.py | 52 - ...erated_grafeas_get_occurrence_note_sync.py | 52 - ...1_generated_grafeas_get_occurrence_sync.py | 52 - ...ted_grafeas_list_note_occurrences_async.py | 53 - ...ated_grafeas_list_note_occurrences_sync.py | 53 - ...s_v1_generated_grafeas_list_notes_async.py | 53 - ...is_v1_generated_grafeas_list_notes_sync.py | 53 - ...enerated_grafeas_list_occurrences_async.py | 53 - ...generated_grafeas_list_occurrences_sync.py | 53 - ..._v1_generated_grafeas_update_note_async.py | 52 - ...s_v1_generated_grafeas_update_note_sync.py | 52 - ...nerated_grafeas_update_occurrence_async.py | 52 - ...enerated_grafeas_update_occurrence_sync.py | 52 - .../snippet_metadata_grafeas.v1.json | 2353 --- .../v1/scripts/fixup_grafeas_v1_keywords.py | 189 - owl-bot-staging/grafeas/v1/setup.py | 98 - .../grafeas/v1/testing/constraints-3.10.txt | 6 - .../grafeas/v1/testing/constraints-3.11.txt | 6 - .../grafeas/v1/testing/constraints-3.12.txt | 6 - .../grafeas/v1/testing/constraints-3.13.txt | 6 - .../grafeas/v1/testing/constraints-3.7.txt | 10 - .../grafeas/v1/testing/constraints-3.8.txt | 6 - .../grafeas/v1/testing/constraints-3.9.txt | 6 - owl-bot-staging/grafeas/v1/tests/__init__.py | 16 - .../grafeas/v1/tests/unit/__init__.py | 16 - .../grafeas/v1/tests/unit/gapic/__init__.py | 16 - .../tests/unit/gapic/grafeas_v1/__init__.py | 16 - .../unit/gapic/grafeas_v1/test_grafeas.py | 11993 ---------------- .../mapsplatformdatasets/gapic_version.py | 2 +- .../mapsplatformdatasets_v1/gapic_version.py | 2 +- .../maps_platform_datasets/async_client.py | 80 +- .../services/maps_platform_datasets/client.py | 85 +- .../services/maps_platform_datasets/pagers.py | 32 +- .../maps_platform_datasets/transports/grpc.py | 102 +- .../transports/grpc_asyncio.py | 101 +- .../maps_platform_datasets/transports/rest.py | 380 +- ...a_google.maps.mapsplatformdatasets.v1.json | 26 +- .../test_maps_platform_datasets.py | 30 + .../google/maps/places/gapic_version.py | 2 +- .../google/maps/places_v1/gapic_version.py | 2 +- .../places_v1/services/places/async_client.py | 72 +- .../maps/places_v1/services/places/client.py | 77 +- .../services/places/transports/grpc.py | 100 +- .../places/transports/grpc_asyncio.py | 99 +- .../services/places/transports/rest.py | 335 +- ...nippet_metadata_google.maps.places.v1.json | 22 +- .../tests/unit/gapic/places_v1/test_places.py | 22 + .../maps/routeoptimization/gapic_version.py | 2 +- .../routeoptimization_v1/gapic_version.py | 2 +- .../route_optimization/async_client.py | 56 +- .../services/route_optimization/client.py | 61 +- .../route_optimization/transports/grpc.py | 100 +- .../transports/grpc_asyncio.py | 97 +- .../route_optimization/transports/rest.py | 203 +- ...data_google.maps.routeoptimization.v1.json | 10 +- .../test_route_optimization.py | 10 + .../services/routes/async_client.py | 48 +- .../maps/routing_v2/services/routes/client.py | 53 +- .../services/routes/transports/grpc.py | 94 +- .../routes/transports/grpc_asyncio.py | 93 +- .../services/routes/transports/rest.py | 120 +- ...ippet_metadata_google.maps.routing.v2.json | 8 +- .../unit/gapic/routing_v2/test_routes.py | 8 + .../google/maps/solar/gapic_version.py | 2 +- .../google/maps/solar_v1/gapic_version.py | 2 +- .../solar_v1/services/solar/async_client.py | 56 +- .../maps/solar_v1/services/solar/client.py | 61 +- .../services/solar/transports/grpc.py | 96 +- .../services/solar/transports/grpc_asyncio.py | 95 +- .../services/solar/transports/rest.py | 201 +- ...snippet_metadata_google.maps.solar.v1.json | 14 +- .../tests/unit/gapic/solar_v1/test_solar.py | 12 + .../merchant_accounts/gapic_version.py | 2 +- .../merchant_accounts_v1beta/gapic_version.py | 2 +- .../account_issue_service/async_client.py | 40 +- .../services/account_issue_service/client.py | 45 +- .../services/account_issue_service/pagers.py | 16 +- .../account_issue_service/transports/grpc.py | 92 +- .../transports/grpc_asyncio.py | 91 +- .../account_issue_service/transports/rest.py | 76 +- .../account_tax_service/async_client.py | 56 +- .../services/account_tax_service/client.py | 61 +- .../services/account_tax_service/pagers.py | 16 +- .../account_tax_service/transports/grpc.py | 96 +- .../transports/grpc_asyncio.py | 95 +- .../account_tax_service/transports/rest.py | 205 +- .../services/accounts_service/async_client.py | 80 +- .../services/accounts_service/client.py | 85 +- .../services/accounts_service/pagers.py | 32 +- .../accounts_service/transports/grpc.py | 104 +- .../transports/grpc_asyncio.py | 103 +- .../accounts_service/transports/rest.py | 371 +- .../autofeed_settings_service/async_client.py | 48 +- .../autofeed_settings_service/client.py | 53 +- .../transports/grpc.py | 94 +- .../transports/grpc_asyncio.py | 93 +- .../transports/rest.py | 142 +- .../business_identity_service/async_client.py | 48 +- .../business_identity_service/client.py | 53 +- .../transports/grpc.py | 94 +- .../transports/grpc_asyncio.py | 93 +- .../transports/rest.py | 142 +- .../business_info_service/async_client.py | 48 +- .../services/business_info_service/client.py | 53 +- .../business_info_service/transports/grpc.py | 94 +- .../transports/grpc_asyncio.py | 93 +- .../business_info_service/transports/rest.py | 138 +- .../email_preferences_service/async_client.py | 48 +- .../email_preferences_service/client.py | 53 +- .../transports/grpc.py | 94 +- .../transports/grpc_asyncio.py | 93 +- .../transports/rest.py | 142 +- .../services/homepage_service/async_client.py | 64 +- .../services/homepage_service/client.py | 69 +- .../homepage_service/transports/grpc.py | 98 +- .../transports/grpc_asyncio.py | 97 +- .../homepage_service/transports/rest.py | 264 +- .../async_client.py | 48 +- .../online_return_policy_service/client.py | 53 +- .../online_return_policy_service/pagers.py | 16 +- .../transports/grpc.py | 96 +- .../transports/grpc_asyncio.py | 95 +- .../transports/rest.py | 142 +- .../services/programs_service/async_client.py | 64 +- .../services/programs_service/client.py | 69 +- .../services/programs_service/pagers.py | 16 +- .../programs_service/transports/grpc.py | 98 +- .../transports/grpc_asyncio.py | 97 +- .../programs_service/transports/rest.py | 262 +- .../services/regions_service/async_client.py | 72 +- .../services/regions_service/client.py | 77 +- .../services/regions_service/pagers.py | 16 +- .../regions_service/transports/grpc.py | 100 +- .../transports/grpc_asyncio.py | 99 +- .../regions_service/transports/rest.py | 308 +- .../shipping_settings_service/async_client.py | 48 +- .../shipping_settings_service/client.py | 53 +- .../transports/grpc.py | 94 +- .../transports/grpc_asyncio.py | 93 +- .../transports/rest.py | 142 +- .../async_client.py | 48 +- .../client.py | 53 +- .../transports/grpc.py | 94 +- .../transports/grpc_asyncio.py | 93 +- .../transports/rest.py | 138 +- .../terms_of_service_service/async_client.py | 56 +- .../terms_of_service_service/client.py | 61 +- .../transports/grpc.py | 96 +- .../transports/grpc_asyncio.py | 95 +- .../transports/rest.py | 180 +- .../services/user_service/async_client.py | 72 +- .../services/user_service/client.py | 77 +- .../services/user_service/pagers.py | 16 +- .../services/user_service/transports/grpc.py | 100 +- .../user_service/transports/grpc_asyncio.py | 99 +- .../services/user_service/transports/rest.py | 308 +- ...gle.shopping.merchant.accounts.v1beta.json | 182 +- .../test_account_issue_service.py | 5 + .../test_account_tax_service.py | 15 + .../test_accounts_service.py | 27 + .../test_autofeed_settings_service.py | 10 + .../test_business_identity_service.py | 10 + .../test_business_info_service.py | 10 + .../test_email_preferences_service.py | 10 + .../test_homepage_service.py | 18 + .../test_online_return_policy_service.py | 10 + .../test_programs_service.py | 20 + .../test_regions_service.py | 25 + .../test_shipping_settings_service.py | 9 + ...erms_of_service_agreement_state_service.py | 10 + .../test_terms_of_service_service.py | 14 + .../test_user_service.py | 25 + .../merchant_conversions/gapic_version.py | 2 +- .../gapic_version.py | 2 +- .../async_client.py | 80 +- .../conversion_sources_service/client.py | 85 +- .../conversion_sources_service/pagers.py | 16 +- .../transports/grpc.py | 104 +- .../transports/grpc_asyncio.py | 103 +- .../transports/rest.py | 380 +- ....shopping.merchant.conversions.v1beta.json | 26 +- .../test_conversion_sources_service.py | 29 + .../merchant_datasources/gapic_version.py | 2 +- .../gapic_version.py | 2 +- .../data_sources_service/async_client.py | 80 +- .../services/data_sources_service/client.py | 85 +- .../services/data_sources_service/pagers.py | 16 +- .../data_sources_service/transports/grpc.py | 102 +- .../transports/grpc_asyncio.py | 101 +- .../data_sources_service/transports/rest.py | 352 +- .../file_uploads_service/async_client.py | 40 +- .../services/file_uploads_service/client.py | 45 +- .../file_uploads_service/transports/grpc.py | 92 +- .../transports/grpc_asyncio.py | 91 +- .../file_uploads_service/transports/rest.py | 74 +- ....shopping.merchant.datasources.v1beta.json | 30 +- .../test_data_sources_service.py | 29 + .../test_file_uploads_service.py | 5 + .../merchant_inventories/gapic_version.py | 2 +- .../gapic_version.py | 2 +- .../local_inventory_service/async_client.py | 56 +- .../local_inventory_service/client.py | 61 +- .../local_inventory_service/pagers.py | 16 +- .../transports/grpc.py | 96 +- .../transports/grpc_asyncio.py | 95 +- .../transports/rest.py | 185 +- .../async_client.py | 56 +- .../regional_inventory_service/client.py | 61 +- .../regional_inventory_service/pagers.py | 16 +- .../transports/grpc.py | 96 +- .../transports/grpc_asyncio.py | 95 +- .../transports/rest.py | 183 +- ....shopping.merchant.inventories.v1beta.json | 26 +- .../test_local_inventory_service.py | 14 + .../test_regional_inventory_service.py | 14 + .../shopping/merchant_lfp/gapic_version.py | 2 +- .../merchant_lfp_v1beta/gapic_version.py | 2 +- .../lfp_inventory_service/async_client.py | 40 +- .../services/lfp_inventory_service/client.py | 45 +- .../lfp_inventory_service/transports/grpc.py | 92 +- .../transports/grpc_asyncio.py | 91 +- .../lfp_inventory_service/transports/rest.py | 74 +- .../services/lfp_sale_service/async_client.py | 40 +- .../services/lfp_sale_service/client.py | 45 +- .../lfp_sale_service/transports/grpc.py | 92 +- .../transports/grpc_asyncio.py | 91 +- .../lfp_sale_service/transports/rest.py | 74 +- .../lfp_store_service/async_client.py | 64 +- .../services/lfp_store_service/client.py | 69 +- .../services/lfp_store_service/pagers.py | 16 +- .../lfp_store_service/transports/grpc.py | 98 +- .../transports/grpc_asyncio.py | 97 +- .../lfp_store_service/transports/rest.py | 238 +- ...a_google.shopping.merchant.lfp.v1beta.json | 26 +- .../test_lfp_inventory_service.py | 4 + .../test_lfp_sale_service.py | 4 + .../test_lfp_store_service.py | 20 + .../merchant_notifications/gapic_version.py | 2 +- .../gapic_version.py | 2 +- .../notifications_api_service/async_client.py | 72 +- .../notifications_api_service/client.py | 77 +- .../notifications_api_service/pagers.py | 16 +- .../transports/grpc.py | 100 +- .../transports/grpc_asyncio.py | 99 +- .../transports/rest.py | 310 +- ...hopping.merchant.notifications.v1beta.json | 22 +- .../test_notifications_api_service.py | 25 + .../merchant_promotions/gapic_version.py | 2 +- .../gapic_version.py | 2 +- .../promotions_service/async_client.py | 56 +- .../services/promotions_service/client.py | 61 +- .../services/promotions_service/pagers.py | 16 +- .../promotions_service/transports/grpc.py | 96 +- .../transports/grpc_asyncio.py | 95 +- .../promotions_service/transports/rest.py | 202 +- ...e.shopping.merchant.promotions.v1beta.json | 14 +- .../test_promotions_service.py | 14 + .../shopping/merchant_quota/gapic_version.py | 2 +- .../merchant_quota_v1beta/gapic_version.py | 2 +- .../services/quota_service/async_client.py | 40 +- .../services/quota_service/client.py | 45 +- .../services/quota_service/pagers.py | 16 +- .../services/quota_service/transports/grpc.py | 92 +- .../quota_service/transports/grpc_asyncio.py | 91 +- .../services/quota_service/transports/rest.py | 74 +- ...google.shopping.merchant.quota.v1beta.json | 6 +- .../test_quota_service.py | 5 + .../merchant_reports/gapic_version.py | 2 +- .../merchant_reports_v1beta/gapic_version.py | 2 +- .../services/report_service/async_client.py | 40 +- .../services/report_service/client.py | 45 +- .../services/report_service/pagers.py | 16 +- .../report_service/transports/grpc.py | 92 +- .../report_service/transports/grpc_asyncio.py | 91 +- .../report_service/transports/rest.py | 74 +- ...ogle.shopping.merchant.reports.v1beta.json | 6 +- .../test_report_service.py | 5 + .../grafeas/grafeas/grafeas/gapic_version.py | 2 +- .../grafeas/grafeas_v1/gapic_version.py | 2 +- .../services/grafeas/async_client.py | 144 +- .../grafeas_v1/services/grafeas/client.py | 123 +- .../grafeas_v1/services/grafeas/pagers.py | 48 +- .../services/grafeas/transports/grpc.py | 118 +- .../grafeas/transports/grpc_asyncio.py | 117 +- .../services/grafeas/transports/rest.py | 866 +- .../snippet_metadata_grafeas.v1.json | 58 +- .../unit/gapic/grafeas_v1/test_grafeas.py | 70 + 1511 files changed, 17109 insertions(+), 340741 deletions(-) delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/.coveragerc delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/.flake8 delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/MANIFEST.in delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/README.rst delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/conf.py delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/index.rst delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/mapsplatformdatasets_v1/maps_platform_datasets.rst delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/mapsplatformdatasets_v1/services_.rst delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/mapsplatformdatasets_v1/types_.rst delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets/__init__.py delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets/gapic_version.py delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets/py.typed delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/__init__.py delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/gapic_version.py delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/py.typed delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/__init__.py delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/__init__.py delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/async_client.py delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/client.py delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/pagers.py delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/README.rst delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/__init__.py delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/base.py delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/grpc.py delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/rest.py delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/rest_base.py delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/types/__init__.py delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/types/data_source.py delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/types/dataset.py delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/types/maps_platform_datasets.py delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/types/maps_platform_datasets_service.py delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/mypy.ini delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/noxfile.py delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_create_dataset_async.py delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_create_dataset_sync.py delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_delete_dataset_async.py delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_delete_dataset_sync.py delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_fetch_dataset_errors_async.py delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_fetch_dataset_errors_sync.py delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_get_dataset_async.py delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_get_dataset_sync.py delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_list_datasets_async.py delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_list_datasets_sync.py delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_update_dataset_metadata_async.py delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_update_dataset_metadata_sync.py delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/snippet_metadata_google.maps.mapsplatformdatasets.v1.json delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/scripts/fixup_mapsplatformdatasets_v1_keywords.py delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/setup.py delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.13.txt delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/tests/__init__.py delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/tests/unit/gapic/mapsplatformdatasets_v1/__init__.py delete mode 100644 owl-bot-staging/google-maps-mapsplatformdatasets/v1/tests/unit/gapic/mapsplatformdatasets_v1/test_maps_platform_datasets.py delete mode 100644 owl-bot-staging/google-maps-places/v1/.coveragerc delete mode 100644 owl-bot-staging/google-maps-places/v1/.flake8 delete mode 100644 owl-bot-staging/google-maps-places/v1/MANIFEST.in delete mode 100644 owl-bot-staging/google-maps-places/v1/README.rst delete mode 100644 owl-bot-staging/google-maps-places/v1/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-maps-places/v1/docs/conf.py delete mode 100644 owl-bot-staging/google-maps-places/v1/docs/index.rst delete mode 100644 owl-bot-staging/google-maps-places/v1/docs/places_v1/places.rst delete mode 100644 owl-bot-staging/google-maps-places/v1/docs/places_v1/services_.rst delete mode 100644 owl-bot-staging/google-maps-places/v1/docs/places_v1/types_.rst delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places/__init__.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places/gapic_version.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places/py.typed delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/__init__.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/gapic_version.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/py.typed delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/__init__.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/__init__.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/async_client.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/client.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/README.rst delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/__init__.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/base.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/grpc.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/rest.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/rest_base.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/__init__.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/attribution.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/content_block.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/contextual_content.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/ev_charging.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/fuel_options.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/geometry.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/photo.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/place.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/places_service.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/polyline.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/price_range.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/reference.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/review.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/route_modifiers.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/routing_preference.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/routing_summary.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/travel_mode.py delete mode 100644 owl-bot-staging/google-maps-places/v1/mypy.ini delete mode 100644 owl-bot-staging/google-maps-places/v1/noxfile.py delete mode 100644 owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_autocomplete_places_async.py delete mode 100644 owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_autocomplete_places_sync.py delete mode 100644 owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_photo_media_async.py delete mode 100644 owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_photo_media_sync.py delete mode 100644 owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_place_async.py delete mode 100644 owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_place_sync.py delete mode 100644 owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_nearby_async.py delete mode 100644 owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_nearby_sync.py delete mode 100644 owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_text_async.py delete mode 100644 owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_text_sync.py delete mode 100644 owl-bot-staging/google-maps-places/v1/samples/generated_samples/snippet_metadata_google.maps.places.v1.json delete mode 100644 owl-bot-staging/google-maps-places/v1/scripts/fixup_places_v1_keywords.py delete mode 100644 owl-bot-staging/google-maps-places/v1/setup.py delete mode 100644 owl-bot-staging/google-maps-places/v1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-maps-places/v1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-maps-places/v1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-maps-places/v1/testing/constraints-3.13.txt delete mode 100644 owl-bot-staging/google-maps-places/v1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-maps-places/v1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-maps-places/v1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-maps-places/v1/tests/__init__.py delete mode 100644 owl-bot-staging/google-maps-places/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-maps-places/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-maps-places/v1/tests/unit/gapic/places_v1/__init__.py delete mode 100644 owl-bot-staging/google-maps-places/v1/tests/unit/gapic/places_v1/test_places.py delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/.coveragerc delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/.flake8 delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/MANIFEST.in delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/README.rst delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/docs/conf.py delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/docs/index.rst delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/docs/routeoptimization_v1/route_optimization.rst delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/docs/routeoptimization_v1/services_.rst delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/docs/routeoptimization_v1/types_.rst delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization/__init__.py delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization/gapic_version.py delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization/py.typed delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/__init__.py delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/gapic_version.py delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/py.typed delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/__init__.py delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/__init__.py delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/async_client.py delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/client.py delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/README.rst delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/__init__.py delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/base.py delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/grpc.py delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/rest.py delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/rest_base.py delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/types/__init__.py delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/types/route_optimization_service.py delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/mypy.ini delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/noxfile.py delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/samples/generated_samples/routeoptimization_v1_generated_route_optimization_batch_optimize_tours_async.py delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/samples/generated_samples/routeoptimization_v1_generated_route_optimization_batch_optimize_tours_sync.py delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/samples/generated_samples/routeoptimization_v1_generated_route_optimization_optimize_tours_async.py delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/samples/generated_samples/routeoptimization_v1_generated_route_optimization_optimize_tours_sync.py delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/samples/generated_samples/snippet_metadata_google.maps.routeoptimization.v1.json delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/scripts/fixup_routeoptimization_v1_keywords.py delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/setup.py delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.13.txt delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/tests/__init__.py delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/tests/unit/gapic/routeoptimization_v1/__init__.py delete mode 100644 owl-bot-staging/google-maps-routeoptimization/v1/tests/unit/gapic/routeoptimization_v1/test_route_optimization.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/.coveragerc delete mode 100644 owl-bot-staging/google-maps-routing/v2/.flake8 delete mode 100644 owl-bot-staging/google-maps-routing/v2/MANIFEST.in delete mode 100644 owl-bot-staging/google-maps-routing/v2/README.rst delete mode 100644 owl-bot-staging/google-maps-routing/v2/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-maps-routing/v2/docs/conf.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/docs/index.rst delete mode 100644 owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst delete mode 100644 owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services_.rst delete mode 100644 owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types_.rst delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/README.rst delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest_base.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/localized_time.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline_details.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/traffic_model.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/transit.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/transit_preferences.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/mypy.ini delete mode 100644 owl-bot-staging/google-maps-routing/v2/noxfile.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json delete mode 100644 owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/setup.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.13.txt delete mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-maps-routing/v2/tests/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py delete mode 100644 owl-bot-staging/google-maps-solar/v1/.coveragerc delete mode 100644 owl-bot-staging/google-maps-solar/v1/.flake8 delete mode 100644 owl-bot-staging/google-maps-solar/v1/MANIFEST.in delete mode 100644 owl-bot-staging/google-maps-solar/v1/README.rst delete mode 100644 owl-bot-staging/google-maps-solar/v1/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-maps-solar/v1/docs/conf.py delete mode 100644 owl-bot-staging/google-maps-solar/v1/docs/index.rst delete mode 100644 owl-bot-staging/google-maps-solar/v1/docs/solar_v1/services_.rst delete mode 100644 owl-bot-staging/google-maps-solar/v1/docs/solar_v1/solar.rst delete mode 100644 owl-bot-staging/google-maps-solar/v1/docs/solar_v1/types_.rst delete mode 100644 owl-bot-staging/google-maps-solar/v1/google/maps/solar/__init__.py delete mode 100644 owl-bot-staging/google-maps-solar/v1/google/maps/solar/gapic_version.py delete mode 100644 owl-bot-staging/google-maps-solar/v1/google/maps/solar/py.typed delete mode 100644 owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/__init__.py delete mode 100644 owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/gapic_version.py delete mode 100644 owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/py.typed delete mode 100644 owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/__init__.py delete mode 100644 owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/__init__.py delete mode 100644 owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/async_client.py delete mode 100644 owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/client.py delete mode 100644 owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/README.rst delete mode 100644 owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/__init__.py delete mode 100644 owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/base.py delete mode 100644 owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/grpc.py delete mode 100644 owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/rest.py delete mode 100644 owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/rest_base.py delete mode 100644 owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/types/__init__.py delete mode 100644 owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/types/solar_service.py delete mode 100644 owl-bot-staging/google-maps-solar/v1/mypy.ini delete mode 100644 owl-bot-staging/google-maps-solar/v1/noxfile.py delete mode 100644 owl-bot-staging/google-maps-solar/v1/samples/generated_samples/snippet_metadata_google.maps.solar.v1.json delete mode 100644 owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_find_closest_building_insights_async.py delete mode 100644 owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_find_closest_building_insights_sync.py delete mode 100644 owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_get_data_layers_async.py delete mode 100644 owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_get_data_layers_sync.py delete mode 100644 owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_get_geo_tiff_async.py delete mode 100644 owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_get_geo_tiff_sync.py delete mode 100644 owl-bot-staging/google-maps-solar/v1/scripts/fixup_solar_v1_keywords.py delete mode 100644 owl-bot-staging/google-maps-solar/v1/setup.py delete mode 100644 owl-bot-staging/google-maps-solar/v1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-maps-solar/v1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-maps-solar/v1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-maps-solar/v1/testing/constraints-3.13.txt delete mode 100644 owl-bot-staging/google-maps-solar/v1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-maps-solar/v1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-maps-solar/v1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-maps-solar/v1/tests/__init__.py delete mode 100644 owl-bot-staging/google-maps-solar/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-maps-solar/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-maps-solar/v1/tests/unit/gapic/solar_v1/__init__.py delete mode 100644 owl-bot-staging/google-maps-solar/v1/tests/unit/gapic/solar_v1/test_solar.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/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/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/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/email_preferences_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/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/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/__init__.py 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/__init__.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/__init__.py 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/__init__.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/__init__.py 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/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/__init__.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/__init__.py 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/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/__init__.py 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/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/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/__init__.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/__init__.py 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/__init__.py 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/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/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/homepage.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_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_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_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_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_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_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_email_preferences_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_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 delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/.coveragerc delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/.flake8 delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/MANIFEST.in delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/conf.py delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/index.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/merchant_conversions_v1beta/conversion_sources_service.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/merchant_conversions_v1beta/services_.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/merchant_conversions_v1beta/types_.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions/gapic_version.py delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions/py.typed delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/gapic_metadata.json delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/gapic_version.py delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/py.typed delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/async_client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/pagers.py delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/rest.py delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/rest_base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/types/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/types/conversionsources.py delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/mypy.ini delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/noxfile.py delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_create_conversion_source_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_create_conversion_source_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_delete_conversion_source_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_delete_conversion_source_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_get_conversion_source_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_get_conversion_source_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_list_conversion_sources_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_list_conversion_sources_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_undelete_conversion_source_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_undelete_conversion_source_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_update_conversion_source_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_update_conversion_source_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.conversions.v1beta.json delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/scripts/fixup_merchant_conversions_v1beta_keywords.py delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/setup.py delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.13.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/tests/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/tests/unit/gapic/merchant_conversions_v1beta/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-conversions/v1beta/tests/unit/gapic/merchant_conversions_v1beta/test_conversion_sources_service.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/.coveragerc delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/.flake8 delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/MANIFEST.in delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/conf.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/index.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/merchant_datasources_v1beta/data_sources_service.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/merchant_datasources_v1beta/file_uploads_service.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/merchant_datasources_v1beta/services_.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/merchant_datasources_v1beta/types_.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources/gapic_version.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources/py.typed delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/gapic_metadata.json delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/gapic_version.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/py.typed delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/async_client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/pagers.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/rest.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/rest_base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/async_client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/rest.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/rest_base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/types/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/types/datasources.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/types/datasourcetypes.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/types/fileinputs.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/types/fileuploads.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/mypy.ini delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/noxfile.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_create_data_source_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_create_data_source_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_delete_data_source_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_delete_data_source_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_fetch_data_source_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_fetch_data_source_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_get_data_source_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_get_data_source_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_list_data_sources_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_list_data_sources_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_update_data_source_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_update_data_source_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_file_uploads_service_get_file_upload_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_file_uploads_service_get_file_upload_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.datasources.v1beta.json delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/scripts/fixup_merchant_datasources_v1beta_keywords.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/setup.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.13.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/tests/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/tests/unit/gapic/merchant_datasources_v1beta/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/tests/unit/gapic/merchant_datasources_v1beta/test_data_sources_service.py delete mode 100644 owl-bot-staging/google-shopping-merchant-datasources/v1beta/tests/unit/gapic/merchant_datasources_v1beta/test_file_uploads_service.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/.coveragerc delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/.flake8 delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/MANIFEST.in delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/conf.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/index.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/local_inventory_service.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/regional_inventory_service.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/services_.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/types_.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/gapic_version.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/py.typed delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/gapic_metadata.json delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/gapic_version.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/py.typed delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/async_client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/pagers.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/rest.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/rest_base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/async_client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/pagers.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/rest.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/rest_base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/localinventory.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/regionalinventory.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/mypy.ini delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/noxfile.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.inventories.v1beta.json delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/scripts/fixup_merchant_inventories_v1beta_keywords.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/setup.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.13.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/test_local_inventory_service.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/test_regional_inventory_service.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/.coveragerc delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/.flake8 delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/MANIFEST.in delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/conf.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/index.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/merchant_lfp_v1beta/lfp_inventory_service.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/merchant_lfp_v1beta/lfp_sale_service.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/merchant_lfp_v1beta/lfp_store_service.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/merchant_lfp_v1beta/services_.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/merchant_lfp_v1beta/types_.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp/gapic_version.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp/py.typed delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/gapic_metadata.json delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/gapic_version.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/py.typed delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/async_client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/rest.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/rest_base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/async_client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/rest.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/rest_base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/async_client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/pagers.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/rest.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/rest_base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/types/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/types/lfpinventory.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/types/lfpsale.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/types/lfpstore.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/mypy.ini delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/noxfile.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_inventory_service_insert_lfp_inventory_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_inventory_service_insert_lfp_inventory_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_sale_service_insert_lfp_sale_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_sale_service_insert_lfp_sale_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_delete_lfp_store_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_delete_lfp_store_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_get_lfp_store_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_get_lfp_store_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_insert_lfp_store_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_insert_lfp_store_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_list_lfp_stores_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_list_lfp_stores_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.lfp.v1beta.json delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/scripts/fixup_merchant_lfp_v1beta_keywords.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/setup.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/testing/constraints-3.13.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/tests/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/tests/unit/gapic/merchant_lfp_v1beta/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/tests/unit/gapic/merchant_lfp_v1beta/test_lfp_inventory_service.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/tests/unit/gapic/merchant_lfp_v1beta/test_lfp_sale_service.py delete mode 100644 owl-bot-staging/google-shopping-merchant-lfp/v1beta/tests/unit/gapic/merchant_lfp_v1beta/test_lfp_store_service.py delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/.coveragerc delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/.flake8 delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/MANIFEST.in delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/conf.py delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/index.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/merchant_notifications_v1beta/notifications_api_service.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/merchant_notifications_v1beta/services_.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/merchant_notifications_v1beta/types_.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications/gapic_version.py delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications/py.typed delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/gapic_metadata.json delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/gapic_version.py delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/py.typed delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/async_client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/pagers.py delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/rest.py delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/rest_base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/types/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/types/notificationsapi.py delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/mypy.ini delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/noxfile.py delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_create_notification_subscription_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_create_notification_subscription_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_delete_notification_subscription_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_delete_notification_subscription_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_get_notification_subscription_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_get_notification_subscription_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_list_notification_subscriptions_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_list_notification_subscriptions_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_update_notification_subscription_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_update_notification_subscription_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.notifications.v1beta.json delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/scripts/fixup_merchant_notifications_v1beta_keywords.py delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/setup.py delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/testing/constraints-3.13.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/tests/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/tests/unit/gapic/merchant_notifications_v1beta/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-notifications/v1beta/tests/unit/gapic/merchant_notifications_v1beta/test_notifications_api_service.py delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/.coveragerc delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/.flake8 delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/MANIFEST.in delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/conf.py delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/index.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/merchant_promotions_v1beta/promotions_service.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/merchant_promotions_v1beta/services_.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/merchant_promotions_v1beta/types_.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions/gapic_version.py delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions/py.typed delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/gapic_metadata.json delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/gapic_version.py delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/py.typed delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/async_client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/pagers.py delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/rest.py delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/rest_base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/types/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/types/promotions.py delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/types/promotions_common.py delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/mypy.ini delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/noxfile.py delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_get_promotion_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_get_promotion_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_insert_promotion_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_insert_promotion_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_list_promotions_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_list_promotions_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.promotions.v1beta.json delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/scripts/fixup_merchant_promotions_v1beta_keywords.py delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/setup.py delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/testing/constraints-3.13.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/tests/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/tests/unit/gapic/merchant_promotions_v1beta/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-promotions/v1beta/tests/unit/gapic/merchant_promotions_v1beta/test_promotions_service.py delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/.coveragerc delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/.flake8 delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/MANIFEST.in delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/conf.py delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/index.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/merchant_quota_v1beta/quota_service.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/merchant_quota_v1beta/services_.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/merchant_quota_v1beta/types_.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota/gapic_version.py delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota/py.typed delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/gapic_metadata.json delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/gapic_version.py delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/py.typed delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/async_client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/pagers.py delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/rest.py delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/rest_base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/types/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/types/quota.py delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/mypy.ini delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/noxfile.py delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/samples/generated_samples/merchantapi_v1beta_generated_quota_service_list_quota_groups_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/samples/generated_samples/merchantapi_v1beta_generated_quota_service_list_quota_groups_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.quota.v1beta.json delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/scripts/fixup_merchant_quota_v1beta_keywords.py delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/setup.py delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.13.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/tests/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/tests/unit/gapic/merchant_quota_v1beta/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-quota/v1beta/tests/unit/gapic/merchant_quota_v1beta/test_quota_service.py delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/.coveragerc delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/.flake8 delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/MANIFEST.in delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/conf.py delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/index.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/merchant_reports_v1beta/report_service.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/merchant_reports_v1beta/services_.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/merchant_reports_v1beta/types_.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports/gapic_version.py delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports/py.typed delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/gapic_metadata.json delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/gapic_version.py delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/py.typed delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/async_client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/pagers.py delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/rest.py delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/rest_base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/types/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/types/reports.py delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/mypy.ini delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/noxfile.py delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/samples/generated_samples/merchantapi_v1beta_generated_report_service_search_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/samples/generated_samples/merchantapi_v1beta_generated_report_service_search_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.reports.v1beta.json delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/scripts/fixup_merchant_reports_v1beta_keywords.py delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/setup.py delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/testing/constraints-3.13.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/tests/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/tests/unit/gapic/merchant_reports_v1beta/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-reports/v1beta/tests/unit/gapic/merchant_reports_v1beta/test_report_service.py delete mode 100644 owl-bot-staging/grafeas/v1/.coveragerc delete mode 100644 owl-bot-staging/grafeas/v1/.flake8 delete mode 100644 owl-bot-staging/grafeas/v1/MANIFEST.in delete mode 100644 owl-bot-staging/grafeas/v1/README.rst delete mode 100644 owl-bot-staging/grafeas/v1/docs/_static/custom.css delete mode 100644 owl-bot-staging/grafeas/v1/docs/conf.py delete mode 100644 owl-bot-staging/grafeas/v1/docs/grafeas_v1/grafeas.rst delete mode 100644 owl-bot-staging/grafeas/v1/docs/grafeas_v1/services_.rst delete mode 100644 owl-bot-staging/grafeas/v1/docs/grafeas_v1/types_.rst delete mode 100644 owl-bot-staging/grafeas/v1/docs/index.rst delete mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas/__init__.py delete mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas/gapic_version.py delete mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas/py.typed delete mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/__init__.py delete mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/gapic_version.py delete mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/py.typed delete mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/__init__.py delete mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/__init__.py delete mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/async_client.py delete mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/client.py delete mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/pagers.py delete mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/README.rst delete mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/__init__.py delete mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/base.py delete mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/grpc.py delete mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/rest.py delete mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/rest_base.py delete mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/__init__.py delete mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/attestation.py delete mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/build.py delete mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/common.py delete mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/compliance.py delete mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/cvss.py delete mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/deployment.py delete mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/discovery.py delete mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/dsse_attestation.py delete mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/grafeas.py delete mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/image.py delete mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/intoto_provenance.py delete mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/intoto_statement.py delete mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/package.py delete mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/provenance.py delete mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/sbom.py delete mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/severity.py delete mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/slsa_provenance.py delete mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/slsa_provenance_zero_two.py delete mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/upgrade.py delete mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/vex.py delete mode 100644 owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/vulnerability.py delete mode 100644 owl-bot-staging/grafeas/v1/mypy.ini delete mode 100644 owl-bot-staging/grafeas/v1/noxfile.py delete mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_notes_async.py delete mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_notes_sync.py delete mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_occurrences_async.py delete mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_occurrences_sync.py delete mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_note_async.py delete mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_note_sync.py delete mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_occurrence_async.py delete mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_occurrence_sync.py delete mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_note_async.py delete mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_note_sync.py delete mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_occurrence_async.py delete mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_occurrence_sync.py delete mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_note_async.py delete mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_note_sync.py delete mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_async.py delete mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_note_async.py delete mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_note_sync.py delete mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_sync.py delete mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_note_occurrences_async.py delete mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_note_occurrences_sync.py delete mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_notes_async.py delete mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_notes_sync.py delete mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_occurrences_async.py delete mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_occurrences_sync.py delete mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_note_async.py delete mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_note_sync.py delete mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_occurrence_async.py delete mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_occurrence_sync.py delete mode 100644 owl-bot-staging/grafeas/v1/samples/generated_samples/snippet_metadata_grafeas.v1.json delete mode 100644 owl-bot-staging/grafeas/v1/scripts/fixup_grafeas_v1_keywords.py delete mode 100644 owl-bot-staging/grafeas/v1/setup.py delete mode 100644 owl-bot-staging/grafeas/v1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/grafeas/v1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/grafeas/v1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/grafeas/v1/testing/constraints-3.13.txt delete mode 100644 owl-bot-staging/grafeas/v1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/grafeas/v1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/grafeas/v1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/grafeas/v1/tests/__init__.py delete mode 100644 owl-bot-staging/grafeas/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/grafeas/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/grafeas/v1/tests/unit/gapic/grafeas_v1/__init__.py delete mode 100644 owl-bot-staging/grafeas/v1/tests/unit/gapic/grafeas_v1/test_grafeas.py diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/.coveragerc b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/.coveragerc deleted file mode 100644 index 9f3dc18dceda..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/maps/mapsplatformdatasets/__init__.py - google/maps/mapsplatformdatasets/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-maps-mapsplatformdatasets/v1/.flake8 b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/MANIFEST.in b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/MANIFEST.in deleted file mode 100644 index d1e798fda05b..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/maps/mapsplatformdatasets *.py -recursive-include google/maps/mapsplatformdatasets_v1 *.py diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/README.rst b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/README.rst deleted file mode 100644 index 4c46f2d1337e..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Maps Mapsplatformdatasets 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 Maps Mapsplatformdatasets 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 diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/_static/custom.css b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/_static/custom.css +++ /dev/null @@ -1,3 +0,0 @@ -dl.field-list > dt { - min-width: 100px -} diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/conf.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/conf.py deleted file mode 100644 index e64db530d444..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-maps-mapsplatformdatasets 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("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# 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.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -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-maps-mapsplatformdatasets" -copyright = u"2023, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# 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 = 'en' - -# 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"] - -# 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 Maps Client Libraries for Python", - "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-maps-mapsplatformdatasets-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-maps-mapsplatformdatasets.tex", - u"google-maps-mapsplatformdatasets 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-maps-mapsplatformdatasets", - u"Google Maps Mapsplatformdatasets 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-maps-mapsplatformdatasets", - u"google-maps-mapsplatformdatasets Documentation", - author, - "google-maps-mapsplatformdatasets", - "GAPIC library for Google Maps Mapsplatformdatasets API", - "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": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", 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-maps-mapsplatformdatasets/v1/docs/index.rst b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/index.rst deleted file mode 100644 index 81b0ab58750e..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - mapsplatformdatasets_v1/services_ - mapsplatformdatasets_v1/types_ diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/mapsplatformdatasets_v1/maps_platform_datasets.rst b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/mapsplatformdatasets_v1/maps_platform_datasets.rst deleted file mode 100644 index d9eff02a3f2b..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/mapsplatformdatasets_v1/maps_platform_datasets.rst +++ /dev/null @@ -1,10 +0,0 @@ -MapsPlatformDatasets --------------------------------------- - -.. automodule:: google.maps.mapsplatformdatasets_v1.services.maps_platform_datasets - :members: - :inherited-members: - -.. automodule:: google.maps.mapsplatformdatasets_v1.services.maps_platform_datasets.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/mapsplatformdatasets_v1/services_.rst b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/mapsplatformdatasets_v1/services_.rst deleted file mode 100644 index f2d8920fc6af..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/mapsplatformdatasets_v1/services_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Maps Mapsplatformdatasets v1 API -==================================================== -.. toctree:: - :maxdepth: 2 - - maps_platform_datasets diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/mapsplatformdatasets_v1/types_.rst b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/mapsplatformdatasets_v1/types_.rst deleted file mode 100644 index f4d2f2d7e793..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/docs/mapsplatformdatasets_v1/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Maps Mapsplatformdatasets v1 API -================================================= - -.. automodule:: google.maps.mapsplatformdatasets_v1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets/__init__.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets/__init__.py deleted file mode 100644 index d87a63978fdc..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets/__init__.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.mapsplatformdatasets import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.maps.mapsplatformdatasets_v1.services.maps_platform_datasets.client import MapsPlatformDatasetsClient -from google.maps.mapsplatformdatasets_v1.services.maps_platform_datasets.async_client import MapsPlatformDatasetsAsyncClient - -from google.maps.mapsplatformdatasets_v1.types.data_source import GcsSource -from google.maps.mapsplatformdatasets_v1.types.data_source import LocalFileSource -from google.maps.mapsplatformdatasets_v1.types.data_source import FileFormat -from google.maps.mapsplatformdatasets_v1.types.dataset import Dataset -from google.maps.mapsplatformdatasets_v1.types.dataset import Status -from google.maps.mapsplatformdatasets_v1.types.dataset import Usage -from google.maps.mapsplatformdatasets_v1.types.maps_platform_datasets import CreateDatasetRequest -from google.maps.mapsplatformdatasets_v1.types.maps_platform_datasets import DeleteDatasetRequest -from google.maps.mapsplatformdatasets_v1.types.maps_platform_datasets import FetchDatasetErrorsRequest -from google.maps.mapsplatformdatasets_v1.types.maps_platform_datasets import FetchDatasetErrorsResponse -from google.maps.mapsplatformdatasets_v1.types.maps_platform_datasets import GetDatasetRequest -from google.maps.mapsplatformdatasets_v1.types.maps_platform_datasets import ListDatasetsRequest -from google.maps.mapsplatformdatasets_v1.types.maps_platform_datasets import ListDatasetsResponse -from google.maps.mapsplatformdatasets_v1.types.maps_platform_datasets import UpdateDatasetMetadataRequest - -__all__ = ('MapsPlatformDatasetsClient', - 'MapsPlatformDatasetsAsyncClient', - 'GcsSource', - 'LocalFileSource', - 'FileFormat', - 'Dataset', - 'Status', - 'Usage', - 'CreateDatasetRequest', - 'DeleteDatasetRequest', - 'FetchDatasetErrorsRequest', - 'FetchDatasetErrorsResponse', - 'GetDatasetRequest', - 'ListDatasetsRequest', - 'ListDatasetsResponse', - 'UpdateDatasetMetadataRequest', -) diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets/gapic_version.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets/py.typed b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets/py.typed deleted file mode 100644 index b186faa8f14d..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-maps-mapsplatformdatasets package uses inline types. diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/__init__.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/__init__.py deleted file mode 100644 index 8d547fc08511..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/__init__.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.mapsplatformdatasets_v1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.maps_platform_datasets import MapsPlatformDatasetsClient -from .services.maps_platform_datasets import MapsPlatformDatasetsAsyncClient - -from .types.data_source import GcsSource -from .types.data_source import LocalFileSource -from .types.data_source import FileFormat -from .types.dataset import Dataset -from .types.dataset import Status -from .types.dataset import Usage -from .types.maps_platform_datasets import CreateDatasetRequest -from .types.maps_platform_datasets import DeleteDatasetRequest -from .types.maps_platform_datasets import FetchDatasetErrorsRequest -from .types.maps_platform_datasets import FetchDatasetErrorsResponse -from .types.maps_platform_datasets import GetDatasetRequest -from .types.maps_platform_datasets import ListDatasetsRequest -from .types.maps_platform_datasets import ListDatasetsResponse -from .types.maps_platform_datasets import UpdateDatasetMetadataRequest - -__all__ = ( - 'MapsPlatformDatasetsAsyncClient', -'CreateDatasetRequest', -'Dataset', -'DeleteDatasetRequest', -'FetchDatasetErrorsRequest', -'FetchDatasetErrorsResponse', -'FileFormat', -'GcsSource', -'GetDatasetRequest', -'ListDatasetsRequest', -'ListDatasetsResponse', -'LocalFileSource', -'MapsPlatformDatasetsClient', -'Status', -'UpdateDatasetMetadataRequest', -'Usage', -) diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/gapic_metadata.json b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/gapic_metadata.json deleted file mode 100644 index fe6bcbfe38b3..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/gapic_metadata.json +++ /dev/null @@ -1,118 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.maps.mapsplatformdatasets_v1", - "protoPackage": "google.maps.mapsplatformdatasets.v1", - "schema": "1.0", - "services": { - "MapsPlatformDatasets": { - "clients": { - "grpc": { - "libraryClient": "MapsPlatformDatasetsClient", - "rpcs": { - "CreateDataset": { - "methods": [ - "create_dataset" - ] - }, - "DeleteDataset": { - "methods": [ - "delete_dataset" - ] - }, - "FetchDatasetErrors": { - "methods": [ - "fetch_dataset_errors" - ] - }, - "GetDataset": { - "methods": [ - "get_dataset" - ] - }, - "ListDatasets": { - "methods": [ - "list_datasets" - ] - }, - "UpdateDatasetMetadata": { - "methods": [ - "update_dataset_metadata" - ] - } - } - }, - "grpc-async": { - "libraryClient": "MapsPlatformDatasetsAsyncClient", - "rpcs": { - "CreateDataset": { - "methods": [ - "create_dataset" - ] - }, - "DeleteDataset": { - "methods": [ - "delete_dataset" - ] - }, - "FetchDatasetErrors": { - "methods": [ - "fetch_dataset_errors" - ] - }, - "GetDataset": { - "methods": [ - "get_dataset" - ] - }, - "ListDatasets": { - "methods": [ - "list_datasets" - ] - }, - "UpdateDatasetMetadata": { - "methods": [ - "update_dataset_metadata" - ] - } - } - }, - "rest": { - "libraryClient": "MapsPlatformDatasetsClient", - "rpcs": { - "CreateDataset": { - "methods": [ - "create_dataset" - ] - }, - "DeleteDataset": { - "methods": [ - "delete_dataset" - ] - }, - "FetchDatasetErrors": { - "methods": [ - "fetch_dataset_errors" - ] - }, - "GetDataset": { - "methods": [ - "get_dataset" - ] - }, - "ListDatasets": { - "methods": [ - "list_datasets" - ] - }, - "UpdateDatasetMetadata": { - "methods": [ - "update_dataset_metadata" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/gapic_version.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/py.typed b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/py.typed deleted file mode 100644 index b186faa8f14d..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-maps-mapsplatformdatasets package uses inline types. diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/__init__.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/__init__.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/__init__.py deleted file mode 100644 index a8cb67724686..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 MapsPlatformDatasetsClient -from .async_client import MapsPlatformDatasetsAsyncClient - -__all__ = ( - 'MapsPlatformDatasetsClient', - 'MapsPlatformDatasetsAsyncClient', -) diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/async_client.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/async_client.py deleted file mode 100644 index 5b3c279b040e..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/async_client.py +++ /dev/null @@ -1,941 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.mapsplatformdatasets_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 - - -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.maps.mapsplatformdatasets_v1.services.maps_platform_datasets import pagers -from google.maps.mapsplatformdatasets_v1.types import data_source -from google.maps.mapsplatformdatasets_v1.types import dataset -from google.maps.mapsplatformdatasets_v1.types import dataset as gmm_dataset -from google.maps.mapsplatformdatasets_v1.types import maps_platform_datasets -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from .transports.base import MapsPlatformDatasetsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import MapsPlatformDatasetsGrpcAsyncIOTransport -from .client import MapsPlatformDatasetsClient - -try: - from google.api_core import client_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 MapsPlatformDatasetsAsyncClient: - """Service definition for the Maps Platform Datasets API.""" - - _client: MapsPlatformDatasetsClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = MapsPlatformDatasetsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = MapsPlatformDatasetsClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = MapsPlatformDatasetsClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = MapsPlatformDatasetsClient._DEFAULT_UNIVERSE - - dataset_path = staticmethod(MapsPlatformDatasetsClient.dataset_path) - parse_dataset_path = staticmethod(MapsPlatformDatasetsClient.parse_dataset_path) - common_billing_account_path = staticmethod(MapsPlatformDatasetsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(MapsPlatformDatasetsClient.parse_common_billing_account_path) - common_folder_path = staticmethod(MapsPlatformDatasetsClient.common_folder_path) - parse_common_folder_path = staticmethod(MapsPlatformDatasetsClient.parse_common_folder_path) - common_organization_path = staticmethod(MapsPlatformDatasetsClient.common_organization_path) - parse_common_organization_path = staticmethod(MapsPlatformDatasetsClient.parse_common_organization_path) - common_project_path = staticmethod(MapsPlatformDatasetsClient.common_project_path) - parse_common_project_path = staticmethod(MapsPlatformDatasetsClient.parse_common_project_path) - common_location_path = staticmethod(MapsPlatformDatasetsClient.common_location_path) - parse_common_location_path = staticmethod(MapsPlatformDatasetsClient.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: - MapsPlatformDatasetsAsyncClient: The constructed client. - """ - return MapsPlatformDatasetsClient.from_service_account_info.__func__(MapsPlatformDatasetsAsyncClient, 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: - MapsPlatformDatasetsAsyncClient: The constructed client. - """ - return MapsPlatformDatasetsClient.from_service_account_file.__func__(MapsPlatformDatasetsAsyncClient, 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 MapsPlatformDatasetsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> MapsPlatformDatasetsTransport: - """Returns the transport used by the client instance. - - Returns: - MapsPlatformDatasetsTransport: 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 = MapsPlatformDatasetsClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, MapsPlatformDatasetsTransport, Callable[..., MapsPlatformDatasetsTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the maps platform datasets 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,MapsPlatformDatasetsTransport,Callable[..., MapsPlatformDatasetsTransport]]]): - 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 MapsPlatformDatasetsTransport 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 = MapsPlatformDatasetsClient( - 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.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient`.", - extra = { - "serviceName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", - "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.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", - "credentialsType": None, - } - ) - - async def create_dataset(self, - request: Optional[Union[maps_platform_datasets.CreateDatasetRequest, dict]] = None, - *, - parent: Optional[str] = None, - dataset: Optional[gmm_dataset.Dataset] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> gmm_dataset.Dataset: - r"""Creates a new dataset for the specified project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import mapsplatformdatasets_v1 - - async def sample_create_dataset(): - # Create a client - client = mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient() - - # Initialize request argument(s) - request = mapsplatformdatasets_v1.CreateDatasetRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_dataset(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.mapsplatformdatasets_v1.types.CreateDatasetRequest, dict]]): - The request object. Request to create a maps dataset. - parent (:class:`str`): - Required. Parent project that will - own the dataset. Format: - projects/{project} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - dataset (:class:`google.maps.mapsplatformdatasets_v1.types.Dataset`): - Required. The dataset version to - create. - - This corresponds to the ``dataset`` 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.maps.mapsplatformdatasets_v1.types.Dataset: - A representation of a dataset - 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. - has_flattened_params = any([parent, dataset]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, maps_platform_datasets.CreateDatasetRequest): - request = maps_platform_datasets.CreateDatasetRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if dataset is not None: - request.dataset = dataset - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_dataset] - - # Certain 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_dataset_metadata(self, - request: Optional[Union[maps_platform_datasets.UpdateDatasetMetadataRequest, dict]] = None, - *, - dataset: Optional[gmm_dataset.Dataset] = 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]]] = (), - ) -> gmm_dataset.Dataset: - r"""Updates the metadata for the dataset. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import mapsplatformdatasets_v1 - - async def sample_update_dataset_metadata(): - # Create a client - client = mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient() - - # Initialize request argument(s) - request = mapsplatformdatasets_v1.UpdateDatasetMetadataRequest( - ) - - # Make the request - response = await client.update_dataset_metadata(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.mapsplatformdatasets_v1.types.UpdateDatasetMetadataRequest, dict]]): - The request object. Request to update the metadata fields - of the dataset. - dataset (:class:`google.maps.mapsplatformdatasets_v1.types.Dataset`): - Required. Resource name of the dataset to update. - Format: projects/{project}/datasets/{dataset_id} - - This corresponds to the ``dataset`` 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. - - The value "*" is used for full replacement (default). - - 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.maps.mapsplatformdatasets_v1.types.Dataset: - A representation of a dataset - 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. - has_flattened_params = any([dataset, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, maps_platform_datasets.UpdateDatasetMetadataRequest): - request = maps_platform_datasets.UpdateDatasetMetadataRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if dataset is not None: - request.dataset = dataset - 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_dataset_metadata] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("dataset.name", request.dataset.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_dataset(self, - request: Optional[Union[maps_platform_datasets.GetDatasetRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> dataset.Dataset: - r"""Gets the dataset. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import mapsplatformdatasets_v1 - - async def sample_get_dataset(): - # Create a client - client = mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient() - - # Initialize request argument(s) - request = mapsplatformdatasets_v1.GetDatasetRequest( - name="name_value", - ) - - # Make the request - response = await client.get_dataset(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.mapsplatformdatasets_v1.types.GetDatasetRequest, dict]]): - The request object. Request to get the specified dataset. - name (:class:`str`): - Required. Resource name. Format: - projects/{project}/datasets/{dataset_id} - - Can also fetch some special versions by appending "@" - and a tag. Format: - projects/{project}/datasets/{dataset_id}@{tag} - - Tag "active": The info of the latest completed version - will be included, and NOT_FOUND if the dataset does not - have one. - - 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.maps.mapsplatformdatasets_v1.types.Dataset: - A representation of a dataset - 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, maps_platform_datasets.GetDatasetRequest): - request = maps_platform_datasets.GetDatasetRequest(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_dataset] - - # Certain 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 fetch_dataset_errors(self, - request: Optional[Union[maps_platform_datasets.FetchDatasetErrorsRequest, dict]] = None, - *, - dataset: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.FetchDatasetErrorsAsyncPager: - r"""Gets all the errors of a dataset. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import mapsplatformdatasets_v1 - - async def sample_fetch_dataset_errors(): - # Create a client - client = mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient() - - # Initialize request argument(s) - request = mapsplatformdatasets_v1.FetchDatasetErrorsRequest( - dataset="dataset_value", - ) - - # Make the request - page_result = client.fetch_dataset_errors(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.maps.mapsplatformdatasets_v1.types.FetchDatasetErrorsRequest, dict]]): - The request object. Request to list detailed errors - belonging to a dataset. - dataset (:class:`str`): - Required. The name of the dataset to list all the errors - for. Format: projects/{project}/datasets/{dataset_id} - - This corresponds to the ``dataset`` 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.maps.mapsplatformdatasets_v1.services.maps_platform_datasets.pagers.FetchDatasetErrorsAsyncPager: - Response object of - FetchDatasetErrors. - 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. - has_flattened_params = any([dataset]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, maps_platform_datasets.FetchDatasetErrorsRequest): - request = maps_platform_datasets.FetchDatasetErrorsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if dataset is not None: - request.dataset = dataset - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.fetch_dataset_errors] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("dataset", request.dataset), - )), - ) - - # 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.FetchDatasetErrorsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_datasets(self, - request: Optional[Union[maps_platform_datasets.ListDatasetsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListDatasetsAsyncPager: - r"""Lists all the datasets for the specified project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import mapsplatformdatasets_v1 - - async def sample_list_datasets(): - # Create a client - client = mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient() - - # Initialize request argument(s) - request = mapsplatformdatasets_v1.ListDatasetsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_datasets(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.maps.mapsplatformdatasets_v1.types.ListDatasetsRequest, dict]]): - The request object. Request to list datasets for the - project. - parent (:class:`str`): - Required. The name of the project to - list all the datasets for. Format: - projects/{project} - - 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.maps.mapsplatformdatasets_v1.services.maps_platform_datasets.pagers.ListDatasetsAsyncPager: - Response object of ListDatasets. - - 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, maps_platform_datasets.ListDatasetsRequest): - request = maps_platform_datasets.ListDatasetsRequest(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_datasets] - - # Certain 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.ListDatasetsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_dataset(self, - request: Optional[Union[maps_platform_datasets.DeleteDatasetRequest, dict]] = None, - *, - name: Optional[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 dataset. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import mapsplatformdatasets_v1 - - async def sample_delete_dataset(): - # Create a client - client = mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient() - - # Initialize request argument(s) - request = mapsplatformdatasets_v1.DeleteDatasetRequest( - name="name_value", - ) - - # Make the request - await client.delete_dataset(request=request) - - Args: - request (Optional[Union[google.maps.mapsplatformdatasets_v1.types.DeleteDatasetRequest, dict]]): - The request object. Request to delete a dataset. - name (:class:`str`): - Required. The name of the dataset to delete. Format: - projects/{project}/datasets/{dataset_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`. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, maps_platform_datasets.DeleteDatasetRequest): - request = maps_platform_datasets.DeleteDatasetRequest(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_dataset] - - # Certain 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) -> "MapsPlatformDatasetsAsyncClient": - 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__) - - -__all__ = ( - "MapsPlatformDatasetsAsyncClient", -) diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/client.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/client.py deleted file mode 100644 index b26bc719eb07..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/client.py +++ /dev/null @@ -1,1271 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -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.maps.mapsplatformdatasets_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 - -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.maps.mapsplatformdatasets_v1.services.maps_platform_datasets import pagers -from google.maps.mapsplatformdatasets_v1.types import data_source -from google.maps.mapsplatformdatasets_v1.types import dataset -from google.maps.mapsplatformdatasets_v1.types import dataset as gmm_dataset -from google.maps.mapsplatformdatasets_v1.types import maps_platform_datasets -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from .transports.base import MapsPlatformDatasetsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import MapsPlatformDatasetsGrpcTransport -from .transports.grpc_asyncio import MapsPlatformDatasetsGrpcAsyncIOTransport -from .transports.rest import MapsPlatformDatasetsRestTransport - - -class MapsPlatformDatasetsClientMeta(type): - """Metaclass for the MapsPlatformDatasets 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[MapsPlatformDatasetsTransport]] - _transport_registry["grpc"] = MapsPlatformDatasetsGrpcTransport - _transport_registry["grpc_asyncio"] = MapsPlatformDatasetsGrpcAsyncIOTransport - _transport_registry["rest"] = MapsPlatformDatasetsRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[MapsPlatformDatasetsTransport]: - """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 MapsPlatformDatasetsClient(metaclass=MapsPlatformDatasetsClientMeta): - """Service definition for the Maps Platform Datasets 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 = "mapsplatformdatasets.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "mapsplatformdatasets.{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: - MapsPlatformDatasetsClient: 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: - MapsPlatformDatasetsClient: 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) -> MapsPlatformDatasetsTransport: - """Returns the transport used by the client instance. - - Returns: - MapsPlatformDatasetsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def dataset_path(project: str,dataset: str,) -> str: - """Returns a fully-qualified dataset string.""" - return "projects/{project}/datasets/{dataset}".format(project=project, dataset=dataset, ) - - @staticmethod - def parse_dataset_path(path: str) -> Dict[str,str]: - """Parses a dataset path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/datasets/(?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 = MapsPlatformDatasetsClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = MapsPlatformDatasetsClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = MapsPlatformDatasetsClient._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 = MapsPlatformDatasetsClient._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 - - @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, MapsPlatformDatasetsTransport, Callable[..., MapsPlatformDatasetsTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the maps platform datasets 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,MapsPlatformDatasetsTransport,Callable[..., MapsPlatformDatasetsTransport]]]): - 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 MapsPlatformDatasetsTransport 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 = MapsPlatformDatasetsClient._read_environment_variables() - self._client_cert_source = MapsPlatformDatasetsClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = MapsPlatformDatasetsClient._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, MapsPlatformDatasetsTransport) - if transport_provided: - # transport is a MapsPlatformDatasetsTransport 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(MapsPlatformDatasetsTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - MapsPlatformDatasetsClient._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[MapsPlatformDatasetsTransport], Callable[..., MapsPlatformDatasetsTransport]] = ( - MapsPlatformDatasetsClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., MapsPlatformDatasetsTransport], 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.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient`.", - extra = { - "serviceName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", - "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.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", - "credentialsType": None, - } - ) - - def create_dataset(self, - request: Optional[Union[maps_platform_datasets.CreateDatasetRequest, dict]] = None, - *, - parent: Optional[str] = None, - dataset: Optional[gmm_dataset.Dataset] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> gmm_dataset.Dataset: - r"""Creates a new dataset for the specified project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import mapsplatformdatasets_v1 - - def sample_create_dataset(): - # Create a client - client = mapsplatformdatasets_v1.MapsPlatformDatasetsClient() - - # Initialize request argument(s) - request = mapsplatformdatasets_v1.CreateDatasetRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_dataset(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.mapsplatformdatasets_v1.types.CreateDatasetRequest, dict]): - The request object. Request to create a maps dataset. - parent (str): - Required. Parent project that will - own the dataset. Format: - projects/{project} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - dataset (google.maps.mapsplatformdatasets_v1.types.Dataset): - Required. The dataset version to - create. - - This corresponds to the ``dataset`` 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.maps.mapsplatformdatasets_v1.types.Dataset: - A representation of a dataset - 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. - has_flattened_params = any([parent, dataset]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, maps_platform_datasets.CreateDatasetRequest): - request = maps_platform_datasets.CreateDatasetRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if dataset is not None: - request.dataset = dataset - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_dataset] - - # Certain 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_dataset_metadata(self, - request: Optional[Union[maps_platform_datasets.UpdateDatasetMetadataRequest, dict]] = None, - *, - dataset: Optional[gmm_dataset.Dataset] = 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]]] = (), - ) -> gmm_dataset.Dataset: - r"""Updates the metadata for the dataset. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import mapsplatformdatasets_v1 - - def sample_update_dataset_metadata(): - # Create a client - client = mapsplatformdatasets_v1.MapsPlatformDatasetsClient() - - # Initialize request argument(s) - request = mapsplatformdatasets_v1.UpdateDatasetMetadataRequest( - ) - - # Make the request - response = client.update_dataset_metadata(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.mapsplatformdatasets_v1.types.UpdateDatasetMetadataRequest, dict]): - The request object. Request to update the metadata fields - of the dataset. - dataset (google.maps.mapsplatformdatasets_v1.types.Dataset): - Required. Resource name of the dataset to update. - Format: projects/{project}/datasets/{dataset_id} - - This corresponds to the ``dataset`` 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. - - The value "*" is used for full replacement (default). - - 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.maps.mapsplatformdatasets_v1.types.Dataset: - A representation of a dataset - 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. - has_flattened_params = any([dataset, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, maps_platform_datasets.UpdateDatasetMetadataRequest): - request = maps_platform_datasets.UpdateDatasetMetadataRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if dataset is not None: - request.dataset = dataset - 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_dataset_metadata] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("dataset.name", request.dataset.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_dataset(self, - request: Optional[Union[maps_platform_datasets.GetDatasetRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> dataset.Dataset: - r"""Gets the dataset. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import mapsplatformdatasets_v1 - - def sample_get_dataset(): - # Create a client - client = mapsplatformdatasets_v1.MapsPlatformDatasetsClient() - - # Initialize request argument(s) - request = mapsplatformdatasets_v1.GetDatasetRequest( - name="name_value", - ) - - # Make the request - response = client.get_dataset(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.mapsplatformdatasets_v1.types.GetDatasetRequest, dict]): - The request object. Request to get the specified dataset. - name (str): - Required. Resource name. Format: - projects/{project}/datasets/{dataset_id} - - Can also fetch some special versions by appending "@" - and a tag. Format: - projects/{project}/datasets/{dataset_id}@{tag} - - Tag "active": The info of the latest completed version - will be included, and NOT_FOUND if the dataset does not - have one. - - 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.maps.mapsplatformdatasets_v1.types.Dataset: - A representation of a dataset - 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, maps_platform_datasets.GetDatasetRequest): - request = maps_platform_datasets.GetDatasetRequest(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_dataset] - - # Certain 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 fetch_dataset_errors(self, - request: Optional[Union[maps_platform_datasets.FetchDatasetErrorsRequest, dict]] = None, - *, - dataset: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.FetchDatasetErrorsPager: - r"""Gets all the errors of a dataset. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import mapsplatformdatasets_v1 - - def sample_fetch_dataset_errors(): - # Create a client - client = mapsplatformdatasets_v1.MapsPlatformDatasetsClient() - - # Initialize request argument(s) - request = mapsplatformdatasets_v1.FetchDatasetErrorsRequest( - dataset="dataset_value", - ) - - # Make the request - page_result = client.fetch_dataset_errors(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.maps.mapsplatformdatasets_v1.types.FetchDatasetErrorsRequest, dict]): - The request object. Request to list detailed errors - belonging to a dataset. - dataset (str): - Required. The name of the dataset to list all the errors - for. Format: projects/{project}/datasets/{dataset_id} - - This corresponds to the ``dataset`` 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.maps.mapsplatformdatasets_v1.services.maps_platform_datasets.pagers.FetchDatasetErrorsPager: - Response object of - FetchDatasetErrors. - 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. - has_flattened_params = any([dataset]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, maps_platform_datasets.FetchDatasetErrorsRequest): - request = maps_platform_datasets.FetchDatasetErrorsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if dataset is not None: - request.dataset = dataset - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.fetch_dataset_errors] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("dataset", request.dataset), - )), - ) - - # 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.FetchDatasetErrorsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_datasets(self, - request: Optional[Union[maps_platform_datasets.ListDatasetsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListDatasetsPager: - r"""Lists all the datasets for the specified project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import mapsplatformdatasets_v1 - - def sample_list_datasets(): - # Create a client - client = mapsplatformdatasets_v1.MapsPlatformDatasetsClient() - - # Initialize request argument(s) - request = mapsplatformdatasets_v1.ListDatasetsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_datasets(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.maps.mapsplatformdatasets_v1.types.ListDatasetsRequest, dict]): - The request object. Request to list datasets for the - project. - parent (str): - Required. The name of the project to - list all the datasets for. Format: - projects/{project} - - 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.maps.mapsplatformdatasets_v1.services.maps_platform_datasets.pagers.ListDatasetsPager: - Response object of ListDatasets. - - 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, maps_platform_datasets.ListDatasetsRequest): - request = maps_platform_datasets.ListDatasetsRequest(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_datasets] - - # Certain 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.ListDatasetsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_dataset(self, - request: Optional[Union[maps_platform_datasets.DeleteDatasetRequest, dict]] = None, - *, - name: Optional[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 dataset. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import mapsplatformdatasets_v1 - - def sample_delete_dataset(): - # Create a client - client = mapsplatformdatasets_v1.MapsPlatformDatasetsClient() - - # Initialize request argument(s) - request = mapsplatformdatasets_v1.DeleteDatasetRequest( - name="name_value", - ) - - # Make the request - client.delete_dataset(request=request) - - Args: - request (Union[google.maps.mapsplatformdatasets_v1.types.DeleteDatasetRequest, dict]): - The request object. Request to delete a dataset. - name (str): - Required. The name of the dataset to delete. Format: - projects/{project}/datasets/{dataset_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`. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, maps_platform_datasets.DeleteDatasetRequest): - request = maps_platform_datasets.DeleteDatasetRequest(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_dataset] - - # Certain 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) -> "MapsPlatformDatasetsClient": - 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__) - - -__all__ = ( - "MapsPlatformDatasetsClient", -) diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/pagers.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/pagers.py deleted file mode 100644 index 0d42c1f7844c..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/pagers.py +++ /dev/null @@ -1,307 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.mapsplatformdatasets_v1.types import dataset -from google.maps.mapsplatformdatasets_v1.types import maps_platform_datasets -from google.rpc import status_pb2 # type: ignore - - -class FetchDatasetErrorsPager: - """A pager for iterating through ``fetch_dataset_errors`` requests. - - This class thinly wraps an initial - :class:`google.maps.mapsplatformdatasets_v1.types.FetchDatasetErrorsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``errors`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``FetchDatasetErrors`` requests and continue to iterate - through the ``errors`` field on the - corresponding responses. - - All the usual :class:`google.maps.mapsplatformdatasets_v1.types.FetchDatasetErrorsResponse` - 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[..., maps_platform_datasets.FetchDatasetErrorsResponse], - request: maps_platform_datasets.FetchDatasetErrorsRequest, - response: maps_platform_datasets.FetchDatasetErrorsResponse, - *, - 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.maps.mapsplatformdatasets_v1.types.FetchDatasetErrorsRequest): - The initial request object. - response (google.maps.mapsplatformdatasets_v1.types.FetchDatasetErrorsResponse): - 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 = maps_platform_datasets.FetchDatasetErrorsRequest(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[maps_platform_datasets.FetchDatasetErrorsResponse]: - 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[status_pb2.Status]: - for page in self.pages: - yield from page.errors - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class FetchDatasetErrorsAsyncPager: - """A pager for iterating through ``fetch_dataset_errors`` requests. - - This class thinly wraps an initial - :class:`google.maps.mapsplatformdatasets_v1.types.FetchDatasetErrorsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``errors`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``FetchDatasetErrors`` requests and continue to iterate - through the ``errors`` field on the - corresponding responses. - - All the usual :class:`google.maps.mapsplatformdatasets_v1.types.FetchDatasetErrorsResponse` - 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[maps_platform_datasets.FetchDatasetErrorsResponse]], - request: maps_platform_datasets.FetchDatasetErrorsRequest, - response: maps_platform_datasets.FetchDatasetErrorsResponse, - *, - 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.maps.mapsplatformdatasets_v1.types.FetchDatasetErrorsRequest): - The initial request object. - response (google.maps.mapsplatformdatasets_v1.types.FetchDatasetErrorsResponse): - 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 = maps_platform_datasets.FetchDatasetErrorsRequest(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[maps_platform_datasets.FetchDatasetErrorsResponse]: - 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[status_pb2.Status]: - async def async_generator(): - async for page in self.pages: - for response in page.errors: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListDatasetsPager: - """A pager for iterating through ``list_datasets`` requests. - - This class thinly wraps an initial - :class:`google.maps.mapsplatformdatasets_v1.types.ListDatasetsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``datasets`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListDatasets`` requests and continue to iterate - through the ``datasets`` field on the - corresponding responses. - - All the usual :class:`google.maps.mapsplatformdatasets_v1.types.ListDatasetsResponse` - 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[..., maps_platform_datasets.ListDatasetsResponse], - request: maps_platform_datasets.ListDatasetsRequest, - response: maps_platform_datasets.ListDatasetsResponse, - *, - 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.maps.mapsplatformdatasets_v1.types.ListDatasetsRequest): - The initial request object. - response (google.maps.mapsplatformdatasets_v1.types.ListDatasetsResponse): - 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 = maps_platform_datasets.ListDatasetsRequest(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[maps_platform_datasets.ListDatasetsResponse]: - 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[dataset.Dataset]: - for page in self.pages: - yield from page.datasets - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListDatasetsAsyncPager: - """A pager for iterating through ``list_datasets`` requests. - - This class thinly wraps an initial - :class:`google.maps.mapsplatformdatasets_v1.types.ListDatasetsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``datasets`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListDatasets`` requests and continue to iterate - through the ``datasets`` field on the - corresponding responses. - - All the usual :class:`google.maps.mapsplatformdatasets_v1.types.ListDatasetsResponse` - 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[maps_platform_datasets.ListDatasetsResponse]], - request: maps_platform_datasets.ListDatasetsRequest, - response: maps_platform_datasets.ListDatasetsResponse, - *, - 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.maps.mapsplatformdatasets_v1.types.ListDatasetsRequest): - The initial request object. - response (google.maps.mapsplatformdatasets_v1.types.ListDatasetsResponse): - 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 = maps_platform_datasets.ListDatasetsRequest(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[maps_platform_datasets.ListDatasetsResponse]: - 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[dataset.Dataset]: - async def async_generator(): - async for page in self.pages: - for response in page.datasets: - 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-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/README.rst b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/README.rst deleted file mode 100644 index cb6fbe0110ae..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`MapsPlatformDatasetsTransport` is the ABC for all transports. -- public child `MapsPlatformDatasetsGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `MapsPlatformDatasetsGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseMapsPlatformDatasetsRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `MapsPlatformDatasetsRestTransport` 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-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/__init__.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/__init__.py deleted file mode 100644 index e3a3c8c168b4..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 MapsPlatformDatasetsTransport -from .grpc import MapsPlatformDatasetsGrpcTransport -from .grpc_asyncio import MapsPlatformDatasetsGrpcAsyncIOTransport -from .rest import MapsPlatformDatasetsRestTransport -from .rest import MapsPlatformDatasetsRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[MapsPlatformDatasetsTransport]] -_transport_registry['grpc'] = MapsPlatformDatasetsGrpcTransport -_transport_registry['grpc_asyncio'] = MapsPlatformDatasetsGrpcAsyncIOTransport -_transport_registry['rest'] = MapsPlatformDatasetsRestTransport - -__all__ = ( - 'MapsPlatformDatasetsTransport', - 'MapsPlatformDatasetsGrpcTransport', - 'MapsPlatformDatasetsGrpcAsyncIOTransport', - 'MapsPlatformDatasetsRestTransport', - 'MapsPlatformDatasetsRestInterceptor', -) diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/base.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/base.py deleted file mode 100644 index 1133740e976a..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/base.py +++ /dev/null @@ -1,254 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.mapsplatformdatasets_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 - -from google.maps.mapsplatformdatasets_v1.types import dataset -from google.maps.mapsplatformdatasets_v1.types import dataset as gmm_dataset -from google.maps.mapsplatformdatasets_v1.types import maps_platform_datasets -from google.protobuf import empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class MapsPlatformDatasetsTransport(abc.ABC): - """Abstract transport class for MapsPlatformDatasets.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'mapsplatformdatasets.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: 'mapsplatformdatasets.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to 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.create_dataset: gapic_v1.method.wrap_method( - self.create_dataset, - default_timeout=60.0, - client_info=client_info, - ), - self.update_dataset_metadata: gapic_v1.method.wrap_method( - self.update_dataset_metadata, - default_timeout=60.0, - client_info=client_info, - ), - self.get_dataset: gapic_v1.method.wrap_method( - self.get_dataset, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.fetch_dataset_errors: gapic_v1.method.wrap_method( - self.fetch_dataset_errors, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_datasets: gapic_v1.method.wrap_method( - self.list_datasets, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.delete_dataset: gapic_v1.method.wrap_method( - self.delete_dataset, - default_timeout=60.0, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def create_dataset(self) -> Callable[ - [maps_platform_datasets.CreateDatasetRequest], - Union[ - gmm_dataset.Dataset, - Awaitable[gmm_dataset.Dataset] - ]]: - raise NotImplementedError() - - @property - def update_dataset_metadata(self) -> Callable[ - [maps_platform_datasets.UpdateDatasetMetadataRequest], - Union[ - gmm_dataset.Dataset, - Awaitable[gmm_dataset.Dataset] - ]]: - raise NotImplementedError() - - @property - def get_dataset(self) -> Callable[ - [maps_platform_datasets.GetDatasetRequest], - Union[ - dataset.Dataset, - Awaitable[dataset.Dataset] - ]]: - raise NotImplementedError() - - @property - def fetch_dataset_errors(self) -> Callable[ - [maps_platform_datasets.FetchDatasetErrorsRequest], - Union[ - maps_platform_datasets.FetchDatasetErrorsResponse, - Awaitable[maps_platform_datasets.FetchDatasetErrorsResponse] - ]]: - raise NotImplementedError() - - @property - def list_datasets(self) -> Callable[ - [maps_platform_datasets.ListDatasetsRequest], - Union[ - maps_platform_datasets.ListDatasetsResponse, - Awaitable[maps_platform_datasets.ListDatasetsResponse] - ]]: - raise NotImplementedError() - - @property - def delete_dataset(self) -> Callable[ - [maps_platform_datasets.DeleteDatasetRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'MapsPlatformDatasetsTransport', -) diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/grpc.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/grpc.py deleted file mode 100644 index 81d8194aef59..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/grpc.py +++ /dev/null @@ -1,480 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.mapsplatformdatasets_v1.types import dataset -from google.maps.mapsplatformdatasets_v1.types import dataset as gmm_dataset -from google.maps.mapsplatformdatasets_v1.types import maps_platform_datasets -from google.protobuf import empty_pb2 # type: ignore -from .base import MapsPlatformDatasetsTransport, 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.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", - "rpcName": 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.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class MapsPlatformDatasetsGrpcTransport(MapsPlatformDatasetsTransport): - """gRPC backend transport for MapsPlatformDatasets. - - Service definition for the Maps Platform Datasets 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 = 'mapsplatformdatasets.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: 'mapsplatformdatasets.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to 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 = 'mapsplatformdatasets.googleapis.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 create_dataset(self) -> Callable[ - [maps_platform_datasets.CreateDatasetRequest], - gmm_dataset.Dataset]: - r"""Return a callable for the create dataset method over gRPC. - - Creates a new dataset for the specified project. - - Returns: - Callable[[~.CreateDatasetRequest], - ~.Dataset]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_dataset' not in self._stubs: - self._stubs['create_dataset'] = self._logged_channel.unary_unary( - '/google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets/CreateDataset', - request_serializer=maps_platform_datasets.CreateDatasetRequest.serialize, - response_deserializer=gmm_dataset.Dataset.deserialize, - ) - return self._stubs['create_dataset'] - - @property - def update_dataset_metadata(self) -> Callable[ - [maps_platform_datasets.UpdateDatasetMetadataRequest], - gmm_dataset.Dataset]: - r"""Return a callable for the update dataset metadata method over gRPC. - - Updates the metadata for the dataset. - - Returns: - Callable[[~.UpdateDatasetMetadataRequest], - ~.Dataset]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_dataset_metadata' not in self._stubs: - self._stubs['update_dataset_metadata'] = self._logged_channel.unary_unary( - '/google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets/UpdateDatasetMetadata', - request_serializer=maps_platform_datasets.UpdateDatasetMetadataRequest.serialize, - response_deserializer=gmm_dataset.Dataset.deserialize, - ) - return self._stubs['update_dataset_metadata'] - - @property - def get_dataset(self) -> Callable[ - [maps_platform_datasets.GetDatasetRequest], - dataset.Dataset]: - r"""Return a callable for the get dataset method over gRPC. - - Gets the dataset. - - Returns: - Callable[[~.GetDatasetRequest], - ~.Dataset]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_dataset' not in self._stubs: - self._stubs['get_dataset'] = self._logged_channel.unary_unary( - '/google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets/GetDataset', - request_serializer=maps_platform_datasets.GetDatasetRequest.serialize, - response_deserializer=dataset.Dataset.deserialize, - ) - return self._stubs['get_dataset'] - - @property - def fetch_dataset_errors(self) -> Callable[ - [maps_platform_datasets.FetchDatasetErrorsRequest], - maps_platform_datasets.FetchDatasetErrorsResponse]: - r"""Return a callable for the fetch dataset errors method over gRPC. - - Gets all the errors of a dataset. - - Returns: - Callable[[~.FetchDatasetErrorsRequest], - ~.FetchDatasetErrorsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'fetch_dataset_errors' not in self._stubs: - self._stubs['fetch_dataset_errors'] = self._logged_channel.unary_unary( - '/google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets/FetchDatasetErrors', - request_serializer=maps_platform_datasets.FetchDatasetErrorsRequest.serialize, - response_deserializer=maps_platform_datasets.FetchDatasetErrorsResponse.deserialize, - ) - return self._stubs['fetch_dataset_errors'] - - @property - def list_datasets(self) -> Callable[ - [maps_platform_datasets.ListDatasetsRequest], - maps_platform_datasets.ListDatasetsResponse]: - r"""Return a callable for the list datasets method over gRPC. - - Lists all the datasets for the specified project. - - Returns: - Callable[[~.ListDatasetsRequest], - ~.ListDatasetsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_datasets' not in self._stubs: - self._stubs['list_datasets'] = self._logged_channel.unary_unary( - '/google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets/ListDatasets', - request_serializer=maps_platform_datasets.ListDatasetsRequest.serialize, - response_deserializer=maps_platform_datasets.ListDatasetsResponse.deserialize, - ) - return self._stubs['list_datasets'] - - @property - def delete_dataset(self) -> Callable[ - [maps_platform_datasets.DeleteDatasetRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete dataset method over gRPC. - - Deletes the specified dataset. - - Returns: - Callable[[~.DeleteDatasetRequest], - ~.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_dataset' not in self._stubs: - self._stubs['delete_dataset'] = self._logged_channel.unary_unary( - '/google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets/DeleteDataset', - request_serializer=maps_platform_datasets.DeleteDatasetRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_dataset'] - - def close(self): - self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'MapsPlatformDatasetsGrpcTransport', -) diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/grpc_asyncio.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/grpc_asyncio.py deleted file mode 100644 index b8703b9c746d..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/grpc_asyncio.py +++ /dev/null @@ -1,552 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.mapsplatformdatasets_v1.types import dataset -from google.maps.mapsplatformdatasets_v1.types import dataset as gmm_dataset -from google.maps.mapsplatformdatasets_v1.types import maps_platform_datasets -from google.protobuf import empty_pb2 # type: ignore -from .base import MapsPlatformDatasetsTransport, DEFAULT_CLIENT_INFO -from .grpc import MapsPlatformDatasetsGrpcTransport - -try: - from google.api_core import client_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.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", - "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.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class MapsPlatformDatasetsGrpcAsyncIOTransport(MapsPlatformDatasetsTransport): - """gRPC AsyncIO backend transport for MapsPlatformDatasets. - - Service definition for the Maps Platform Datasets 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 = 'mapsplatformdatasets.googleapis.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 = 'mapsplatformdatasets.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: 'mapsplatformdatasets.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to 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 create_dataset(self) -> Callable[ - [maps_platform_datasets.CreateDatasetRequest], - Awaitable[gmm_dataset.Dataset]]: - r"""Return a callable for the create dataset method over gRPC. - - Creates a new dataset for the specified project. - - Returns: - Callable[[~.CreateDatasetRequest], - Awaitable[~.Dataset]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_dataset' not in self._stubs: - self._stubs['create_dataset'] = self._logged_channel.unary_unary( - '/google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets/CreateDataset', - request_serializer=maps_platform_datasets.CreateDatasetRequest.serialize, - response_deserializer=gmm_dataset.Dataset.deserialize, - ) - return self._stubs['create_dataset'] - - @property - def update_dataset_metadata(self) -> Callable[ - [maps_platform_datasets.UpdateDatasetMetadataRequest], - Awaitable[gmm_dataset.Dataset]]: - r"""Return a callable for the update dataset metadata method over gRPC. - - Updates the metadata for the dataset. - - Returns: - Callable[[~.UpdateDatasetMetadataRequest], - Awaitable[~.Dataset]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_dataset_metadata' not in self._stubs: - self._stubs['update_dataset_metadata'] = self._logged_channel.unary_unary( - '/google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets/UpdateDatasetMetadata', - request_serializer=maps_platform_datasets.UpdateDatasetMetadataRequest.serialize, - response_deserializer=gmm_dataset.Dataset.deserialize, - ) - return self._stubs['update_dataset_metadata'] - - @property - def get_dataset(self) -> Callable[ - [maps_platform_datasets.GetDatasetRequest], - Awaitable[dataset.Dataset]]: - r"""Return a callable for the get dataset method over gRPC. - - Gets the dataset. - - Returns: - Callable[[~.GetDatasetRequest], - Awaitable[~.Dataset]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_dataset' not in self._stubs: - self._stubs['get_dataset'] = self._logged_channel.unary_unary( - '/google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets/GetDataset', - request_serializer=maps_platform_datasets.GetDatasetRequest.serialize, - response_deserializer=dataset.Dataset.deserialize, - ) - return self._stubs['get_dataset'] - - @property - def fetch_dataset_errors(self) -> Callable[ - [maps_platform_datasets.FetchDatasetErrorsRequest], - Awaitable[maps_platform_datasets.FetchDatasetErrorsResponse]]: - r"""Return a callable for the fetch dataset errors method over gRPC. - - Gets all the errors of a dataset. - - Returns: - Callable[[~.FetchDatasetErrorsRequest], - Awaitable[~.FetchDatasetErrorsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'fetch_dataset_errors' not in self._stubs: - self._stubs['fetch_dataset_errors'] = self._logged_channel.unary_unary( - '/google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets/FetchDatasetErrors', - request_serializer=maps_platform_datasets.FetchDatasetErrorsRequest.serialize, - response_deserializer=maps_platform_datasets.FetchDatasetErrorsResponse.deserialize, - ) - return self._stubs['fetch_dataset_errors'] - - @property - def list_datasets(self) -> Callable[ - [maps_platform_datasets.ListDatasetsRequest], - Awaitable[maps_platform_datasets.ListDatasetsResponse]]: - r"""Return a callable for the list datasets method over gRPC. - - Lists all the datasets for the specified project. - - Returns: - Callable[[~.ListDatasetsRequest], - Awaitable[~.ListDatasetsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_datasets' not in self._stubs: - self._stubs['list_datasets'] = self._logged_channel.unary_unary( - '/google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets/ListDatasets', - request_serializer=maps_platform_datasets.ListDatasetsRequest.serialize, - response_deserializer=maps_platform_datasets.ListDatasetsResponse.deserialize, - ) - return self._stubs['list_datasets'] - - @property - def delete_dataset(self) -> Callable[ - [maps_platform_datasets.DeleteDatasetRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete dataset method over gRPC. - - Deletes the specified dataset. - - Returns: - Callable[[~.DeleteDatasetRequest], - 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_dataset' not in self._stubs: - self._stubs['delete_dataset'] = self._logged_channel.unary_unary( - '/google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets/DeleteDataset', - request_serializer=maps_platform_datasets.DeleteDatasetRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_dataset'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.create_dataset: self._wrap_method( - self.create_dataset, - default_timeout=60.0, - client_info=client_info, - ), - self.update_dataset_metadata: self._wrap_method( - self.update_dataset_metadata, - default_timeout=60.0, - client_info=client_info, - ), - self.get_dataset: self._wrap_method( - self.get_dataset, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.fetch_dataset_errors: self._wrap_method( - self.fetch_dataset_errors, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_datasets: self._wrap_method( - self.list_datasets, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.delete_dataset: self._wrap_method( - self.delete_dataset, - default_timeout=60.0, - 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__ = ( - 'MapsPlatformDatasetsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/rest.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/rest.py deleted file mode 100644 index 0a4d5499984d..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/rest.py +++ /dev/null @@ -1,1051 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -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.maps.mapsplatformdatasets_v1.types import dataset -from google.maps.mapsplatformdatasets_v1.types import dataset as gmm_dataset -from google.maps.mapsplatformdatasets_v1.types import maps_platform_datasets -from google.protobuf import empty_pb2 # type: ignore - - -from .rest_base import _BaseMapsPlatformDatasetsRestTransport -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}", -) - - -class MapsPlatformDatasetsRestInterceptor: - """Interceptor for MapsPlatformDatasets. - - 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 MapsPlatformDatasetsRestTransport. - - .. code-block:: python - class MyCustomMapsPlatformDatasetsInterceptor(MapsPlatformDatasetsRestInterceptor): - def pre_create_dataset(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_dataset(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_dataset(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_fetch_dataset_errors(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_fetch_dataset_errors(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_dataset(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_dataset(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_datasets(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_datasets(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_dataset_metadata(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_dataset_metadata(self, response): - logging.log(f"Received response: {response}") - return response - - transport = MapsPlatformDatasetsRestTransport(interceptor=MyCustomMapsPlatformDatasetsInterceptor()) - client = MapsPlatformDatasetsClient(transport=transport) - - - """ - def pre_create_dataset(self, request: maps_platform_datasets.CreateDatasetRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[maps_platform_datasets.CreateDatasetRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for create_dataset - - Override in a subclass to manipulate the request or metadata - before they are sent to the MapsPlatformDatasets server. - """ - return request, metadata - - def post_create_dataset(self, response: gmm_dataset.Dataset) -> gmm_dataset.Dataset: - """Post-rpc interceptor for create_dataset - - Override in a subclass to manipulate the response - after it is returned by the MapsPlatformDatasets server but before - it is returned to user code. - """ - return response - - def pre_delete_dataset(self, request: maps_platform_datasets.DeleteDatasetRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[maps_platform_datasets.DeleteDatasetRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_dataset - - Override in a subclass to manipulate the request or metadata - before they are sent to the MapsPlatformDatasets server. - """ - return request, metadata - - def pre_fetch_dataset_errors(self, request: maps_platform_datasets.FetchDatasetErrorsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[maps_platform_datasets.FetchDatasetErrorsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for fetch_dataset_errors - - Override in a subclass to manipulate the request or metadata - before they are sent to the MapsPlatformDatasets server. - """ - return request, metadata - - def post_fetch_dataset_errors(self, response: maps_platform_datasets.FetchDatasetErrorsResponse) -> maps_platform_datasets.FetchDatasetErrorsResponse: - """Post-rpc interceptor for fetch_dataset_errors - - Override in a subclass to manipulate the response - after it is returned by the MapsPlatformDatasets server but before - it is returned to user code. - """ - return response - - def pre_get_dataset(self, request: maps_platform_datasets.GetDatasetRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[maps_platform_datasets.GetDatasetRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_dataset - - Override in a subclass to manipulate the request or metadata - before they are sent to the MapsPlatformDatasets server. - """ - return request, metadata - - def post_get_dataset(self, response: dataset.Dataset) -> dataset.Dataset: - """Post-rpc interceptor for get_dataset - - Override in a subclass to manipulate the response - after it is returned by the MapsPlatformDatasets server but before - it is returned to user code. - """ - return response - - def pre_list_datasets(self, request: maps_platform_datasets.ListDatasetsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[maps_platform_datasets.ListDatasetsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_datasets - - Override in a subclass to manipulate the request or metadata - before they are sent to the MapsPlatformDatasets server. - """ - return request, metadata - - def post_list_datasets(self, response: maps_platform_datasets.ListDatasetsResponse) -> maps_platform_datasets.ListDatasetsResponse: - """Post-rpc interceptor for list_datasets - - Override in a subclass to manipulate the response - after it is returned by the MapsPlatformDatasets server but before - it is returned to user code. - """ - return response - - def pre_update_dataset_metadata(self, request: maps_platform_datasets.UpdateDatasetMetadataRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[maps_platform_datasets.UpdateDatasetMetadataRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for update_dataset_metadata - - Override in a subclass to manipulate the request or metadata - before they are sent to the MapsPlatformDatasets server. - """ - return request, metadata - - def post_update_dataset_metadata(self, response: gmm_dataset.Dataset) -> gmm_dataset.Dataset: - """Post-rpc interceptor for update_dataset_metadata - - Override in a subclass to manipulate the response - after it is returned by the MapsPlatformDatasets server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class MapsPlatformDatasetsRestStub: - _session: AuthorizedSession - _host: str - _interceptor: MapsPlatformDatasetsRestInterceptor - - -class MapsPlatformDatasetsRestTransport(_BaseMapsPlatformDatasetsRestTransport): - """REST backend synchronous transport for MapsPlatformDatasets. - - Service definition for the Maps Platform Datasets 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 = 'mapsplatformdatasets.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[MapsPlatformDatasetsRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'mapsplatformdatasets.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to 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 MapsPlatformDatasetsRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _CreateDataset(_BaseMapsPlatformDatasetsRestTransport._BaseCreateDataset, MapsPlatformDatasetsRestStub): - def __hash__(self): - return hash("MapsPlatformDatasetsRestTransport.CreateDataset") - - @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: maps_platform_datasets.CreateDatasetRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> gmm_dataset.Dataset: - r"""Call the create dataset method over HTTP. - - Args: - request (~.maps_platform_datasets.CreateDatasetRequest): - The request object. Request to create a maps dataset. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.gmm_dataset.Dataset: - A representation of a dataset - resource. - - """ - - http_options = _BaseMapsPlatformDatasetsRestTransport._BaseCreateDataset._get_http_options() - - request, metadata = self._interceptor.pre_create_dataset(request, metadata) - transcoded_request = _BaseMapsPlatformDatasetsRestTransport._BaseCreateDataset._get_transcoded_request(http_options, request) - - body = _BaseMapsPlatformDatasetsRestTransport._BaseCreateDataset._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseMapsPlatformDatasetsRestTransport._BaseCreateDataset._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient.CreateDataset", - extra = { - "serviceName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", - "rpcName": "CreateDataset", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = MapsPlatformDatasetsRestTransport._CreateDataset._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 = gmm_dataset.Dataset() - pb_resp = gmm_dataset.Dataset.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_create_dataset(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = gmm_dataset.Dataset.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.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient.create_dataset", - extra = { - "serviceName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", - "rpcName": "CreateDataset", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _DeleteDataset(_BaseMapsPlatformDatasetsRestTransport._BaseDeleteDataset, MapsPlatformDatasetsRestStub): - def __hash__(self): - return hash("MapsPlatformDatasetsRestTransport.DeleteDataset") - - @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: maps_platform_datasets.DeleteDatasetRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ): - r"""Call the delete dataset method over HTTP. - - Args: - request (~.maps_platform_datasets.DeleteDatasetRequest): - The request object. Request to delete a dataset. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, 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 = _BaseMapsPlatformDatasetsRestTransport._BaseDeleteDataset._get_http_options() - - request, metadata = self._interceptor.pre_delete_dataset(request, metadata) - transcoded_request = _BaseMapsPlatformDatasetsRestTransport._BaseDeleteDataset._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseMapsPlatformDatasetsRestTransport._BaseDeleteDataset._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(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.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient.DeleteDataset", - extra = { - "serviceName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", - "rpcName": "DeleteDataset", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = MapsPlatformDatasetsRestTransport._DeleteDataset._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 _FetchDatasetErrors(_BaseMapsPlatformDatasetsRestTransport._BaseFetchDatasetErrors, MapsPlatformDatasetsRestStub): - def __hash__(self): - return hash("MapsPlatformDatasetsRestTransport.FetchDatasetErrors") - - @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: maps_platform_datasets.FetchDatasetErrorsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> maps_platform_datasets.FetchDatasetErrorsResponse: - r"""Call the fetch dataset errors method over HTTP. - - Args: - request (~.maps_platform_datasets.FetchDatasetErrorsRequest): - The request object. Request to list detailed errors - belonging to a dataset. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.maps_platform_datasets.FetchDatasetErrorsResponse: - Response object of - FetchDatasetErrors. - - """ - - http_options = _BaseMapsPlatformDatasetsRestTransport._BaseFetchDatasetErrors._get_http_options() - - request, metadata = self._interceptor.pre_fetch_dataset_errors(request, metadata) - transcoded_request = _BaseMapsPlatformDatasetsRestTransport._BaseFetchDatasetErrors._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseMapsPlatformDatasetsRestTransport._BaseFetchDatasetErrors._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient.FetchDatasetErrors", - extra = { - "serviceName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", - "rpcName": "FetchDatasetErrors", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = MapsPlatformDatasetsRestTransport._FetchDatasetErrors._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 = maps_platform_datasets.FetchDatasetErrorsResponse() - pb_resp = maps_platform_datasets.FetchDatasetErrorsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_fetch_dataset_errors(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = maps_platform_datasets.FetchDatasetErrorsResponse.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.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient.fetch_dataset_errors", - extra = { - "serviceName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", - "rpcName": "FetchDatasetErrors", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetDataset(_BaseMapsPlatformDatasetsRestTransport._BaseGetDataset, MapsPlatformDatasetsRestStub): - def __hash__(self): - return hash("MapsPlatformDatasetsRestTransport.GetDataset") - - @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: maps_platform_datasets.GetDatasetRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> dataset.Dataset: - r"""Call the get dataset method over HTTP. - - Args: - request (~.maps_platform_datasets.GetDatasetRequest): - The request object. Request to get the specified dataset. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.dataset.Dataset: - A representation of a dataset - resource. - - """ - - http_options = _BaseMapsPlatformDatasetsRestTransport._BaseGetDataset._get_http_options() - - request, metadata = self._interceptor.pre_get_dataset(request, metadata) - transcoded_request = _BaseMapsPlatformDatasetsRestTransport._BaseGetDataset._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseMapsPlatformDatasetsRestTransport._BaseGetDataset._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient.GetDataset", - extra = { - "serviceName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", - "rpcName": "GetDataset", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = MapsPlatformDatasetsRestTransport._GetDataset._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 = dataset.Dataset() - pb_resp = dataset.Dataset.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_dataset(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = dataset.Dataset.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.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient.get_dataset", - extra = { - "serviceName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", - "rpcName": "GetDataset", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListDatasets(_BaseMapsPlatformDatasetsRestTransport._BaseListDatasets, MapsPlatformDatasetsRestStub): - def __hash__(self): - return hash("MapsPlatformDatasetsRestTransport.ListDatasets") - - @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: maps_platform_datasets.ListDatasetsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> maps_platform_datasets.ListDatasetsResponse: - r"""Call the list datasets method over HTTP. - - Args: - request (~.maps_platform_datasets.ListDatasetsRequest): - The request object. Request to list datasets for the - project. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.maps_platform_datasets.ListDatasetsResponse: - Response object of ListDatasets. - """ - - http_options = _BaseMapsPlatformDatasetsRestTransport._BaseListDatasets._get_http_options() - - request, metadata = self._interceptor.pre_list_datasets(request, metadata) - transcoded_request = _BaseMapsPlatformDatasetsRestTransport._BaseListDatasets._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseMapsPlatformDatasetsRestTransport._BaseListDatasets._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient.ListDatasets", - extra = { - "serviceName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", - "rpcName": "ListDatasets", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = MapsPlatformDatasetsRestTransport._ListDatasets._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 = maps_platform_datasets.ListDatasetsResponse() - pb_resp = maps_platform_datasets.ListDatasetsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_datasets(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = maps_platform_datasets.ListDatasetsResponse.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.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient.list_datasets", - extra = { - "serviceName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", - "rpcName": "ListDatasets", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UpdateDatasetMetadata(_BaseMapsPlatformDatasetsRestTransport._BaseUpdateDatasetMetadata, MapsPlatformDatasetsRestStub): - def __hash__(self): - return hash("MapsPlatformDatasetsRestTransport.UpdateDatasetMetadata") - - @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: maps_platform_datasets.UpdateDatasetMetadataRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> gmm_dataset.Dataset: - r"""Call the update dataset metadata method over HTTP. - - Args: - request (~.maps_platform_datasets.UpdateDatasetMetadataRequest): - The request object. Request to update the metadata fields - of the dataset. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.gmm_dataset.Dataset: - A representation of a dataset - resource. - - """ - - http_options = _BaseMapsPlatformDatasetsRestTransport._BaseUpdateDatasetMetadata._get_http_options() - - request, metadata = self._interceptor.pre_update_dataset_metadata(request, metadata) - transcoded_request = _BaseMapsPlatformDatasetsRestTransport._BaseUpdateDatasetMetadata._get_transcoded_request(http_options, request) - - body = _BaseMapsPlatformDatasetsRestTransport._BaseUpdateDatasetMetadata._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseMapsPlatformDatasetsRestTransport._BaseUpdateDatasetMetadata._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient.UpdateDatasetMetadata", - extra = { - "serviceName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", - "rpcName": "UpdateDatasetMetadata", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = MapsPlatformDatasetsRestTransport._UpdateDatasetMetadata._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 = gmm_dataset.Dataset() - pb_resp = gmm_dataset.Dataset.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_update_dataset_metadata(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = gmm_dataset.Dataset.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.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient.update_dataset_metadata", - extra = { - "serviceName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", - "rpcName": "UpdateDatasetMetadata", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def create_dataset(self) -> Callable[ - [maps_platform_datasets.CreateDatasetRequest], - gmm_dataset.Dataset]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateDataset(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_dataset(self) -> Callable[ - [maps_platform_datasets.DeleteDatasetRequest], - 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._DeleteDataset(self._session, self._host, self._interceptor) # type: ignore - - @property - def fetch_dataset_errors(self) -> Callable[ - [maps_platform_datasets.FetchDatasetErrorsRequest], - maps_platform_datasets.FetchDatasetErrorsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._FetchDatasetErrors(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_dataset(self) -> Callable[ - [maps_platform_datasets.GetDatasetRequest], - dataset.Dataset]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetDataset(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_datasets(self) -> Callable[ - [maps_platform_datasets.ListDatasetsRequest], - maps_platform_datasets.ListDatasetsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListDatasets(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_dataset_metadata(self) -> Callable[ - [maps_platform_datasets.UpdateDatasetMetadataRequest], - gmm_dataset.Dataset]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateDatasetMetadata(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'MapsPlatformDatasetsRestTransport', -) diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/rest_base.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/rest_base.py deleted file mode 100644 index 464ab2674fce..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/rest_base.py +++ /dev/null @@ -1,336 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 MapsPlatformDatasetsTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.maps.mapsplatformdatasets_v1.types import dataset -from google.maps.mapsplatformdatasets_v1.types import dataset as gmm_dataset -from google.maps.mapsplatformdatasets_v1.types import maps_platform_datasets -from google.protobuf import empty_pb2 # type: ignore - - -class _BaseMapsPlatformDatasetsRestTransport(MapsPlatformDatasetsTransport): - """Base REST backend transport for MapsPlatformDatasets. - - 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 = 'mapsplatformdatasets.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: 'mapsplatformdatasets.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 _BaseCreateDataset: - 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': '/v1/{parent=projects/*}/datasets', - 'body': 'dataset', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = maps_platform_datasets.CreateDatasetRequest.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(_BaseMapsPlatformDatasetsRestTransport._BaseCreateDataset._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteDataset: - 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': '/v1/{name=projects/*/datasets/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = maps_platform_datasets.DeleteDatasetRequest.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(_BaseMapsPlatformDatasetsRestTransport._BaseDeleteDataset._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseFetchDatasetErrors: - 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': '/v1/{dataset=projects/*/datasets/*}:fetchDatasetErrors', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = maps_platform_datasets.FetchDatasetErrorsRequest.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(_BaseMapsPlatformDatasetsRestTransport._BaseFetchDatasetErrors._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetDataset: - 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': '/v1/{name=projects/*/datasets/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = maps_platform_datasets.GetDatasetRequest.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(_BaseMapsPlatformDatasetsRestTransport._BaseGetDataset._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListDatasets: - 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': '/v1/{parent=projects/*}/datasets', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = maps_platform_datasets.ListDatasetsRequest.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(_BaseMapsPlatformDatasetsRestTransport._BaseListDatasets._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateDatasetMetadata: - 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': '/v1/{dataset.name=projects/*/datasets/*}', - 'body': 'dataset', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = maps_platform_datasets.UpdateDatasetMetadataRequest.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(_BaseMapsPlatformDatasetsRestTransport._BaseUpdateDatasetMetadata._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseMapsPlatformDatasetsRestTransport', -) diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/types/__init__.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/types/__init__.py deleted file mode 100644 index 64e0edf7cc91..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/types/__init__.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .data_source import ( - GcsSource, - LocalFileSource, - FileFormat, -) -from .dataset import ( - Dataset, - Status, - Usage, -) -from .maps_platform_datasets import ( - CreateDatasetRequest, - DeleteDatasetRequest, - FetchDatasetErrorsRequest, - FetchDatasetErrorsResponse, - GetDatasetRequest, - ListDatasetsRequest, - ListDatasetsResponse, - UpdateDatasetMetadataRequest, -) - -__all__ = ( - 'GcsSource', - 'LocalFileSource', - 'FileFormat', - 'Dataset', - 'Status', - 'Usage', - 'CreateDatasetRequest', - 'DeleteDatasetRequest', - 'FetchDatasetErrorsRequest', - 'FetchDatasetErrorsResponse', - 'GetDatasetRequest', - 'ListDatasetsRequest', - 'ListDatasetsResponse', - 'UpdateDatasetMetadataRequest', -) diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/types/data_source.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/types/data_source.py deleted file mode 100644 index 6957a23d1849..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/types/data_source.py +++ /dev/null @@ -1,97 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.mapsplatformdatasets.v1', - manifest={ - 'FileFormat', - 'LocalFileSource', - 'GcsSource', - }, -) - - -class FileFormat(proto.Enum): - r"""The format of the file being uploaded. - - Values: - FILE_FORMAT_UNSPECIFIED (0): - Unspecified file format. - FILE_FORMAT_GEOJSON (1): - GeoJson file. - FILE_FORMAT_KML (2): - KML file. - FILE_FORMAT_CSV (3): - CSV file. - """ - FILE_FORMAT_UNSPECIFIED = 0 - FILE_FORMAT_GEOJSON = 1 - FILE_FORMAT_KML = 2 - FILE_FORMAT_CSV = 3 - - -class LocalFileSource(proto.Message): - r"""The details about the data source when it is a local file. - - Attributes: - filename (str): - The file name of the uploaded file. - file_format (google.maps.mapsplatformdatasets_v1.types.FileFormat): - The format of the file that is being - uploaded. - """ - - filename: str = proto.Field( - proto.STRING, - number=1, - ) - file_format: 'FileFormat' = proto.Field( - proto.ENUM, - number=2, - enum='FileFormat', - ) - - -class GcsSource(proto.Message): - r"""The details about the data source when it is in Google Cloud - Storage. - - Attributes: - input_uri (str): - Source data URI. For example, ``gs://my_bucket/my_object``. - file_format (google.maps.mapsplatformdatasets_v1.types.FileFormat): - The file format of the Google Cloud Storage - object. This is used mainly for validation. - """ - - input_uri: str = proto.Field( - proto.STRING, - number=1, - ) - file_format: 'FileFormat' = proto.Field( - proto.ENUM, - number=2, - enum='FileFormat', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/types/dataset.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/types/dataset.py deleted file mode 100644 index 712ba7ac6361..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/types/dataset.py +++ /dev/null @@ -1,236 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.mapsplatformdatasets_v1.types import data_source -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.mapsplatformdatasets.v1', - manifest={ - 'Usage', - 'Dataset', - 'Status', - }, -) - - -class Usage(proto.Enum): - r"""Usage specifies where the data is intended to be used to - inform how to process the data. - - Values: - USAGE_UNSPECIFIED (0): - The usage of this dataset is not set. - USAGE_DATA_DRIVEN_STYLING (1): - This dataset will be used for data driven - styling. - """ - USAGE_UNSPECIFIED = 0 - USAGE_DATA_DRIVEN_STYLING = 1 - - -class Dataset(proto.Message): - r"""A representation of a dataset resource. - - 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: - name (str): - Resource name. Format: - projects/{project}/datasets/{dataset_id} - display_name (str): - Human readable name, shown in the console UI. - - Must be unique within a project. - description (str): - A description of this dataset. - version_id (str): - The version ID of the dataset. - usage (MutableSequence[google.maps.mapsplatformdatasets_v1.types.Usage]): - Specified use case for this dataset. - local_file_source (google.maps.mapsplatformdatasets_v1.types.LocalFileSource): - A local file source for the dataset for a - single upload. - - This field is a member of `oneof`_ ``data_source``. - gcs_source (google.maps.mapsplatformdatasets_v1.types.GcsSource): - A Google Cloud Storage file source for the - dataset for a single upload. - - This field is a member of `oneof`_ ``data_source``. - status (google.maps.mapsplatformdatasets_v1.types.Status): - Output only. The status of this dataset - version. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when the dataset was first - created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when the dataset metadata - was last updated. - version_create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when this version was - created. - version_description (str): - Output only. The description for this version - of dataset. It is provided when importing data - to the dataset. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - description: str = proto.Field( - proto.STRING, - number=3, - ) - version_id: str = proto.Field( - proto.STRING, - number=4, - ) - usage: MutableSequence['Usage'] = proto.RepeatedField( - proto.ENUM, - number=5, - enum='Usage', - ) - local_file_source: data_source.LocalFileSource = proto.Field( - proto.MESSAGE, - number=6, - oneof='data_source', - message=data_source.LocalFileSource, - ) - gcs_source: data_source.GcsSource = proto.Field( - proto.MESSAGE, - number=7, - oneof='data_source', - message=data_source.GcsSource, - ) - status: 'Status' = proto.Field( - proto.MESSAGE, - number=12, - message='Status', - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=8, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - version_create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - version_description: str = proto.Field( - proto.STRING, - number=11, - ) - - -class Status(proto.Message): - r"""Status of the dataset. - - Attributes: - state (google.maps.mapsplatformdatasets_v1.types.Status.State): - State enum for status. - error_message (str): - Error message indicating reason of failure. - It is empty if the datasets is not in a failed - state. - """ - class State(proto.Enum): - r"""A list of states for the dataset. - - Values: - STATE_UNSPECIFIED (0): - The state of this dataset is not set. - STATE_IMPORTING (1): - Data is being imported to a dataset. - STATE_IMPORT_SUCCEEDED (2): - Importing data to a dataset succeeded. - STATE_IMPORT_FAILED (3): - Importing data to a dataset failed. - STATE_DELETING (4): - The dataset is in the process of getting - deleted. - STATE_DELETION_FAILED (5): - The deletion failed state. This state - represents that dataset deletion has failed. - Deletion may be retried. - STATE_PROCESSING (6): - Data is being processed. - STATE_PROCESSING_FAILED (7): - The processing failed state. This state - represents that processing has failed and may - report errors. - STATE_NEEDS_REVIEW (8): - This state is currently not used. - STATE_PUBLISHING (9): - The publishing state. This state represents - the publishing is in progress. - STATE_PUBLISHING_FAILED (10): - The publishing failed states. This state - represents that the publishing failed. - Publishing may be retried. - STATE_COMPLETED (11): - The completed state. This state represents - the dataset being available for its specific - usage. - """ - STATE_UNSPECIFIED = 0 - STATE_IMPORTING = 1 - STATE_IMPORT_SUCCEEDED = 2 - STATE_IMPORT_FAILED = 3 - STATE_DELETING = 4 - STATE_DELETION_FAILED = 5 - STATE_PROCESSING = 6 - STATE_PROCESSING_FAILED = 7 - STATE_NEEDS_REVIEW = 8 - STATE_PUBLISHING = 9 - STATE_PUBLISHING_FAILED = 10 - STATE_COMPLETED = 11 - - state: State = proto.Field( - proto.ENUM, - number=1, - enum=State, - ) - error_message: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/types/maps_platform_datasets.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/types/maps_platform_datasets.py deleted file mode 100644 index df36e87d1582..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/types/maps_platform_datasets.py +++ /dev/null @@ -1,265 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.mapsplatformdatasets_v1.types import dataset as gmm_dataset -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.mapsplatformdatasets.v1', - manifest={ - 'CreateDatasetRequest', - 'UpdateDatasetMetadataRequest', - 'GetDatasetRequest', - 'ListDatasetsRequest', - 'ListDatasetsResponse', - 'FetchDatasetErrorsRequest', - 'FetchDatasetErrorsResponse', - 'DeleteDatasetRequest', - }, -) - - -class CreateDatasetRequest(proto.Message): - r"""Request to create a maps dataset. - - Attributes: - parent (str): - Required. Parent project that will own the - dataset. Format: projects/{project} - dataset (google.maps.mapsplatformdatasets_v1.types.Dataset): - Required. The dataset version to create. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - dataset: gmm_dataset.Dataset = proto.Field( - proto.MESSAGE, - number=2, - message=gmm_dataset.Dataset, - ) - - -class UpdateDatasetMetadataRequest(proto.Message): - r"""Request to update the metadata fields of the dataset. - - Attributes: - dataset (google.maps.mapsplatformdatasets_v1.types.Dataset): - Required. Resource name of the dataset to update. Format: - projects/{project}/datasets/{dataset_id} - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The list of fields to be updated. - - The value "*" is used for full replacement (default). - """ - - dataset: gmm_dataset.Dataset = proto.Field( - proto.MESSAGE, - number=1, - message=gmm_dataset.Dataset, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class GetDatasetRequest(proto.Message): - r"""Request to get the specified dataset. - - Attributes: - name (str): - Required. Resource name. Format: - projects/{project}/datasets/{dataset_id} - - Can also fetch some special versions by appending "@" and a - tag. Format: projects/{project}/datasets/{dataset_id}@{tag} - - Tag "active": The info of the latest completed version will - be included, and NOT_FOUND if the dataset does not have one. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListDatasetsRequest(proto.Message): - r"""Request to list datasets for the project. - - Attributes: - parent (str): - Required. The name of the project to list all - the datasets for. Format: projects/{project} - page_size (int): - The maximum number of datasets to return per - page. - If unspecified (or zero), all datasets will be - returned. - page_token (str): - The page token, received from a previous - ListDatasets call. Provide this to retrieve the - subsequent page. - tag (str): - The tag that specifies the desired version - for each dataset. - Note that when pagination is also specified, - some filtering can happen after pagination, - which may cause the response to contain fewer - datasets than the page size, even if it's not - the last page. - - Tag "active": Each dataset in the response will - include the info of its latest completed - version, and the dataset will be skipped if it - does not have one. - """ - - 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, - ) - tag: str = proto.Field( - proto.STRING, - number=4, - ) - - -class ListDatasetsResponse(proto.Message): - r"""Response object of ListDatasets. - - Attributes: - datasets (MutableSequence[google.maps.mapsplatformdatasets_v1.types.Dataset]): - All the datasets for the project. - 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 - - datasets: MutableSequence[gmm_dataset.Dataset] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gmm_dataset.Dataset, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class FetchDatasetErrorsRequest(proto.Message): - r"""Request to list detailed errors belonging to a dataset. - - Attributes: - dataset (str): - Required. The name of the dataset to list all the errors - for. Format: projects/{project}/datasets/{dataset_id} - page_size (int): - The maximum number of errors to return per - page. - The maximum value is 500; values above 500 will - be capped to 500. - - If unspecified, at most 50 errors will be - returned. - page_token (str): - The page token, received from a previous - ListDatasetErrors call. Provide this to retrieve - the subsequent page. - """ - - dataset: 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 FetchDatasetErrorsResponse(proto.Message): - r"""Response object of FetchDatasetErrors. - - Attributes: - 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. - errors (MutableSequence[google.rpc.status_pb2.Status]): - The errors associated with a dataset. - """ - - @property - def raw_page(self): - return self - - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - errors: MutableSequence[status_pb2.Status] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=status_pb2.Status, - ) - - -class DeleteDatasetRequest(proto.Message): - r"""Request to delete a dataset. - - Attributes: - name (str): - Required. The name of the dataset to delete. Format: - projects/{project}/datasets/{dataset_id} - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/types/maps_platform_datasets_service.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/types/maps_platform_datasets_service.py deleted file mode 100644 index 4224501e4543..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/types/maps_platform_datasets_service.py +++ /dev/null @@ -1,26 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.mapsplatformdatasets.v1', - manifest={ - }, -) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/mypy.ini b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/noxfile.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/noxfile.py deleted file mode 100644 index 3d09ce6c0f5a..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/noxfile.py +++ /dev/null @@ -1,280 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", - "3.12", - "3.13", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = 'google-maps-mapsplatformdatasets' - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.13" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "prerelease_deps", -] - -@nox.session(python=ALL_PYTHON) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def unit(session, protobuf_implementation): - """Run the unit test suite.""" - - 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+") - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") - - # 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") - - session.run( - 'py.test', - '--quiet', - '--cov=google/maps/mapsplatformdatasets_v1/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - -@nox.session(python=ALL_PYTHON[-1]) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def prerelease_deps(session, protobuf_implementation): - """Run the unit test suite against pre-release versions of dependencies.""" - - 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 test environment dependencies - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - - # Install the package without dependencies - session.install('-e', '.', '--no-deps') - - # We test the minimum dependency versions using the minimum Python - # version so the lowest python runtime that we test has a corresponding constraints - # file, located at `testing/constraints--.txt`, which contains all of the - # 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 - ) - ] - - session.install(*constraints_deps) - - prerel_deps = [ - "googleapis-common-protos", - "google-api-core", - "google-auth", - # Exclude grpcio!=1.67.0rc1 which does not support python 3.13 - "grpcio!=1.67.0rc1", - "grpcio-status", - "protobuf", - "proto-plus", - ] - - for dep in prerel_deps: - session.install("--pre", "--no-deps", "--upgrade", dep) - - # Remaining dependencies - other_deps = [ - "requests", - ] - session.install(*other_deps) - - # Print out prerelease package versions - - session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") - session.run("python", "-c", "import google.auth; print(google.auth.__version__)") - session.run("python", "-c", "import grpc; print(grpc.__version__)") - session.run( - "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" - ) - session.run( - "python", "-c", "import proto; print(proto.__version__)" - ) - - session.run( - 'py.test', - '--quiet', - '--cov=google/maps/mapsplatformdatasets_v1/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - - -@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=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 docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==7.0.1", "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=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", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_create_dataset_async.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_create_dataset_async.py deleted file mode 100644 index 5b50f1a1217e..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_create_dataset_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateDataset -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-mapsplatformdatasets - - -# [START mapsplatformdatasets_v1_generated_MapsPlatformDatasets_CreateDataset_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.maps import mapsplatformdatasets_v1 - - -async def sample_create_dataset(): - # Create a client - client = mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient() - - # Initialize request argument(s) - request = mapsplatformdatasets_v1.CreateDatasetRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_dataset(request=request) - - # Handle the response - print(response) - -# [END mapsplatformdatasets_v1_generated_MapsPlatformDatasets_CreateDataset_async] diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_create_dataset_sync.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_create_dataset_sync.py deleted file mode 100644 index 2df3d5dbcf12..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_create_dataset_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateDataset -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-mapsplatformdatasets - - -# [START mapsplatformdatasets_v1_generated_MapsPlatformDatasets_CreateDataset_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.maps import mapsplatformdatasets_v1 - - -def sample_create_dataset(): - # Create a client - client = mapsplatformdatasets_v1.MapsPlatformDatasetsClient() - - # Initialize request argument(s) - request = mapsplatformdatasets_v1.CreateDatasetRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_dataset(request=request) - - # Handle the response - print(response) - -# [END mapsplatformdatasets_v1_generated_MapsPlatformDatasets_CreateDataset_sync] diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_delete_dataset_async.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_delete_dataset_async.py deleted file mode 100644 index b290ae5be047..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_delete_dataset_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteDataset -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-mapsplatformdatasets - - -# [START mapsplatformdatasets_v1_generated_MapsPlatformDatasets_DeleteDataset_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.maps import mapsplatformdatasets_v1 - - -async def sample_delete_dataset(): - # Create a client - client = mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient() - - # Initialize request argument(s) - request = mapsplatformdatasets_v1.DeleteDatasetRequest( - name="name_value", - ) - - # Make the request - await client.delete_dataset(request=request) - - -# [END mapsplatformdatasets_v1_generated_MapsPlatformDatasets_DeleteDataset_async] diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_delete_dataset_sync.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_delete_dataset_sync.py deleted file mode 100644 index c7179f4147ac..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_delete_dataset_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteDataset -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-mapsplatformdatasets - - -# [START mapsplatformdatasets_v1_generated_MapsPlatformDatasets_DeleteDataset_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.maps import mapsplatformdatasets_v1 - - -def sample_delete_dataset(): - # Create a client - client = mapsplatformdatasets_v1.MapsPlatformDatasetsClient() - - # Initialize request argument(s) - request = mapsplatformdatasets_v1.DeleteDatasetRequest( - name="name_value", - ) - - # Make the request - client.delete_dataset(request=request) - - -# [END mapsplatformdatasets_v1_generated_MapsPlatformDatasets_DeleteDataset_sync] diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_fetch_dataset_errors_async.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_fetch_dataset_errors_async.py deleted file mode 100644 index 993b9aa8fe4e..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_fetch_dataset_errors_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for FetchDatasetErrors -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-mapsplatformdatasets - - -# [START mapsplatformdatasets_v1_generated_MapsPlatformDatasets_FetchDatasetErrors_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.maps import mapsplatformdatasets_v1 - - -async def sample_fetch_dataset_errors(): - # Create a client - client = mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient() - - # Initialize request argument(s) - request = mapsplatformdatasets_v1.FetchDatasetErrorsRequest( - dataset="dataset_value", - ) - - # Make the request - page_result = client.fetch_dataset_errors(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END mapsplatformdatasets_v1_generated_MapsPlatformDatasets_FetchDatasetErrors_async] diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_fetch_dataset_errors_sync.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_fetch_dataset_errors_sync.py deleted file mode 100644 index 644e0a562566..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_fetch_dataset_errors_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for FetchDatasetErrors -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-mapsplatformdatasets - - -# [START mapsplatformdatasets_v1_generated_MapsPlatformDatasets_FetchDatasetErrors_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.maps import mapsplatformdatasets_v1 - - -def sample_fetch_dataset_errors(): - # Create a client - client = mapsplatformdatasets_v1.MapsPlatformDatasetsClient() - - # Initialize request argument(s) - request = mapsplatformdatasets_v1.FetchDatasetErrorsRequest( - dataset="dataset_value", - ) - - # Make the request - page_result = client.fetch_dataset_errors(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END mapsplatformdatasets_v1_generated_MapsPlatformDatasets_FetchDatasetErrors_sync] diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_get_dataset_async.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_get_dataset_async.py deleted file mode 100644 index 312e767bd626..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_get_dataset_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetDataset -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-mapsplatformdatasets - - -# [START mapsplatformdatasets_v1_generated_MapsPlatformDatasets_GetDataset_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.maps import mapsplatformdatasets_v1 - - -async def sample_get_dataset(): - # Create a client - client = mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient() - - # Initialize request argument(s) - request = mapsplatformdatasets_v1.GetDatasetRequest( - name="name_value", - ) - - # Make the request - response = await client.get_dataset(request=request) - - # Handle the response - print(response) - -# [END mapsplatformdatasets_v1_generated_MapsPlatformDatasets_GetDataset_async] diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_get_dataset_sync.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_get_dataset_sync.py deleted file mode 100644 index 0acc34dfa04a..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_get_dataset_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetDataset -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-mapsplatformdatasets - - -# [START mapsplatformdatasets_v1_generated_MapsPlatformDatasets_GetDataset_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.maps import mapsplatformdatasets_v1 - - -def sample_get_dataset(): - # Create a client - client = mapsplatformdatasets_v1.MapsPlatformDatasetsClient() - - # Initialize request argument(s) - request = mapsplatformdatasets_v1.GetDatasetRequest( - name="name_value", - ) - - # Make the request - response = client.get_dataset(request=request) - - # Handle the response - print(response) - -# [END mapsplatformdatasets_v1_generated_MapsPlatformDatasets_GetDataset_sync] diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_list_datasets_async.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_list_datasets_async.py deleted file mode 100644 index 8d05703b3263..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_list_datasets_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListDatasets -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-mapsplatformdatasets - - -# [START mapsplatformdatasets_v1_generated_MapsPlatformDatasets_ListDatasets_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.maps import mapsplatformdatasets_v1 - - -async def sample_list_datasets(): - # Create a client - client = mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient() - - # Initialize request argument(s) - request = mapsplatformdatasets_v1.ListDatasetsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_datasets(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END mapsplatformdatasets_v1_generated_MapsPlatformDatasets_ListDatasets_async] diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_list_datasets_sync.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_list_datasets_sync.py deleted file mode 100644 index 648a02bc6842..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_list_datasets_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListDatasets -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-mapsplatformdatasets - - -# [START mapsplatformdatasets_v1_generated_MapsPlatformDatasets_ListDatasets_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.maps import mapsplatformdatasets_v1 - - -def sample_list_datasets(): - # Create a client - client = mapsplatformdatasets_v1.MapsPlatformDatasetsClient() - - # Initialize request argument(s) - request = mapsplatformdatasets_v1.ListDatasetsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_datasets(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END mapsplatformdatasets_v1_generated_MapsPlatformDatasets_ListDatasets_sync] diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_update_dataset_metadata_async.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_update_dataset_metadata_async.py deleted file mode 100644 index ef0886fafc21..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_update_dataset_metadata_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateDatasetMetadata -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-mapsplatformdatasets - - -# [START mapsplatformdatasets_v1_generated_MapsPlatformDatasets_UpdateDatasetMetadata_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.maps import mapsplatformdatasets_v1 - - -async def sample_update_dataset_metadata(): - # Create a client - client = mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient() - - # Initialize request argument(s) - request = mapsplatformdatasets_v1.UpdateDatasetMetadataRequest( - ) - - # Make the request - response = await client.update_dataset_metadata(request=request) - - # Handle the response - print(response) - -# [END mapsplatformdatasets_v1_generated_MapsPlatformDatasets_UpdateDatasetMetadata_async] diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_update_dataset_metadata_sync.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_update_dataset_metadata_sync.py deleted file mode 100644 index da429a9ff436..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/mapsplatformdatasets_v1_generated_maps_platform_datasets_update_dataset_metadata_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateDatasetMetadata -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-mapsplatformdatasets - - -# [START mapsplatformdatasets_v1_generated_MapsPlatformDatasets_UpdateDatasetMetadata_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.maps import mapsplatformdatasets_v1 - - -def sample_update_dataset_metadata(): - # Create a client - client = mapsplatformdatasets_v1.MapsPlatformDatasetsClient() - - # Initialize request argument(s) - request = mapsplatformdatasets_v1.UpdateDatasetMetadataRequest( - ) - - # Make the request - response = client.update_dataset_metadata(request=request) - - # Handle the response - print(response) - -# [END mapsplatformdatasets_v1_generated_MapsPlatformDatasets_UpdateDatasetMetadata_sync] diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/snippet_metadata_google.maps.mapsplatformdatasets.v1.json b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/snippet_metadata_google.maps.mapsplatformdatasets.v1.json deleted file mode 100644 index efd05ec97721..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/samples/generated_samples/snippet_metadata_google.maps.mapsplatformdatasets.v1.json +++ /dev/null @@ -1,991 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.maps.mapsplatformdatasets.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "google-maps-mapsplatformdatasets", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient", - "shortName": "MapsPlatformDatasetsAsyncClient" - }, - "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient.create_dataset", - "method": { - "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets.CreateDataset", - "service": { - "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", - "shortName": "MapsPlatformDatasets" - }, - "shortName": "CreateDataset" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.mapsplatformdatasets_v1.types.CreateDatasetRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "dataset", - "type": "google.maps.mapsplatformdatasets_v1.types.Dataset" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.maps.mapsplatformdatasets_v1.types.Dataset", - "shortName": "create_dataset" - }, - "description": "Sample for CreateDataset", - "file": "mapsplatformdatasets_v1_generated_maps_platform_datasets_create_dataset_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "mapsplatformdatasets_v1_generated_MapsPlatformDatasets_CreateDataset_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": "mapsplatformdatasets_v1_generated_maps_platform_datasets_create_dataset_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient", - "shortName": "MapsPlatformDatasetsClient" - }, - "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient.create_dataset", - "method": { - "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets.CreateDataset", - "service": { - "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", - "shortName": "MapsPlatformDatasets" - }, - "shortName": "CreateDataset" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.mapsplatformdatasets_v1.types.CreateDatasetRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "dataset", - "type": "google.maps.mapsplatformdatasets_v1.types.Dataset" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.maps.mapsplatformdatasets_v1.types.Dataset", - "shortName": "create_dataset" - }, - "description": "Sample for CreateDataset", - "file": "mapsplatformdatasets_v1_generated_maps_platform_datasets_create_dataset_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "mapsplatformdatasets_v1_generated_MapsPlatformDatasets_CreateDataset_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": "mapsplatformdatasets_v1_generated_maps_platform_datasets_create_dataset_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient", - "shortName": "MapsPlatformDatasetsAsyncClient" - }, - "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient.delete_dataset", - "method": { - "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets.DeleteDataset", - "service": { - "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", - "shortName": "MapsPlatformDatasets" - }, - "shortName": "DeleteDataset" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.mapsplatformdatasets_v1.types.DeleteDatasetRequest" - }, - { - "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_dataset" - }, - "description": "Sample for DeleteDataset", - "file": "mapsplatformdatasets_v1_generated_maps_platform_datasets_delete_dataset_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "mapsplatformdatasets_v1_generated_MapsPlatformDatasets_DeleteDataset_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": "mapsplatformdatasets_v1_generated_maps_platform_datasets_delete_dataset_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient", - "shortName": "MapsPlatformDatasetsClient" - }, - "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient.delete_dataset", - "method": { - "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets.DeleteDataset", - "service": { - "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", - "shortName": "MapsPlatformDatasets" - }, - "shortName": "DeleteDataset" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.mapsplatformdatasets_v1.types.DeleteDatasetRequest" - }, - { - "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_dataset" - }, - "description": "Sample for DeleteDataset", - "file": "mapsplatformdatasets_v1_generated_maps_platform_datasets_delete_dataset_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "mapsplatformdatasets_v1_generated_MapsPlatformDatasets_DeleteDataset_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": "mapsplatformdatasets_v1_generated_maps_platform_datasets_delete_dataset_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient", - "shortName": "MapsPlatformDatasetsAsyncClient" - }, - "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient.fetch_dataset_errors", - "method": { - "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets.FetchDatasetErrors", - "service": { - "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", - "shortName": "MapsPlatformDatasets" - }, - "shortName": "FetchDatasetErrors" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.mapsplatformdatasets_v1.types.FetchDatasetErrorsRequest" - }, - { - "name": "dataset", - "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.maps.mapsplatformdatasets_v1.services.maps_platform_datasets.pagers.FetchDatasetErrorsAsyncPager", - "shortName": "fetch_dataset_errors" - }, - "description": "Sample for FetchDatasetErrors", - "file": "mapsplatformdatasets_v1_generated_maps_platform_datasets_fetch_dataset_errors_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "mapsplatformdatasets_v1_generated_MapsPlatformDatasets_FetchDatasetErrors_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": "mapsplatformdatasets_v1_generated_maps_platform_datasets_fetch_dataset_errors_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient", - "shortName": "MapsPlatformDatasetsClient" - }, - "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient.fetch_dataset_errors", - "method": { - "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets.FetchDatasetErrors", - "service": { - "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", - "shortName": "MapsPlatformDatasets" - }, - "shortName": "FetchDatasetErrors" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.mapsplatformdatasets_v1.types.FetchDatasetErrorsRequest" - }, - { - "name": "dataset", - "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.maps.mapsplatformdatasets_v1.services.maps_platform_datasets.pagers.FetchDatasetErrorsPager", - "shortName": "fetch_dataset_errors" - }, - "description": "Sample for FetchDatasetErrors", - "file": "mapsplatformdatasets_v1_generated_maps_platform_datasets_fetch_dataset_errors_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "mapsplatformdatasets_v1_generated_MapsPlatformDatasets_FetchDatasetErrors_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": "mapsplatformdatasets_v1_generated_maps_platform_datasets_fetch_dataset_errors_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient", - "shortName": "MapsPlatformDatasetsAsyncClient" - }, - "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient.get_dataset", - "method": { - "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets.GetDataset", - "service": { - "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", - "shortName": "MapsPlatformDatasets" - }, - "shortName": "GetDataset" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.mapsplatformdatasets_v1.types.GetDatasetRequest" - }, - { - "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.maps.mapsplatformdatasets_v1.types.Dataset", - "shortName": "get_dataset" - }, - "description": "Sample for GetDataset", - "file": "mapsplatformdatasets_v1_generated_maps_platform_datasets_get_dataset_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "mapsplatformdatasets_v1_generated_MapsPlatformDatasets_GetDataset_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": "mapsplatformdatasets_v1_generated_maps_platform_datasets_get_dataset_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient", - "shortName": "MapsPlatformDatasetsClient" - }, - "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient.get_dataset", - "method": { - "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets.GetDataset", - "service": { - "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", - "shortName": "MapsPlatformDatasets" - }, - "shortName": "GetDataset" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.mapsplatformdatasets_v1.types.GetDatasetRequest" - }, - { - "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.maps.mapsplatformdatasets_v1.types.Dataset", - "shortName": "get_dataset" - }, - "description": "Sample for GetDataset", - "file": "mapsplatformdatasets_v1_generated_maps_platform_datasets_get_dataset_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "mapsplatformdatasets_v1_generated_MapsPlatformDatasets_GetDataset_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": "mapsplatformdatasets_v1_generated_maps_platform_datasets_get_dataset_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient", - "shortName": "MapsPlatformDatasetsAsyncClient" - }, - "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient.list_datasets", - "method": { - "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets.ListDatasets", - "service": { - "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", - "shortName": "MapsPlatformDatasets" - }, - "shortName": "ListDatasets" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.mapsplatformdatasets_v1.types.ListDatasetsRequest" - }, - { - "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.maps.mapsplatformdatasets_v1.services.maps_platform_datasets.pagers.ListDatasetsAsyncPager", - "shortName": "list_datasets" - }, - "description": "Sample for ListDatasets", - "file": "mapsplatformdatasets_v1_generated_maps_platform_datasets_list_datasets_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "mapsplatformdatasets_v1_generated_MapsPlatformDatasets_ListDatasets_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": "mapsplatformdatasets_v1_generated_maps_platform_datasets_list_datasets_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient", - "shortName": "MapsPlatformDatasetsClient" - }, - "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient.list_datasets", - "method": { - "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets.ListDatasets", - "service": { - "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", - "shortName": "MapsPlatformDatasets" - }, - "shortName": "ListDatasets" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.mapsplatformdatasets_v1.types.ListDatasetsRequest" - }, - { - "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.maps.mapsplatformdatasets_v1.services.maps_platform_datasets.pagers.ListDatasetsPager", - "shortName": "list_datasets" - }, - "description": "Sample for ListDatasets", - "file": "mapsplatformdatasets_v1_generated_maps_platform_datasets_list_datasets_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "mapsplatformdatasets_v1_generated_MapsPlatformDatasets_ListDatasets_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": "mapsplatformdatasets_v1_generated_maps_platform_datasets_list_datasets_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient", - "shortName": "MapsPlatformDatasetsAsyncClient" - }, - "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient.update_dataset_metadata", - "method": { - "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets.UpdateDatasetMetadata", - "service": { - "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", - "shortName": "MapsPlatformDatasets" - }, - "shortName": "UpdateDatasetMetadata" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.mapsplatformdatasets_v1.types.UpdateDatasetMetadataRequest" - }, - { - "name": "dataset", - "type": "google.maps.mapsplatformdatasets_v1.types.Dataset" - }, - { - "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.maps.mapsplatformdatasets_v1.types.Dataset", - "shortName": "update_dataset_metadata" - }, - "description": "Sample for UpdateDatasetMetadata", - "file": "mapsplatformdatasets_v1_generated_maps_platform_datasets_update_dataset_metadata_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "mapsplatformdatasets_v1_generated_MapsPlatformDatasets_UpdateDatasetMetadata_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": "mapsplatformdatasets_v1_generated_maps_platform_datasets_update_dataset_metadata_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient", - "shortName": "MapsPlatformDatasetsClient" - }, - "fullName": "google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient.update_dataset_metadata", - "method": { - "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets.UpdateDatasetMetadata", - "service": { - "fullName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", - "shortName": "MapsPlatformDatasets" - }, - "shortName": "UpdateDatasetMetadata" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.mapsplatformdatasets_v1.types.UpdateDatasetMetadataRequest" - }, - { - "name": "dataset", - "type": "google.maps.mapsplatformdatasets_v1.types.Dataset" - }, - { - "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.maps.mapsplatformdatasets_v1.types.Dataset", - "shortName": "update_dataset_metadata" - }, - "description": "Sample for UpdateDatasetMetadata", - "file": "mapsplatformdatasets_v1_generated_maps_platform_datasets_update_dataset_metadata_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "mapsplatformdatasets_v1_generated_MapsPlatformDatasets_UpdateDatasetMetadata_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": "mapsplatformdatasets_v1_generated_maps_platform_datasets_update_dataset_metadata_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/scripts/fixup_mapsplatformdatasets_v1_keywords.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/scripts/fixup_mapsplatformdatasets_v1_keywords.py deleted file mode 100644 index ff0000bc3ad6..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/scripts/fixup_mapsplatformdatasets_v1_keywords.py +++ /dev/null @@ -1,181 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 mapsplatformdatasetsCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_dataset': ('parent', 'dataset', ), - 'delete_dataset': ('name', ), - 'fetch_dataset_errors': ('dataset', 'page_size', 'page_token', ), - 'get_dataset': ('name', ), - 'list_datasets': ('parent', 'page_size', 'page_token', 'tag', ), - 'update_dataset_metadata': ('dataset', '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=mapsplatformdatasetsCallTransformer(), -): - """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 mapsplatformdatasets 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-maps-mapsplatformdatasets/v1/setup.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/setup.py deleted file mode 100644 index b2f22f2d7c10..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/setup.py +++ /dev/null @@ -1,98 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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-maps-mapsplatformdatasets' - - -description = "Google Maps Mapsplatformdatasets API client library" - -version = None - -with open(os.path.join(package_root, 'google/maps/mapsplatformdatasets/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.0dev,!=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.0dev,!=2.24.0,!=2.25.0", - "proto-plus >= 1.22.3, <2.0.0dev", - "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'", - "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", -] -extras = { -} -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-mapsplatformdatasets" - -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-maps-mapsplatformdatasets/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.10.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.10.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.11.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.11.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.12.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.12.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.13.txt b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.13.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.13.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.7.txt deleted file mode 100644 index fc812592b0ee..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.7.txt +++ /dev/null @@ -1,10 +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.0dev", -# 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 diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.8.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.8.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.9.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.9.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/tests/__init__.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-maps-mapsplatformdatasets/v1/tests/unit/__init__.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-maps-mapsplatformdatasets/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-maps-mapsplatformdatasets/v1/tests/unit/gapic/mapsplatformdatasets_v1/__init__.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/tests/unit/gapic/mapsplatformdatasets_v1/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/tests/unit/gapic/mapsplatformdatasets_v1/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-maps-mapsplatformdatasets/v1/tests/unit/gapic/mapsplatformdatasets_v1/test_maps_platform_datasets.py b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/tests/unit/gapic/mapsplatformdatasets_v1/test_maps_platform_datasets.py deleted file mode 100644 index d8d1b199a178..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/tests/unit/gapic/mapsplatformdatasets_v1/test_maps_platform_datasets.py +++ /dev/null @@ -1,6115 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.mapsplatformdatasets_v1.services.maps_platform_datasets import MapsPlatformDatasetsAsyncClient -from google.maps.mapsplatformdatasets_v1.services.maps_platform_datasets import MapsPlatformDatasetsClient -from google.maps.mapsplatformdatasets_v1.services.maps_platform_datasets import pagers -from google.maps.mapsplatformdatasets_v1.services.maps_platform_datasets import transports -from google.maps.mapsplatformdatasets_v1.types import data_source -from google.maps.mapsplatformdatasets_v1.types import dataset -from google.maps.mapsplatformdatasets_v1.types import dataset as gmm_dataset -from google.maps.mapsplatformdatasets_v1.types import maps_platform_datasets -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.rpc import status_pb2 # type: ignore -import google.auth - - -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 MapsPlatformDatasetsClient._get_default_mtls_endpoint(None) is None - assert MapsPlatformDatasetsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert MapsPlatformDatasetsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert MapsPlatformDatasetsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert MapsPlatformDatasetsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert MapsPlatformDatasetsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert MapsPlatformDatasetsClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert MapsPlatformDatasetsClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert MapsPlatformDatasetsClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - MapsPlatformDatasetsClient._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 MapsPlatformDatasetsClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert MapsPlatformDatasetsClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert MapsPlatformDatasetsClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - MapsPlatformDatasetsClient._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 MapsPlatformDatasetsClient._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 MapsPlatformDatasetsClient._get_client_cert_source(None, False) is None - assert MapsPlatformDatasetsClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert MapsPlatformDatasetsClient._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 MapsPlatformDatasetsClient._get_client_cert_source(None, True) is mock_default_cert_source - assert MapsPlatformDatasetsClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(MapsPlatformDatasetsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(MapsPlatformDatasetsClient)) -@mock.patch.object(MapsPlatformDatasetsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(MapsPlatformDatasetsAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = MapsPlatformDatasetsClient._DEFAULT_UNIVERSE - default_endpoint = MapsPlatformDatasetsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = MapsPlatformDatasetsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert MapsPlatformDatasetsClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert MapsPlatformDatasetsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == MapsPlatformDatasetsClient.DEFAULT_MTLS_ENDPOINT - assert MapsPlatformDatasetsClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert MapsPlatformDatasetsClient._get_api_endpoint(None, None, default_universe, "always") == MapsPlatformDatasetsClient.DEFAULT_MTLS_ENDPOINT - assert MapsPlatformDatasetsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == MapsPlatformDatasetsClient.DEFAULT_MTLS_ENDPOINT - assert MapsPlatformDatasetsClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert MapsPlatformDatasetsClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - MapsPlatformDatasetsClient._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 MapsPlatformDatasetsClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert MapsPlatformDatasetsClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert MapsPlatformDatasetsClient._get_universe_domain(None, None) == MapsPlatformDatasetsClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - MapsPlatformDatasetsClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - - -@pytest.mark.parametrize("client_class,transport_name", [ - (MapsPlatformDatasetsClient, "grpc"), - (MapsPlatformDatasetsAsyncClient, "grpc_asyncio"), - (MapsPlatformDatasetsClient, "rest"), -]) -def test_maps_platform_datasets_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 == ( - 'mapsplatformdatasets.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://mapsplatformdatasets.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.MapsPlatformDatasetsGrpcTransport, "grpc"), - (transports.MapsPlatformDatasetsGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.MapsPlatformDatasetsRestTransport, "rest"), -]) -def test_maps_platform_datasets_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", [ - (MapsPlatformDatasetsClient, "grpc"), - (MapsPlatformDatasetsAsyncClient, "grpc_asyncio"), - (MapsPlatformDatasetsClient, "rest"), -]) -def test_maps_platform_datasets_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 == ( - 'mapsplatformdatasets.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://mapsplatformdatasets.googleapis.com' - ) - - -def test_maps_platform_datasets_client_get_transport_class(): - transport = MapsPlatformDatasetsClient.get_transport_class() - available_transports = [ - transports.MapsPlatformDatasetsGrpcTransport, - transports.MapsPlatformDatasetsRestTransport, - ] - assert transport in available_transports - - transport = MapsPlatformDatasetsClient.get_transport_class("grpc") - assert transport == transports.MapsPlatformDatasetsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (MapsPlatformDatasetsClient, transports.MapsPlatformDatasetsGrpcTransport, "grpc"), - (MapsPlatformDatasetsAsyncClient, transports.MapsPlatformDatasetsGrpcAsyncIOTransport, "grpc_asyncio"), - (MapsPlatformDatasetsClient, transports.MapsPlatformDatasetsRestTransport, "rest"), -]) -@mock.patch.object(MapsPlatformDatasetsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(MapsPlatformDatasetsClient)) -@mock.patch.object(MapsPlatformDatasetsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(MapsPlatformDatasetsAsyncClient)) -def test_maps_platform_datasets_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(MapsPlatformDatasetsClient, '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(MapsPlatformDatasetsClient, '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", [ - (MapsPlatformDatasetsClient, transports.MapsPlatformDatasetsGrpcTransport, "grpc", "true"), - (MapsPlatformDatasetsAsyncClient, transports.MapsPlatformDatasetsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (MapsPlatformDatasetsClient, transports.MapsPlatformDatasetsGrpcTransport, "grpc", "false"), - (MapsPlatformDatasetsAsyncClient, transports.MapsPlatformDatasetsGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (MapsPlatformDatasetsClient, transports.MapsPlatformDatasetsRestTransport, "rest", "true"), - (MapsPlatformDatasetsClient, transports.MapsPlatformDatasetsRestTransport, "rest", "false"), -]) -@mock.patch.object(MapsPlatformDatasetsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(MapsPlatformDatasetsClient)) -@mock.patch.object(MapsPlatformDatasetsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(MapsPlatformDatasetsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_maps_platform_datasets_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", [ - MapsPlatformDatasetsClient, MapsPlatformDatasetsAsyncClient -]) -@mock.patch.object(MapsPlatformDatasetsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(MapsPlatformDatasetsClient)) -@mock.patch.object(MapsPlatformDatasetsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(MapsPlatformDatasetsAsyncClient)) -def test_maps_platform_datasets_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", [ - MapsPlatformDatasetsClient, MapsPlatformDatasetsAsyncClient -]) -@mock.patch.object(MapsPlatformDatasetsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(MapsPlatformDatasetsClient)) -@mock.patch.object(MapsPlatformDatasetsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(MapsPlatformDatasetsAsyncClient)) -def test_maps_platform_datasets_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = MapsPlatformDatasetsClient._DEFAULT_UNIVERSE - default_endpoint = MapsPlatformDatasetsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = MapsPlatformDatasetsClient._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", [ - (MapsPlatformDatasetsClient, transports.MapsPlatformDatasetsGrpcTransport, "grpc"), - (MapsPlatformDatasetsAsyncClient, transports.MapsPlatformDatasetsGrpcAsyncIOTransport, "grpc_asyncio"), - (MapsPlatformDatasetsClient, transports.MapsPlatformDatasetsRestTransport, "rest"), -]) -def test_maps_platform_datasets_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", [ - (MapsPlatformDatasetsClient, transports.MapsPlatformDatasetsGrpcTransport, "grpc", grpc_helpers), - (MapsPlatformDatasetsAsyncClient, transports.MapsPlatformDatasetsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (MapsPlatformDatasetsClient, transports.MapsPlatformDatasetsRestTransport, "rest", None), -]) -def test_maps_platform_datasets_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_maps_platform_datasets_client_client_options_from_dict(): - with mock.patch('google.maps.mapsplatformdatasets_v1.services.maps_platform_datasets.transports.MapsPlatformDatasetsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = MapsPlatformDatasetsClient( - 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", [ - (MapsPlatformDatasetsClient, transports.MapsPlatformDatasetsGrpcTransport, "grpc", grpc_helpers), - (MapsPlatformDatasetsAsyncClient, transports.MapsPlatformDatasetsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_maps_platform_datasets_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( - "mapsplatformdatasets.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=None, - default_host="mapsplatformdatasets.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - maps_platform_datasets.CreateDatasetRequest, - dict, -]) -def test_create_dataset(request_type, transport: str = 'grpc'): - client = MapsPlatformDatasetsClient( - 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_dataset), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gmm_dataset.Dataset( - name='name_value', - display_name='display_name_value', - description='description_value', - version_id='version_id_value', - usage=[gmm_dataset.Usage.USAGE_DATA_DRIVEN_STYLING], - version_description='version_description_value', - ) - response = client.create_dataset(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = maps_platform_datasets.CreateDatasetRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gmm_dataset.Dataset) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.version_id == 'version_id_value' - assert response.usage == [gmm_dataset.Usage.USAGE_DATA_DRIVEN_STYLING] - assert response.version_description == 'version_description_value' - - -def test_create_dataset_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 = MapsPlatformDatasetsClient( - 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 = maps_platform_datasets.CreateDatasetRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_dataset), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_dataset(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == maps_platform_datasets.CreateDatasetRequest( - parent='parent_value', - ) - -def test_create_dataset_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = MapsPlatformDatasetsClient( - 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_dataset in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_dataset] = mock_rpc - request = {} - client.create_dataset(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_dataset(request) - - # Establish that a new wrapper 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_dataset_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = MapsPlatformDatasetsAsyncClient( - 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_dataset in client._client._transport._wrapped_methods - - # 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_dataset] = mock_rpc - - request = {} - await client.create_dataset(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.create_dataset(request) - - # Establish that a new wrapper 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_dataset_async(transport: str = 'grpc_asyncio', request_type=maps_platform_datasets.CreateDatasetRequest): - client = MapsPlatformDatasetsAsyncClient( - 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_dataset), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gmm_dataset.Dataset( - name='name_value', - display_name='display_name_value', - description='description_value', - version_id='version_id_value', - usage=[gmm_dataset.Usage.USAGE_DATA_DRIVEN_STYLING], - version_description='version_description_value', - )) - response = await client.create_dataset(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = maps_platform_datasets.CreateDatasetRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gmm_dataset.Dataset) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.version_id == 'version_id_value' - assert response.usage == [gmm_dataset.Usage.USAGE_DATA_DRIVEN_STYLING] - assert response.version_description == 'version_description_value' - - -@pytest.mark.asyncio -async def test_create_dataset_async_from_dict(): - await test_create_dataset_async(request_type=dict) - -def test_create_dataset_field_headers(): - client = MapsPlatformDatasetsClient( - 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 = maps_platform_datasets.CreateDatasetRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_dataset), - '__call__') as call: - call.return_value = gmm_dataset.Dataset() - client.create_dataset(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_dataset_field_headers_async(): - client = MapsPlatformDatasetsAsyncClient( - 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 = maps_platform_datasets.CreateDatasetRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_dataset), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gmm_dataset.Dataset()) - await client.create_dataset(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_dataset_flattened(): - client = MapsPlatformDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_dataset), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gmm_dataset.Dataset() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_dataset( - parent='parent_value', - dataset=gmm_dataset.Dataset(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].dataset - mock_val = gmm_dataset.Dataset(name='name_value') - assert arg == mock_val - - -def test_create_dataset_flattened_error(): - client = MapsPlatformDatasetsClient( - 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_dataset( - maps_platform_datasets.CreateDatasetRequest(), - parent='parent_value', - dataset=gmm_dataset.Dataset(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_dataset_flattened_async(): - client = MapsPlatformDatasetsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_dataset), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gmm_dataset.Dataset() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gmm_dataset.Dataset()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_dataset( - parent='parent_value', - dataset=gmm_dataset.Dataset(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].dataset - mock_val = gmm_dataset.Dataset(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_dataset_flattened_error_async(): - client = MapsPlatformDatasetsAsyncClient( - 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_dataset( - maps_platform_datasets.CreateDatasetRequest(), - parent='parent_value', - dataset=gmm_dataset.Dataset(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - maps_platform_datasets.UpdateDatasetMetadataRequest, - dict, -]) -def test_update_dataset_metadata(request_type, transport: str = 'grpc'): - client = MapsPlatformDatasetsClient( - 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_dataset_metadata), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gmm_dataset.Dataset( - name='name_value', - display_name='display_name_value', - description='description_value', - version_id='version_id_value', - usage=[gmm_dataset.Usage.USAGE_DATA_DRIVEN_STYLING], - version_description='version_description_value', - ) - response = client.update_dataset_metadata(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = maps_platform_datasets.UpdateDatasetMetadataRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gmm_dataset.Dataset) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.version_id == 'version_id_value' - assert response.usage == [gmm_dataset.Usage.USAGE_DATA_DRIVEN_STYLING] - assert response.version_description == 'version_description_value' - - -def test_update_dataset_metadata_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 = MapsPlatformDatasetsClient( - 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 = maps_platform_datasets.UpdateDatasetMetadataRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_dataset_metadata), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_dataset_metadata(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == maps_platform_datasets.UpdateDatasetMetadataRequest( - ) - -def test_update_dataset_metadata_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = MapsPlatformDatasetsClient( - 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_dataset_metadata in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_dataset_metadata] = mock_rpc - request = {} - client.update_dataset_metadata(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_dataset_metadata(request) - - # Establish that a new wrapper 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_dataset_metadata_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = MapsPlatformDatasetsAsyncClient( - 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_dataset_metadata in client._client._transport._wrapped_methods - - # 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_dataset_metadata] = mock_rpc - - request = {} - await client.update_dataset_metadata(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_dataset_metadata(request) - - # Establish that a new wrapper 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_dataset_metadata_async(transport: str = 'grpc_asyncio', request_type=maps_platform_datasets.UpdateDatasetMetadataRequest): - client = MapsPlatformDatasetsAsyncClient( - 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_dataset_metadata), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gmm_dataset.Dataset( - name='name_value', - display_name='display_name_value', - description='description_value', - version_id='version_id_value', - usage=[gmm_dataset.Usage.USAGE_DATA_DRIVEN_STYLING], - version_description='version_description_value', - )) - response = await client.update_dataset_metadata(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = maps_platform_datasets.UpdateDatasetMetadataRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gmm_dataset.Dataset) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.version_id == 'version_id_value' - assert response.usage == [gmm_dataset.Usage.USAGE_DATA_DRIVEN_STYLING] - assert response.version_description == 'version_description_value' - - -@pytest.mark.asyncio -async def test_update_dataset_metadata_async_from_dict(): - await test_update_dataset_metadata_async(request_type=dict) - -def test_update_dataset_metadata_field_headers(): - client = MapsPlatformDatasetsClient( - 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 = maps_platform_datasets.UpdateDatasetMetadataRequest() - - request.dataset.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_dataset_metadata), - '__call__') as call: - call.return_value = gmm_dataset.Dataset() - client.update_dataset_metadata(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', - 'dataset.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_dataset_metadata_field_headers_async(): - client = MapsPlatformDatasetsAsyncClient( - 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 = maps_platform_datasets.UpdateDatasetMetadataRequest() - - request.dataset.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_dataset_metadata), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gmm_dataset.Dataset()) - await client.update_dataset_metadata(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', - 'dataset.name=name_value', - ) in kw['metadata'] - - -def test_update_dataset_metadata_flattened(): - client = MapsPlatformDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_dataset_metadata), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gmm_dataset.Dataset() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_dataset_metadata( - dataset=gmm_dataset.Dataset(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].dataset - mock_val = gmm_dataset.Dataset(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_dataset_metadata_flattened_error(): - client = MapsPlatformDatasetsClient( - 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_dataset_metadata( - maps_platform_datasets.UpdateDatasetMetadataRequest(), - dataset=gmm_dataset.Dataset(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_dataset_metadata_flattened_async(): - client = MapsPlatformDatasetsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_dataset_metadata), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gmm_dataset.Dataset() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gmm_dataset.Dataset()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_dataset_metadata( - dataset=gmm_dataset.Dataset(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].dataset - mock_val = gmm_dataset.Dataset(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_dataset_metadata_flattened_error_async(): - client = MapsPlatformDatasetsAsyncClient( - 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_dataset_metadata( - maps_platform_datasets.UpdateDatasetMetadataRequest(), - dataset=gmm_dataset.Dataset(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - maps_platform_datasets.GetDatasetRequest, - dict, -]) -def test_get_dataset(request_type, transport: str = 'grpc'): - client = MapsPlatformDatasetsClient( - 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_dataset), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = dataset.Dataset( - name='name_value', - display_name='display_name_value', - description='description_value', - version_id='version_id_value', - usage=[dataset.Usage.USAGE_DATA_DRIVEN_STYLING], - version_description='version_description_value', - ) - response = client.get_dataset(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = maps_platform_datasets.GetDatasetRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, dataset.Dataset) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.version_id == 'version_id_value' - assert response.usage == [dataset.Usage.USAGE_DATA_DRIVEN_STYLING] - assert response.version_description == 'version_description_value' - - -def test_get_dataset_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 = MapsPlatformDatasetsClient( - 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 = maps_platform_datasets.GetDatasetRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_dataset), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_dataset(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == maps_platform_datasets.GetDatasetRequest( - name='name_value', - ) - -def test_get_dataset_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = MapsPlatformDatasetsClient( - 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_dataset in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_dataset] = mock_rpc - request = {} - client.get_dataset(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_dataset(request) - - # Establish that a new wrapper 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_dataset_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = MapsPlatformDatasetsAsyncClient( - 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_dataset in client._client._transport._wrapped_methods - - # 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_dataset] = mock_rpc - - request = {} - await client.get_dataset(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_dataset(request) - - # Establish that a new wrapper 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_dataset_async(transport: str = 'grpc_asyncio', request_type=maps_platform_datasets.GetDatasetRequest): - client = MapsPlatformDatasetsAsyncClient( - 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_dataset), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(dataset.Dataset( - name='name_value', - display_name='display_name_value', - description='description_value', - version_id='version_id_value', - usage=[dataset.Usage.USAGE_DATA_DRIVEN_STYLING], - version_description='version_description_value', - )) - response = await client.get_dataset(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = maps_platform_datasets.GetDatasetRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, dataset.Dataset) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.version_id == 'version_id_value' - assert response.usage == [dataset.Usage.USAGE_DATA_DRIVEN_STYLING] - assert response.version_description == 'version_description_value' - - -@pytest.mark.asyncio -async def test_get_dataset_async_from_dict(): - await test_get_dataset_async(request_type=dict) - -def test_get_dataset_field_headers(): - client = MapsPlatformDatasetsClient( - 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 = maps_platform_datasets.GetDatasetRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_dataset), - '__call__') as call: - call.return_value = dataset.Dataset() - client.get_dataset(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_dataset_field_headers_async(): - client = MapsPlatformDatasetsAsyncClient( - 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 = maps_platform_datasets.GetDatasetRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_dataset), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dataset.Dataset()) - await client.get_dataset(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_dataset_flattened(): - client = MapsPlatformDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_dataset), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = dataset.Dataset() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_dataset( - 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_dataset_flattened_error(): - client = MapsPlatformDatasetsClient( - 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_dataset( - maps_platform_datasets.GetDatasetRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_dataset_flattened_async(): - client = MapsPlatformDatasetsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_dataset), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = dataset.Dataset() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dataset.Dataset()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_dataset( - 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_dataset_flattened_error_async(): - client = MapsPlatformDatasetsAsyncClient( - 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_dataset( - maps_platform_datasets.GetDatasetRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - maps_platform_datasets.FetchDatasetErrorsRequest, - dict, -]) -def test_fetch_dataset_errors(request_type, transport: str = 'grpc'): - client = MapsPlatformDatasetsClient( - 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.fetch_dataset_errors), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = maps_platform_datasets.FetchDatasetErrorsResponse( - next_page_token='next_page_token_value', - ) - response = client.fetch_dataset_errors(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = maps_platform_datasets.FetchDatasetErrorsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.FetchDatasetErrorsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_fetch_dataset_errors_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 = MapsPlatformDatasetsClient( - 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 = maps_platform_datasets.FetchDatasetErrorsRequest( - dataset='dataset_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.fetch_dataset_errors), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.fetch_dataset_errors(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == maps_platform_datasets.FetchDatasetErrorsRequest( - dataset='dataset_value', - page_token='page_token_value', - ) - -def test_fetch_dataset_errors_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = MapsPlatformDatasetsClient( - 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.fetch_dataset_errors in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.fetch_dataset_errors] = mock_rpc - request = {} - client.fetch_dataset_errors(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.fetch_dataset_errors(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_fetch_dataset_errors_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = MapsPlatformDatasetsAsyncClient( - 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.fetch_dataset_errors in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.fetch_dataset_errors] = mock_rpc - - request = {} - await client.fetch_dataset_errors(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.fetch_dataset_errors(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_fetch_dataset_errors_async(transport: str = 'grpc_asyncio', request_type=maps_platform_datasets.FetchDatasetErrorsRequest): - client = MapsPlatformDatasetsAsyncClient( - 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.fetch_dataset_errors), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(maps_platform_datasets.FetchDatasetErrorsResponse( - next_page_token='next_page_token_value', - )) - response = await client.fetch_dataset_errors(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = maps_platform_datasets.FetchDatasetErrorsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.FetchDatasetErrorsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_fetch_dataset_errors_async_from_dict(): - await test_fetch_dataset_errors_async(request_type=dict) - -def test_fetch_dataset_errors_field_headers(): - client = MapsPlatformDatasetsClient( - 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 = maps_platform_datasets.FetchDatasetErrorsRequest() - - request.dataset = 'dataset_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.fetch_dataset_errors), - '__call__') as call: - call.return_value = maps_platform_datasets.FetchDatasetErrorsResponse() - client.fetch_dataset_errors(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', - 'dataset=dataset_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_fetch_dataset_errors_field_headers_async(): - client = MapsPlatformDatasetsAsyncClient( - 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 = maps_platform_datasets.FetchDatasetErrorsRequest() - - request.dataset = 'dataset_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.fetch_dataset_errors), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(maps_platform_datasets.FetchDatasetErrorsResponse()) - await client.fetch_dataset_errors(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', - 'dataset=dataset_value', - ) in kw['metadata'] - - -def test_fetch_dataset_errors_flattened(): - client = MapsPlatformDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.fetch_dataset_errors), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = maps_platform_datasets.FetchDatasetErrorsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.fetch_dataset_errors( - dataset='dataset_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].dataset - mock_val = 'dataset_value' - assert arg == mock_val - - -def test_fetch_dataset_errors_flattened_error(): - client = MapsPlatformDatasetsClient( - 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.fetch_dataset_errors( - maps_platform_datasets.FetchDatasetErrorsRequest(), - dataset='dataset_value', - ) - -@pytest.mark.asyncio -async def test_fetch_dataset_errors_flattened_async(): - client = MapsPlatformDatasetsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.fetch_dataset_errors), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = maps_platform_datasets.FetchDatasetErrorsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(maps_platform_datasets.FetchDatasetErrorsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.fetch_dataset_errors( - dataset='dataset_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].dataset - mock_val = 'dataset_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_fetch_dataset_errors_flattened_error_async(): - client = MapsPlatformDatasetsAsyncClient( - 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.fetch_dataset_errors( - maps_platform_datasets.FetchDatasetErrorsRequest(), - dataset='dataset_value', - ) - - -def test_fetch_dataset_errors_pager(transport_name: str = "grpc"): - client = MapsPlatformDatasetsClient( - 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.fetch_dataset_errors), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - maps_platform_datasets.FetchDatasetErrorsResponse( - errors=[ - status_pb2.Status(), - status_pb2.Status(), - status_pb2.Status(), - ], - next_page_token='abc', - ), - maps_platform_datasets.FetchDatasetErrorsResponse( - errors=[], - next_page_token='def', - ), - maps_platform_datasets.FetchDatasetErrorsResponse( - errors=[ - status_pb2.Status(), - ], - next_page_token='ghi', - ), - maps_platform_datasets.FetchDatasetErrorsResponse( - errors=[ - status_pb2.Status(), - status_pb2.Status(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('dataset', ''), - )), - ) - pager = client.fetch_dataset_errors(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, status_pb2.Status) - for i in results) -def test_fetch_dataset_errors_pages(transport_name: str = "grpc"): - client = MapsPlatformDatasetsClient( - 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.fetch_dataset_errors), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - maps_platform_datasets.FetchDatasetErrorsResponse( - errors=[ - status_pb2.Status(), - status_pb2.Status(), - status_pb2.Status(), - ], - next_page_token='abc', - ), - maps_platform_datasets.FetchDatasetErrorsResponse( - errors=[], - next_page_token='def', - ), - maps_platform_datasets.FetchDatasetErrorsResponse( - errors=[ - status_pb2.Status(), - ], - next_page_token='ghi', - ), - maps_platform_datasets.FetchDatasetErrorsResponse( - errors=[ - status_pb2.Status(), - status_pb2.Status(), - ], - ), - RuntimeError, - ) - pages = list(client.fetch_dataset_errors(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_fetch_dataset_errors_async_pager(): - client = MapsPlatformDatasetsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.fetch_dataset_errors), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - maps_platform_datasets.FetchDatasetErrorsResponse( - errors=[ - status_pb2.Status(), - status_pb2.Status(), - status_pb2.Status(), - ], - next_page_token='abc', - ), - maps_platform_datasets.FetchDatasetErrorsResponse( - errors=[], - next_page_token='def', - ), - maps_platform_datasets.FetchDatasetErrorsResponse( - errors=[ - status_pb2.Status(), - ], - next_page_token='ghi', - ), - maps_platform_datasets.FetchDatasetErrorsResponse( - errors=[ - status_pb2.Status(), - status_pb2.Status(), - ], - ), - RuntimeError, - ) - async_pager = await client.fetch_dataset_errors(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, status_pb2.Status) - for i in responses) - - -@pytest.mark.asyncio -async def test_fetch_dataset_errors_async_pages(): - client = MapsPlatformDatasetsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.fetch_dataset_errors), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - maps_platform_datasets.FetchDatasetErrorsResponse( - errors=[ - status_pb2.Status(), - status_pb2.Status(), - status_pb2.Status(), - ], - next_page_token='abc', - ), - maps_platform_datasets.FetchDatasetErrorsResponse( - errors=[], - next_page_token='def', - ), - maps_platform_datasets.FetchDatasetErrorsResponse( - errors=[ - status_pb2.Status(), - ], - next_page_token='ghi', - ), - maps_platform_datasets.FetchDatasetErrorsResponse( - errors=[ - status_pb2.Status(), - status_pb2.Status(), - ], - ), - 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.fetch_dataset_errors(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", [ - maps_platform_datasets.ListDatasetsRequest, - dict, -]) -def test_list_datasets(request_type, transport: str = 'grpc'): - client = MapsPlatformDatasetsClient( - 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_datasets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = maps_platform_datasets.ListDatasetsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_datasets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = maps_platform_datasets.ListDatasetsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDatasetsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_datasets_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 = MapsPlatformDatasetsClient( - 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 = maps_platform_datasets.ListDatasetsRequest( - parent='parent_value', - page_token='page_token_value', - tag='tag_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_datasets), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_datasets(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == maps_platform_datasets.ListDatasetsRequest( - parent='parent_value', - page_token='page_token_value', - tag='tag_value', - ) - -def test_list_datasets_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = MapsPlatformDatasetsClient( - 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_datasets in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_datasets] = mock_rpc - request = {} - client.list_datasets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_datasets(request) - - # Establish that a new wrapper 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_datasets_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = MapsPlatformDatasetsAsyncClient( - 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_datasets in client._client._transport._wrapped_methods - - # 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_datasets] = mock_rpc - - request = {} - await client.list_datasets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_datasets(request) - - # Establish that a new wrapper 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_datasets_async(transport: str = 'grpc_asyncio', request_type=maps_platform_datasets.ListDatasetsRequest): - client = MapsPlatformDatasetsAsyncClient( - 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_datasets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(maps_platform_datasets.ListDatasetsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_datasets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = maps_platform_datasets.ListDatasetsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDatasetsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_datasets_async_from_dict(): - await test_list_datasets_async(request_type=dict) - -def test_list_datasets_field_headers(): - client = MapsPlatformDatasetsClient( - 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 = maps_platform_datasets.ListDatasetsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_datasets), - '__call__') as call: - call.return_value = maps_platform_datasets.ListDatasetsResponse() - client.list_datasets(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_datasets_field_headers_async(): - client = MapsPlatformDatasetsAsyncClient( - 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 = maps_platform_datasets.ListDatasetsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_datasets), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(maps_platform_datasets.ListDatasetsResponse()) - await client.list_datasets(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_datasets_flattened(): - client = MapsPlatformDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_datasets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = maps_platform_datasets.ListDatasetsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_datasets( - 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_datasets_flattened_error(): - client = MapsPlatformDatasetsClient( - 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_datasets( - maps_platform_datasets.ListDatasetsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_datasets_flattened_async(): - client = MapsPlatformDatasetsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_datasets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = maps_platform_datasets.ListDatasetsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(maps_platform_datasets.ListDatasetsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_datasets( - 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_datasets_flattened_error_async(): - client = MapsPlatformDatasetsAsyncClient( - 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_datasets( - maps_platform_datasets.ListDatasetsRequest(), - parent='parent_value', - ) - - -def test_list_datasets_pager(transport_name: str = "grpc"): - client = MapsPlatformDatasetsClient( - 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_datasets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - maps_platform_datasets.ListDatasetsResponse( - datasets=[ - dataset.Dataset(), - dataset.Dataset(), - dataset.Dataset(), - ], - next_page_token='abc', - ), - maps_platform_datasets.ListDatasetsResponse( - datasets=[], - next_page_token='def', - ), - maps_platform_datasets.ListDatasetsResponse( - datasets=[ - dataset.Dataset(), - ], - next_page_token='ghi', - ), - maps_platform_datasets.ListDatasetsResponse( - datasets=[ - dataset.Dataset(), - dataset.Dataset(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_datasets(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, dataset.Dataset) - for i in results) -def test_list_datasets_pages(transport_name: str = "grpc"): - client = MapsPlatformDatasetsClient( - 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_datasets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - maps_platform_datasets.ListDatasetsResponse( - datasets=[ - dataset.Dataset(), - dataset.Dataset(), - dataset.Dataset(), - ], - next_page_token='abc', - ), - maps_platform_datasets.ListDatasetsResponse( - datasets=[], - next_page_token='def', - ), - maps_platform_datasets.ListDatasetsResponse( - datasets=[ - dataset.Dataset(), - ], - next_page_token='ghi', - ), - maps_platform_datasets.ListDatasetsResponse( - datasets=[ - dataset.Dataset(), - dataset.Dataset(), - ], - ), - RuntimeError, - ) - pages = list(client.list_datasets(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_datasets_async_pager(): - client = MapsPlatformDatasetsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_datasets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - maps_platform_datasets.ListDatasetsResponse( - datasets=[ - dataset.Dataset(), - dataset.Dataset(), - dataset.Dataset(), - ], - next_page_token='abc', - ), - maps_platform_datasets.ListDatasetsResponse( - datasets=[], - next_page_token='def', - ), - maps_platform_datasets.ListDatasetsResponse( - datasets=[ - dataset.Dataset(), - ], - next_page_token='ghi', - ), - maps_platform_datasets.ListDatasetsResponse( - datasets=[ - dataset.Dataset(), - dataset.Dataset(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_datasets(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, dataset.Dataset) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_datasets_async_pages(): - client = MapsPlatformDatasetsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_datasets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - maps_platform_datasets.ListDatasetsResponse( - datasets=[ - dataset.Dataset(), - dataset.Dataset(), - dataset.Dataset(), - ], - next_page_token='abc', - ), - maps_platform_datasets.ListDatasetsResponse( - datasets=[], - next_page_token='def', - ), - maps_platform_datasets.ListDatasetsResponse( - datasets=[ - dataset.Dataset(), - ], - next_page_token='ghi', - ), - maps_platform_datasets.ListDatasetsResponse( - datasets=[ - dataset.Dataset(), - dataset.Dataset(), - ], - ), - 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_datasets(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", [ - maps_platform_datasets.DeleteDatasetRequest, - dict, -]) -def test_delete_dataset(request_type, transport: str = 'grpc'): - client = MapsPlatformDatasetsClient( - 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_dataset), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_dataset(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = maps_platform_datasets.DeleteDatasetRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_dataset_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 = MapsPlatformDatasetsClient( - 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 = maps_platform_datasets.DeleteDatasetRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_dataset), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_dataset(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == maps_platform_datasets.DeleteDatasetRequest( - name='name_value', - ) - -def test_delete_dataset_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = MapsPlatformDatasetsClient( - 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_dataset in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_dataset] = mock_rpc - request = {} - client.delete_dataset(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_dataset(request) - - # Establish that a new wrapper 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_dataset_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = MapsPlatformDatasetsAsyncClient( - 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_dataset in client._client._transport._wrapped_methods - - # 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_dataset] = mock_rpc - - request = {} - await client.delete_dataset(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.delete_dataset(request) - - # Establish that a new wrapper 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_dataset_async(transport: str = 'grpc_asyncio', request_type=maps_platform_datasets.DeleteDatasetRequest): - client = MapsPlatformDatasetsAsyncClient( - 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_dataset), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_dataset(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = maps_platform_datasets.DeleteDatasetRequest() - 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_dataset_async_from_dict(): - await test_delete_dataset_async(request_type=dict) - -def test_delete_dataset_field_headers(): - client = MapsPlatformDatasetsClient( - 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 = maps_platform_datasets.DeleteDatasetRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_dataset), - '__call__') as call: - call.return_value = None - client.delete_dataset(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_dataset_field_headers_async(): - client = MapsPlatformDatasetsAsyncClient( - 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 = maps_platform_datasets.DeleteDatasetRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_dataset), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_dataset(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_dataset_flattened(): - client = MapsPlatformDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_dataset), - '__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_dataset( - 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_dataset_flattened_error(): - client = MapsPlatformDatasetsClient( - 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_dataset( - maps_platform_datasets.DeleteDatasetRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_dataset_flattened_async(): - client = MapsPlatformDatasetsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_dataset), - '__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_dataset( - 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_dataset_flattened_error_async(): - client = MapsPlatformDatasetsAsyncClient( - 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_dataset( - maps_platform_datasets.DeleteDatasetRequest(), - name='name_value', - ) - - -def test_create_dataset_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 = MapsPlatformDatasetsClient( - 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_dataset in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_dataset] = mock_rpc - - request = {} - client.create_dataset(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_dataset(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_dataset_rest_required_fields(request_type=maps_platform_datasets.CreateDatasetRequest): - transport_class = transports.MapsPlatformDatasetsRestTransport - - 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_dataset._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_dataset._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 = MapsPlatformDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gmm_dataset.Dataset() - # 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 = gmm_dataset.Dataset.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_dataset(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_dataset_rest_unset_required_fields(): - transport = transports.MapsPlatformDatasetsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_dataset._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "dataset", ))) - - -def test_create_dataset_rest_flattened(): - client = MapsPlatformDatasetsClient( - 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 = gmm_dataset.Dataset() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - dataset=gmm_dataset.Dataset(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 = gmm_dataset.Dataset.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_dataset(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*}/datasets" % client.transport._host, args[1]) - - -def test_create_dataset_rest_flattened_error(transport: str = 'rest'): - client = MapsPlatformDatasetsClient( - 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_dataset( - maps_platform_datasets.CreateDatasetRequest(), - parent='parent_value', - dataset=gmm_dataset.Dataset(name='name_value'), - ) - - -def test_update_dataset_metadata_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 = MapsPlatformDatasetsClient( - 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_dataset_metadata in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_dataset_metadata] = mock_rpc - - request = {} - client.update_dataset_metadata(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_dataset_metadata(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_dataset_metadata_rest_required_fields(request_type=maps_platform_datasets.UpdateDatasetMetadataRequest): - transport_class = transports.MapsPlatformDatasetsRestTransport - - 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_dataset_metadata._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_dataset_metadata._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 = MapsPlatformDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gmm_dataset.Dataset() - # 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 = gmm_dataset.Dataset.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_dataset_metadata(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_dataset_metadata_rest_unset_required_fields(): - transport = transports.MapsPlatformDatasetsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_dataset_metadata._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("dataset", ))) - - -def test_update_dataset_metadata_rest_flattened(): - client = MapsPlatformDatasetsClient( - 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 = gmm_dataset.Dataset() - - # get arguments that satisfy an http rule for this method - sample_request = {'dataset': {'name': 'projects/sample1/datasets/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - dataset=gmm_dataset.Dataset(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 = gmm_dataset.Dataset.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_dataset_metadata(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{dataset.name=projects/*/datasets/*}" % client.transport._host, args[1]) - - -def test_update_dataset_metadata_rest_flattened_error(transport: str = 'rest'): - client = MapsPlatformDatasetsClient( - 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_dataset_metadata( - maps_platform_datasets.UpdateDatasetMetadataRequest(), - dataset=gmm_dataset.Dataset(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_get_dataset_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 = MapsPlatformDatasetsClient( - 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_dataset in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_dataset] = mock_rpc - - request = {} - client.get_dataset(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_dataset(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_dataset_rest_required_fields(request_type=maps_platform_datasets.GetDatasetRequest): - transport_class = transports.MapsPlatformDatasetsRestTransport - - 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_dataset._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_dataset._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 = MapsPlatformDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = dataset.Dataset() - # 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 = dataset.Dataset.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_dataset(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_dataset_rest_unset_required_fields(): - transport = transports.MapsPlatformDatasetsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_dataset._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_dataset_rest_flattened(): - client = MapsPlatformDatasetsClient( - 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 = dataset.Dataset() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/datasets/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 = dataset.Dataset.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_dataset(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/datasets/*}" % client.transport._host, args[1]) - - -def test_get_dataset_rest_flattened_error(transport: str = 'rest'): - client = MapsPlatformDatasetsClient( - 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_dataset( - maps_platform_datasets.GetDatasetRequest(), - name='name_value', - ) - - -def test_fetch_dataset_errors_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 = MapsPlatformDatasetsClient( - 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.fetch_dataset_errors in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.fetch_dataset_errors] = mock_rpc - - request = {} - client.fetch_dataset_errors(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.fetch_dataset_errors(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_fetch_dataset_errors_rest_required_fields(request_type=maps_platform_datasets.FetchDatasetErrorsRequest): - transport_class = transports.MapsPlatformDatasetsRestTransport - - request_init = {} - request_init["dataset"] = "" - request = 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()).fetch_dataset_errors._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["dataset"] = 'dataset_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).fetch_dataset_errors._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 "dataset" in jsonified_request - assert jsonified_request["dataset"] == 'dataset_value' - - client = MapsPlatformDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = maps_platform_datasets.FetchDatasetErrorsResponse() - # 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 = maps_platform_datasets.FetchDatasetErrorsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.fetch_dataset_errors(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_fetch_dataset_errors_rest_unset_required_fields(): - transport = transports.MapsPlatformDatasetsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.fetch_dataset_errors._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("dataset", ))) - - -def test_fetch_dataset_errors_rest_flattened(): - client = MapsPlatformDatasetsClient( - 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 = maps_platform_datasets.FetchDatasetErrorsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'dataset': 'projects/sample1/datasets/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - dataset='dataset_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 = maps_platform_datasets.FetchDatasetErrorsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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.fetch_dataset_errors(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{dataset=projects/*/datasets/*}:fetchDatasetErrors" % client.transport._host, args[1]) - - -def test_fetch_dataset_errors_rest_flattened_error(transport: str = 'rest'): - client = MapsPlatformDatasetsClient( - 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.fetch_dataset_errors( - maps_platform_datasets.FetchDatasetErrorsRequest(), - dataset='dataset_value', - ) - - -def test_fetch_dataset_errors_rest_pager(transport: str = 'rest'): - client = MapsPlatformDatasetsClient( - 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 = ( - maps_platform_datasets.FetchDatasetErrorsResponse( - errors=[ - status_pb2.Status(), - status_pb2.Status(), - status_pb2.Status(), - ], - next_page_token='abc', - ), - maps_platform_datasets.FetchDatasetErrorsResponse( - errors=[], - next_page_token='def', - ), - maps_platform_datasets.FetchDatasetErrorsResponse( - errors=[ - status_pb2.Status(), - ], - next_page_token='ghi', - ), - maps_platform_datasets.FetchDatasetErrorsResponse( - errors=[ - status_pb2.Status(), - status_pb2.Status(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(maps_platform_datasets.FetchDatasetErrorsResponse.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 = {'dataset': 'projects/sample1/datasets/sample2'} - - pager = client.fetch_dataset_errors(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, status_pb2.Status) - for i in results) - - pages = list(client.fetch_dataset_errors(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_list_datasets_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 = MapsPlatformDatasetsClient( - 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_datasets in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_datasets] = mock_rpc - - request = {} - client.list_datasets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_datasets(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_datasets_rest_required_fields(request_type=maps_platform_datasets.ListDatasetsRequest): - transport_class = transports.MapsPlatformDatasetsRestTransport - - 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_datasets._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_datasets._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", "tag", )) - 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 = MapsPlatformDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = maps_platform_datasets.ListDatasetsResponse() - # 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 = maps_platform_datasets.ListDatasetsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_datasets(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_datasets_rest_unset_required_fields(): - transport = transports.MapsPlatformDatasetsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_datasets._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", "tag", )) & set(("parent", ))) - - -def test_list_datasets_rest_flattened(): - client = MapsPlatformDatasetsClient( - 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 = maps_platform_datasets.ListDatasetsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/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 = maps_platform_datasets.ListDatasetsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_datasets(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*}/datasets" % client.transport._host, args[1]) - - -def test_list_datasets_rest_flattened_error(transport: str = 'rest'): - client = MapsPlatformDatasetsClient( - 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_datasets( - maps_platform_datasets.ListDatasetsRequest(), - parent='parent_value', - ) - - -def test_list_datasets_rest_pager(transport: str = 'rest'): - client = MapsPlatformDatasetsClient( - 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 = ( - maps_platform_datasets.ListDatasetsResponse( - datasets=[ - dataset.Dataset(), - dataset.Dataset(), - dataset.Dataset(), - ], - next_page_token='abc', - ), - maps_platform_datasets.ListDatasetsResponse( - datasets=[], - next_page_token='def', - ), - maps_platform_datasets.ListDatasetsResponse( - datasets=[ - dataset.Dataset(), - ], - next_page_token='ghi', - ), - maps_platform_datasets.ListDatasetsResponse( - datasets=[ - dataset.Dataset(), - dataset.Dataset(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(maps_platform_datasets.ListDatasetsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1'} - - pager = client.list_datasets(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, dataset.Dataset) - for i in results) - - pages = list(client.list_datasets(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_delete_dataset_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 = MapsPlatformDatasetsClient( - 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_dataset in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_dataset] = mock_rpc - - request = {} - client.delete_dataset(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_dataset(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_dataset_rest_required_fields(request_type=maps_platform_datasets.DeleteDatasetRequest): - transport_class = transports.MapsPlatformDatasetsRestTransport - - 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_dataset._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_dataset._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 = MapsPlatformDatasetsClient( - 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_dataset(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_dataset_rest_unset_required_fields(): - transport = transports.MapsPlatformDatasetsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_dataset._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_delete_dataset_rest_flattened(): - client = MapsPlatformDatasetsClient( - 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': 'projects/sample1/datasets/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_dataset(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/datasets/*}" % client.transport._host, args[1]) - - -def test_delete_dataset_rest_flattened_error(transport: str = 'rest'): - client = MapsPlatformDatasetsClient( - 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_dataset( - maps_platform_datasets.DeleteDatasetRequest(), - name='name_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.MapsPlatformDatasetsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = MapsPlatformDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.MapsPlatformDatasetsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = MapsPlatformDatasetsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.MapsPlatformDatasetsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = MapsPlatformDatasetsClient( - 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 = MapsPlatformDatasetsClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.MapsPlatformDatasetsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = MapsPlatformDatasetsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.MapsPlatformDatasetsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = MapsPlatformDatasetsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.MapsPlatformDatasetsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.MapsPlatformDatasetsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.MapsPlatformDatasetsGrpcTransport, - transports.MapsPlatformDatasetsGrpcAsyncIOTransport, - transports.MapsPlatformDatasetsRestTransport, -]) -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 = MapsPlatformDatasetsClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = MapsPlatformDatasetsClient( - 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_create_dataset_empty_call_grpc(): - client = MapsPlatformDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_dataset), - '__call__') as call: - call.return_value = gmm_dataset.Dataset() - client.create_dataset(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = maps_platform_datasets.CreateDatasetRequest() - - assert args[0] == request_msg - - -# This 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_dataset_metadata_empty_call_grpc(): - client = MapsPlatformDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_dataset_metadata), - '__call__') as call: - call.return_value = gmm_dataset.Dataset() - client.update_dataset_metadata(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = maps_platform_datasets.UpdateDatasetMetadataRequest() - - assert args[0] == request_msg - - -# This 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_dataset_empty_call_grpc(): - client = MapsPlatformDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_dataset), - '__call__') as call: - call.return_value = dataset.Dataset() - client.get_dataset(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = maps_platform_datasets.GetDatasetRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_fetch_dataset_errors_empty_call_grpc(): - client = MapsPlatformDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.fetch_dataset_errors), - '__call__') as call: - call.return_value = maps_platform_datasets.FetchDatasetErrorsResponse() - client.fetch_dataset_errors(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = maps_platform_datasets.FetchDatasetErrorsRequest() - - assert args[0] == request_msg - - -# This 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_datasets_empty_call_grpc(): - client = MapsPlatformDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_datasets), - '__call__') as call: - call.return_value = maps_platform_datasets.ListDatasetsResponse() - client.list_datasets(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = maps_platform_datasets.ListDatasetsRequest() - - assert args[0] == request_msg - - -# This 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_dataset_empty_call_grpc(): - client = MapsPlatformDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_dataset), - '__call__') as call: - call.return_value = None - client.delete_dataset(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = maps_platform_datasets.DeleteDatasetRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = MapsPlatformDatasetsAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = MapsPlatformDatasetsAsyncClient( - 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_create_dataset_empty_call_grpc_asyncio(): - client = MapsPlatformDatasetsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_dataset), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gmm_dataset.Dataset( - name='name_value', - display_name='display_name_value', - description='description_value', - version_id='version_id_value', - usage=[gmm_dataset.Usage.USAGE_DATA_DRIVEN_STYLING], - version_description='version_description_value', - )) - await client.create_dataset(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = maps_platform_datasets.CreateDatasetRequest() - - assert args[0] == request_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_dataset_metadata_empty_call_grpc_asyncio(): - client = MapsPlatformDatasetsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_dataset_metadata), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gmm_dataset.Dataset( - name='name_value', - display_name='display_name_value', - description='description_value', - version_id='version_id_value', - usage=[gmm_dataset.Usage.USAGE_DATA_DRIVEN_STYLING], - version_description='version_description_value', - )) - await client.update_dataset_metadata(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = maps_platform_datasets.UpdateDatasetMetadataRequest() - - assert args[0] == request_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_dataset_empty_call_grpc_asyncio(): - client = MapsPlatformDatasetsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_dataset), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dataset.Dataset( - name='name_value', - display_name='display_name_value', - description='description_value', - version_id='version_id_value', - usage=[dataset.Usage.USAGE_DATA_DRIVEN_STYLING], - version_description='version_description_value', - )) - await client.get_dataset(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = maps_platform_datasets.GetDatasetRequest() - - assert args[0] == request_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_fetch_dataset_errors_empty_call_grpc_asyncio(): - client = MapsPlatformDatasetsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.fetch_dataset_errors), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(maps_platform_datasets.FetchDatasetErrorsResponse( - next_page_token='next_page_token_value', - )) - await client.fetch_dataset_errors(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = maps_platform_datasets.FetchDatasetErrorsRequest() - - assert args[0] == request_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_datasets_empty_call_grpc_asyncio(): - client = MapsPlatformDatasetsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_datasets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(maps_platform_datasets.ListDatasetsResponse( - next_page_token='next_page_token_value', - )) - await client.list_datasets(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = maps_platform_datasets.ListDatasetsRequest() - - assert args[0] == request_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_dataset_empty_call_grpc_asyncio(): - client = MapsPlatformDatasetsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_dataset), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_dataset(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = maps_platform_datasets.DeleteDatasetRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = MapsPlatformDatasetsClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_create_dataset_rest_bad_request(request_type=maps_platform_datasets.CreateDatasetRequest): - client = MapsPlatformDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/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_dataset(request) - - -@pytest.mark.parametrize("request_type", [ - maps_platform_datasets.CreateDatasetRequest, - dict, -]) -def test_create_dataset_rest_call_success(request_type): - client = MapsPlatformDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request_init["dataset"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'version_id': 'version_id_value', 'usage': [1], 'local_file_source': {'filename': 'filename_value', 'file_format': 1}, 'gcs_source': {'input_uri': 'input_uri_value', 'file_format': 1}, 'status': {'state': 1, 'error_message': 'error_message_value'}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'version_create_time': {}, 'version_description': 'version_description_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 = maps_platform_datasets.CreateDatasetRequest.meta.fields["dataset"] - - 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["dataset"].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["dataset"][field])): - del request_init["dataset"][field][i][subfield] - else: - del request_init["dataset"][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 = gmm_dataset.Dataset( - name='name_value', - display_name='display_name_value', - description='description_value', - version_id='version_id_value', - usage=[gmm_dataset.Usage.USAGE_DATA_DRIVEN_STYLING], - version_description='version_description_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 = gmm_dataset.Dataset.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_dataset(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gmm_dataset.Dataset) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.version_id == 'version_id_value' - assert response.usage == [gmm_dataset.Usage.USAGE_DATA_DRIVEN_STYLING] - assert response.version_description == 'version_description_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_dataset_rest_interceptors(null_interceptor): - transport = transports.MapsPlatformDatasetsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.MapsPlatformDatasetsRestInterceptor(), - ) - client = MapsPlatformDatasetsClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.MapsPlatformDatasetsRestInterceptor, "post_create_dataset") as post, \ - mock.patch.object(transports.MapsPlatformDatasetsRestInterceptor, "pre_create_dataset") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = maps_platform_datasets.CreateDatasetRequest.pb(maps_platform_datasets.CreateDatasetRequest()) - 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 = gmm_dataset.Dataset.to_json(gmm_dataset.Dataset()) - req.return_value.content = return_value - - request = maps_platform_datasets.CreateDatasetRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gmm_dataset.Dataset() - - client.create_dataset(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_dataset_metadata_rest_bad_request(request_type=maps_platform_datasets.UpdateDatasetMetadataRequest): - client = MapsPlatformDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'dataset': {'name': 'projects/sample1/datasets/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_dataset_metadata(request) - - -@pytest.mark.parametrize("request_type", [ - maps_platform_datasets.UpdateDatasetMetadataRequest, - dict, -]) -def test_update_dataset_metadata_rest_call_success(request_type): - client = MapsPlatformDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'dataset': {'name': 'projects/sample1/datasets/sample2'}} - request_init["dataset"] = {'name': 'projects/sample1/datasets/sample2', 'display_name': 'display_name_value', 'description': 'description_value', 'version_id': 'version_id_value', 'usage': [1], 'local_file_source': {'filename': 'filename_value', 'file_format': 1}, 'gcs_source': {'input_uri': 'input_uri_value', 'file_format': 1}, 'status': {'state': 1, 'error_message': 'error_message_value'}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'version_create_time': {}, 'version_description': 'version_description_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 = maps_platform_datasets.UpdateDatasetMetadataRequest.meta.fields["dataset"] - - 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["dataset"].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["dataset"][field])): - del request_init["dataset"][field][i][subfield] - else: - del request_init["dataset"][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 = gmm_dataset.Dataset( - name='name_value', - display_name='display_name_value', - description='description_value', - version_id='version_id_value', - usage=[gmm_dataset.Usage.USAGE_DATA_DRIVEN_STYLING], - version_description='version_description_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 = gmm_dataset.Dataset.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_dataset_metadata(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gmm_dataset.Dataset) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.version_id == 'version_id_value' - assert response.usage == [gmm_dataset.Usage.USAGE_DATA_DRIVEN_STYLING] - assert response.version_description == 'version_description_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_dataset_metadata_rest_interceptors(null_interceptor): - transport = transports.MapsPlatformDatasetsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.MapsPlatformDatasetsRestInterceptor(), - ) - client = MapsPlatformDatasetsClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.MapsPlatformDatasetsRestInterceptor, "post_update_dataset_metadata") as post, \ - mock.patch.object(transports.MapsPlatformDatasetsRestInterceptor, "pre_update_dataset_metadata") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = maps_platform_datasets.UpdateDatasetMetadataRequest.pb(maps_platform_datasets.UpdateDatasetMetadataRequest()) - 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 = gmm_dataset.Dataset.to_json(gmm_dataset.Dataset()) - req.return_value.content = return_value - - request = maps_platform_datasets.UpdateDatasetMetadataRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gmm_dataset.Dataset() - - client.update_dataset_metadata(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_dataset_rest_bad_request(request_type=maps_platform_datasets.GetDatasetRequest): - client = MapsPlatformDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/datasets/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_dataset(request) - - -@pytest.mark.parametrize("request_type", [ - maps_platform_datasets.GetDatasetRequest, - dict, -]) -def test_get_dataset_rest_call_success(request_type): - client = MapsPlatformDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/datasets/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 = dataset.Dataset( - name='name_value', - display_name='display_name_value', - description='description_value', - version_id='version_id_value', - usage=[dataset.Usage.USAGE_DATA_DRIVEN_STYLING], - version_description='version_description_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 = dataset.Dataset.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_dataset(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, dataset.Dataset) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.version_id == 'version_id_value' - assert response.usage == [dataset.Usage.USAGE_DATA_DRIVEN_STYLING] - assert response.version_description == 'version_description_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_dataset_rest_interceptors(null_interceptor): - transport = transports.MapsPlatformDatasetsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.MapsPlatformDatasetsRestInterceptor(), - ) - client = MapsPlatformDatasetsClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.MapsPlatformDatasetsRestInterceptor, "post_get_dataset") as post, \ - mock.patch.object(transports.MapsPlatformDatasetsRestInterceptor, "pre_get_dataset") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = maps_platform_datasets.GetDatasetRequest.pb(maps_platform_datasets.GetDatasetRequest()) - 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 = dataset.Dataset.to_json(dataset.Dataset()) - req.return_value.content = return_value - - request = maps_platform_datasets.GetDatasetRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = dataset.Dataset() - - client.get_dataset(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_fetch_dataset_errors_rest_bad_request(request_type=maps_platform_datasets.FetchDatasetErrorsRequest): - client = MapsPlatformDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'dataset': 'projects/sample1/datasets/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.fetch_dataset_errors(request) - - -@pytest.mark.parametrize("request_type", [ - maps_platform_datasets.FetchDatasetErrorsRequest, - dict, -]) -def test_fetch_dataset_errors_rest_call_success(request_type): - client = MapsPlatformDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'dataset': 'projects/sample1/datasets/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 = maps_platform_datasets.FetchDatasetErrorsResponse( - 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 = maps_platform_datasets.FetchDatasetErrorsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.fetch_dataset_errors(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.FetchDatasetErrorsPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_fetch_dataset_errors_rest_interceptors(null_interceptor): - transport = transports.MapsPlatformDatasetsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.MapsPlatformDatasetsRestInterceptor(), - ) - client = MapsPlatformDatasetsClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.MapsPlatformDatasetsRestInterceptor, "post_fetch_dataset_errors") as post, \ - mock.patch.object(transports.MapsPlatformDatasetsRestInterceptor, "pre_fetch_dataset_errors") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = maps_platform_datasets.FetchDatasetErrorsRequest.pb(maps_platform_datasets.FetchDatasetErrorsRequest()) - 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 = maps_platform_datasets.FetchDatasetErrorsResponse.to_json(maps_platform_datasets.FetchDatasetErrorsResponse()) - req.return_value.content = return_value - - request = maps_platform_datasets.FetchDatasetErrorsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = maps_platform_datasets.FetchDatasetErrorsResponse() - - client.fetch_dataset_errors(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_datasets_rest_bad_request(request_type=maps_platform_datasets.ListDatasetsRequest): - client = MapsPlatformDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/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_datasets(request) - - -@pytest.mark.parametrize("request_type", [ - maps_platform_datasets.ListDatasetsRequest, - dict, -]) -def test_list_datasets_rest_call_success(request_type): - client = MapsPlatformDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = maps_platform_datasets.ListDatasetsResponse( - 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 = maps_platform_datasets.ListDatasetsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_datasets(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDatasetsPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_datasets_rest_interceptors(null_interceptor): - transport = transports.MapsPlatformDatasetsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.MapsPlatformDatasetsRestInterceptor(), - ) - client = MapsPlatformDatasetsClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.MapsPlatformDatasetsRestInterceptor, "post_list_datasets") as post, \ - mock.patch.object(transports.MapsPlatformDatasetsRestInterceptor, "pre_list_datasets") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = maps_platform_datasets.ListDatasetsRequest.pb(maps_platform_datasets.ListDatasetsRequest()) - 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 = maps_platform_datasets.ListDatasetsResponse.to_json(maps_platform_datasets.ListDatasetsResponse()) - req.return_value.content = return_value - - request = maps_platform_datasets.ListDatasetsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = maps_platform_datasets.ListDatasetsResponse() - - client.list_datasets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_dataset_rest_bad_request(request_type=maps_platform_datasets.DeleteDatasetRequest): - client = MapsPlatformDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/datasets/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_dataset(request) - - -@pytest.mark.parametrize("request_type", [ - maps_platform_datasets.DeleteDatasetRequest, - dict, -]) -def test_delete_dataset_rest_call_success(request_type): - client = MapsPlatformDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/datasets/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_dataset(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_dataset_rest_interceptors(null_interceptor): - transport = transports.MapsPlatformDatasetsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.MapsPlatformDatasetsRestInterceptor(), - ) - client = MapsPlatformDatasetsClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.MapsPlatformDatasetsRestInterceptor, "pre_delete_dataset") as pre: - pre.assert_not_called() - pb_message = maps_platform_datasets.DeleteDatasetRequest.pb(maps_platform_datasets.DeleteDatasetRequest()) - 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 = maps_platform_datasets.DeleteDatasetRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_dataset(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - -def test_initialize_client_w_rest(): - client = MapsPlatformDatasetsClient( - 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_create_dataset_empty_call_rest(): - client = MapsPlatformDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_dataset), - '__call__') as call: - client.create_dataset(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = maps_platform_datasets.CreateDatasetRequest() - - assert args[0] == request_msg - - -# This 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_dataset_metadata_empty_call_rest(): - client = MapsPlatformDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_dataset_metadata), - '__call__') as call: - client.update_dataset_metadata(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = maps_platform_datasets.UpdateDatasetMetadataRequest() - - assert args[0] == request_msg - - -# This 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_dataset_empty_call_rest(): - client = MapsPlatformDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_dataset), - '__call__') as call: - client.get_dataset(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = maps_platform_datasets.GetDatasetRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_fetch_dataset_errors_empty_call_rest(): - client = MapsPlatformDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.fetch_dataset_errors), - '__call__') as call: - client.fetch_dataset_errors(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = maps_platform_datasets.FetchDatasetErrorsRequest() - - assert args[0] == request_msg - - -# This 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_datasets_empty_call_rest(): - client = MapsPlatformDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_datasets), - '__call__') as call: - client.list_datasets(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = maps_platform_datasets.ListDatasetsRequest() - - assert args[0] == request_msg - - -# This 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_dataset_empty_call_rest(): - client = MapsPlatformDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_dataset), - '__call__') as call: - client.delete_dataset(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = maps_platform_datasets.DeleteDatasetRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = MapsPlatformDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.MapsPlatformDatasetsGrpcTransport, - ) - -def test_maps_platform_datasets_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.MapsPlatformDatasetsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_maps_platform_datasets_base_transport(): - # Instantiate the base transport. - with mock.patch('google.maps.mapsplatformdatasets_v1.services.maps_platform_datasets.transports.MapsPlatformDatasetsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.MapsPlatformDatasetsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_dataset', - 'update_dataset_metadata', - 'get_dataset', - 'fetch_dataset_errors', - 'list_datasets', - 'delete_dataset', - ) - 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_maps_platform_datasets_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.maps.mapsplatformdatasets_v1.services.maps_platform_datasets.transports.MapsPlatformDatasetsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.MapsPlatformDatasetsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_maps_platform_datasets_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.maps.mapsplatformdatasets_v1.services.maps_platform_datasets.transports.MapsPlatformDatasetsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.MapsPlatformDatasetsTransport() - adc.assert_called_once() - - -def test_maps_platform_datasets_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) - MapsPlatformDatasetsClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.MapsPlatformDatasetsGrpcTransport, - transports.MapsPlatformDatasetsGrpcAsyncIOTransport, - ], -) -def test_maps_platform_datasets_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.MapsPlatformDatasetsGrpcTransport, - transports.MapsPlatformDatasetsGrpcAsyncIOTransport, - transports.MapsPlatformDatasetsRestTransport, - ], -) -def test_maps_platform_datasets_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.MapsPlatformDatasetsGrpcTransport, grpc_helpers), - (transports.MapsPlatformDatasetsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_maps_platform_datasets_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( - "mapsplatformdatasets.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=["1", "2"], - default_host="mapsplatformdatasets.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.MapsPlatformDatasetsGrpcTransport, transports.MapsPlatformDatasetsGrpcAsyncIOTransport]) -def test_maps_platform_datasets_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_maps_platform_datasets_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.MapsPlatformDatasetsRestTransport ( - 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_maps_platform_datasets_host_no_port(transport_name): - client = MapsPlatformDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='mapsplatformdatasets.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'mapsplatformdatasets.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://mapsplatformdatasets.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_maps_platform_datasets_host_with_port(transport_name): - client = MapsPlatformDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='mapsplatformdatasets.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'mapsplatformdatasets.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://mapsplatformdatasets.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_maps_platform_datasets_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = MapsPlatformDatasetsClient( - credentials=creds1, - transport=transport_name, - ) - client2 = MapsPlatformDatasetsClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.create_dataset._session - session2 = client2.transport.create_dataset._session - assert session1 != session2 - session1 = client1.transport.update_dataset_metadata._session - session2 = client2.transport.update_dataset_metadata._session - assert session1 != session2 - session1 = client1.transport.get_dataset._session - session2 = client2.transport.get_dataset._session - assert session1 != session2 - session1 = client1.transport.fetch_dataset_errors._session - session2 = client2.transport.fetch_dataset_errors._session - assert session1 != session2 - session1 = client1.transport.list_datasets._session - session2 = client2.transport.list_datasets._session - assert session1 != session2 - session1 = client1.transport.delete_dataset._session - session2 = client2.transport.delete_dataset._session - assert session1 != session2 -def test_maps_platform_datasets_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.MapsPlatformDatasetsGrpcTransport( - 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_maps_platform_datasets_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.MapsPlatformDatasetsGrpcAsyncIOTransport( - 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.MapsPlatformDatasetsGrpcTransport, transports.MapsPlatformDatasetsGrpcAsyncIOTransport]) -def test_maps_platform_datasets_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.MapsPlatformDatasetsGrpcTransport, transports.MapsPlatformDatasetsGrpcAsyncIOTransport]) -def test_maps_platform_datasets_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_dataset_path(): - project = "squid" - dataset = "clam" - expected = "projects/{project}/datasets/{dataset}".format(project=project, dataset=dataset, ) - actual = MapsPlatformDatasetsClient.dataset_path(project, dataset) - assert expected == actual - - -def test_parse_dataset_path(): - expected = { - "project": "whelk", - "dataset": "octopus", - } - path = MapsPlatformDatasetsClient.dataset_path(**expected) - - # Check that the path construction is reversible. - actual = MapsPlatformDatasetsClient.parse_dataset_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = MapsPlatformDatasetsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = MapsPlatformDatasetsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = MapsPlatformDatasetsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = MapsPlatformDatasetsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = MapsPlatformDatasetsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = MapsPlatformDatasetsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = MapsPlatformDatasetsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = MapsPlatformDatasetsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = MapsPlatformDatasetsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = MapsPlatformDatasetsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = MapsPlatformDatasetsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = MapsPlatformDatasetsClient.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 = MapsPlatformDatasetsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = MapsPlatformDatasetsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = MapsPlatformDatasetsClient.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.MapsPlatformDatasetsTransport, '_prep_wrapped_messages') as prep: - client = MapsPlatformDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.MapsPlatformDatasetsTransport, '_prep_wrapped_messages') as prep: - transport_class = MapsPlatformDatasetsClient.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 = MapsPlatformDatasetsClient( - 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 = MapsPlatformDatasetsAsyncClient( - 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 = MapsPlatformDatasetsClient( - 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 = MapsPlatformDatasetsClient( - 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", [ - (MapsPlatformDatasetsClient, transports.MapsPlatformDatasetsGrpcTransport), - (MapsPlatformDatasetsAsyncClient, transports.MapsPlatformDatasetsGrpcAsyncIOTransport), -]) -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-maps-places/v1/.coveragerc b/owl-bot-staging/google-maps-places/v1/.coveragerc deleted file mode 100644 index 85cb2db49afb..000000000000 --- a/owl-bot-staging/google-maps-places/v1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/maps/places/__init__.py - google/maps/places/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-maps-places/v1/.flake8 b/owl-bot-staging/google-maps-places/v1/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-maps-places/v1/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/google-maps-places/v1/MANIFEST.in b/owl-bot-staging/google-maps-places/v1/MANIFEST.in deleted file mode 100644 index aca0ee5357fb..000000000000 --- a/owl-bot-staging/google-maps-places/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/maps/places *.py -recursive-include google/maps/places_v1 *.py diff --git a/owl-bot-staging/google-maps-places/v1/README.rst b/owl-bot-staging/google-maps-places/v1/README.rst deleted file mode 100644 index a4719af79336..000000000000 --- a/owl-bot-staging/google-maps-places/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Maps Places 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 Maps Places 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 diff --git a/owl-bot-staging/google-maps-places/v1/docs/_static/custom.css b/owl-bot-staging/google-maps-places/v1/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-maps-places/v1/docs/_static/custom.css +++ /dev/null @@ -1,3 +0,0 @@ -dl.field-list > dt { - min-width: 100px -} diff --git a/owl-bot-staging/google-maps-places/v1/docs/conf.py b/owl-bot-staging/google-maps-places/v1/docs/conf.py deleted file mode 100644 index db77e54d8b8d..000000000000 --- a/owl-bot-staging/google-maps-places/v1/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-maps-places 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("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# 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.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -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-maps-places" -copyright = u"2023, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# 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 = 'en' - -# 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"] - -# 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 Maps Client Libraries for Python", - "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-maps-places-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-maps-places.tex", - u"google-maps-places 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-maps-places", - u"Google Maps Places 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-maps-places", - u"google-maps-places Documentation", - author, - "google-maps-places", - "GAPIC library for Google Maps Places API", - "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": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", 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-maps-places/v1/docs/index.rst b/owl-bot-staging/google-maps-places/v1/docs/index.rst deleted file mode 100644 index bb4fadc1e6f8..000000000000 --- a/owl-bot-staging/google-maps-places/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - places_v1/services_ - places_v1/types_ diff --git a/owl-bot-staging/google-maps-places/v1/docs/places_v1/places.rst b/owl-bot-staging/google-maps-places/v1/docs/places_v1/places.rst deleted file mode 100644 index cf160d2126f2..000000000000 --- a/owl-bot-staging/google-maps-places/v1/docs/places_v1/places.rst +++ /dev/null @@ -1,6 +0,0 @@ -Places ------------------------- - -.. automodule:: google.maps.places_v1.services.places - :members: - :inherited-members: diff --git a/owl-bot-staging/google-maps-places/v1/docs/places_v1/services_.rst b/owl-bot-staging/google-maps-places/v1/docs/places_v1/services_.rst deleted file mode 100644 index 91337ff78a9a..000000000000 --- a/owl-bot-staging/google-maps-places/v1/docs/places_v1/services_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Maps Places v1 API -====================================== -.. toctree:: - :maxdepth: 2 - - places diff --git a/owl-bot-staging/google-maps-places/v1/docs/places_v1/types_.rst b/owl-bot-staging/google-maps-places/v1/docs/places_v1/types_.rst deleted file mode 100644 index d634d52d3f87..000000000000 --- a/owl-bot-staging/google-maps-places/v1/docs/places_v1/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Maps Places v1 API -=================================== - -.. automodule:: google.maps.places_v1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places/__init__.py b/owl-bot-staging/google-maps-places/v1/google/maps/places/__init__.py deleted file mode 100644 index b6e255b38d0f..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places/__init__.py +++ /dev/null @@ -1,83 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.places import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.maps.places_v1.services.places.client import PlacesClient -from google.maps.places_v1.services.places.async_client import PlacesAsyncClient - -from google.maps.places_v1.types.attribution import AuthorAttribution -from google.maps.places_v1.types.content_block import ContentBlock -from google.maps.places_v1.types.contextual_content import ContextualContent -from google.maps.places_v1.types.ev_charging import EVChargeOptions -from google.maps.places_v1.types.ev_charging import EVConnectorType -from google.maps.places_v1.types.fuel_options import FuelOptions -from google.maps.places_v1.types.geometry import Circle -from google.maps.places_v1.types.photo import Photo -from google.maps.places_v1.types.place import Place -from google.maps.places_v1.types.place import PriceLevel -from google.maps.places_v1.types.places_service import AutocompletePlacesRequest -from google.maps.places_v1.types.places_service import AutocompletePlacesResponse -from google.maps.places_v1.types.places_service import GetPhotoMediaRequest -from google.maps.places_v1.types.places_service import GetPlaceRequest -from google.maps.places_v1.types.places_service import PhotoMedia -from google.maps.places_v1.types.places_service import RoutingParameters -from google.maps.places_v1.types.places_service import SearchNearbyRequest -from google.maps.places_v1.types.places_service import SearchNearbyResponse -from google.maps.places_v1.types.places_service import SearchTextRequest -from google.maps.places_v1.types.places_service import SearchTextResponse -from google.maps.places_v1.types.polyline import Polyline -from google.maps.places_v1.types.price_range import PriceRange -from google.maps.places_v1.types.reference import References -from google.maps.places_v1.types.review import Review -from google.maps.places_v1.types.route_modifiers import RouteModifiers -from google.maps.places_v1.types.routing_preference import RoutingPreference -from google.maps.places_v1.types.routing_summary import RoutingSummary -from google.maps.places_v1.types.travel_mode import TravelMode - -__all__ = ('PlacesClient', - 'PlacesAsyncClient', - 'AuthorAttribution', - 'ContentBlock', - 'ContextualContent', - 'EVChargeOptions', - 'EVConnectorType', - 'FuelOptions', - 'Circle', - 'Photo', - 'Place', - 'PriceLevel', - 'AutocompletePlacesRequest', - 'AutocompletePlacesResponse', - 'GetPhotoMediaRequest', - 'GetPlaceRequest', - 'PhotoMedia', - 'RoutingParameters', - 'SearchNearbyRequest', - 'SearchNearbyResponse', - 'SearchTextRequest', - 'SearchTextResponse', - 'Polyline', - 'PriceRange', - 'References', - 'Review', - 'RouteModifiers', - 'RoutingPreference', - 'RoutingSummary', - 'TravelMode', -) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places/gapic_version.py b/owl-bot-staging/google-maps-places/v1/google/maps/places/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-maps-places/v1/google/maps/places/py.typed b/owl-bot-staging/google-maps-places/v1/google/maps/places/py.typed deleted file mode 100644 index ae821546ded2..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-maps-places package uses inline types. diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/__init__.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/__init__.py deleted file mode 100644 index 42c0424e3800..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/__init__.py +++ /dev/null @@ -1,84 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.places_v1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.places import PlacesClient -from .services.places import PlacesAsyncClient - -from .types.attribution import AuthorAttribution -from .types.content_block import ContentBlock -from .types.contextual_content import ContextualContent -from .types.ev_charging import EVChargeOptions -from .types.ev_charging import EVConnectorType -from .types.fuel_options import FuelOptions -from .types.geometry import Circle -from .types.photo import Photo -from .types.place import Place -from .types.place import PriceLevel -from .types.places_service import AutocompletePlacesRequest -from .types.places_service import AutocompletePlacesResponse -from .types.places_service import GetPhotoMediaRequest -from .types.places_service import GetPlaceRequest -from .types.places_service import PhotoMedia -from .types.places_service import RoutingParameters -from .types.places_service import SearchNearbyRequest -from .types.places_service import SearchNearbyResponse -from .types.places_service import SearchTextRequest -from .types.places_service import SearchTextResponse -from .types.polyline import Polyline -from .types.price_range import PriceRange -from .types.reference import References -from .types.review import Review -from .types.route_modifiers import RouteModifiers -from .types.routing_preference import RoutingPreference -from .types.routing_summary import RoutingSummary -from .types.travel_mode import TravelMode - -__all__ = ( - 'PlacesAsyncClient', -'AuthorAttribution', -'AutocompletePlacesRequest', -'AutocompletePlacesResponse', -'Circle', -'ContentBlock', -'ContextualContent', -'EVChargeOptions', -'EVConnectorType', -'FuelOptions', -'GetPhotoMediaRequest', -'GetPlaceRequest', -'Photo', -'PhotoMedia', -'Place', -'PlacesClient', -'Polyline', -'PriceLevel', -'PriceRange', -'References', -'Review', -'RouteModifiers', -'RoutingParameters', -'RoutingPreference', -'RoutingSummary', -'SearchNearbyRequest', -'SearchNearbyResponse', -'SearchTextRequest', -'SearchTextResponse', -'TravelMode', -) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/gapic_metadata.json b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/gapic_metadata.json deleted file mode 100644 index 00da5ef96769..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/gapic_metadata.json +++ /dev/null @@ -1,103 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.maps.places_v1", - "protoPackage": "google.maps.places.v1", - "schema": "1.0", - "services": { - "Places": { - "clients": { - "grpc": { - "libraryClient": "PlacesClient", - "rpcs": { - "AutocompletePlaces": { - "methods": [ - "autocomplete_places" - ] - }, - "GetPhotoMedia": { - "methods": [ - "get_photo_media" - ] - }, - "GetPlace": { - "methods": [ - "get_place" - ] - }, - "SearchNearby": { - "methods": [ - "search_nearby" - ] - }, - "SearchText": { - "methods": [ - "search_text" - ] - } - } - }, - "grpc-async": { - "libraryClient": "PlacesAsyncClient", - "rpcs": { - "AutocompletePlaces": { - "methods": [ - "autocomplete_places" - ] - }, - "GetPhotoMedia": { - "methods": [ - "get_photo_media" - ] - }, - "GetPlace": { - "methods": [ - "get_place" - ] - }, - "SearchNearby": { - "methods": [ - "search_nearby" - ] - }, - "SearchText": { - "methods": [ - "search_text" - ] - } - } - }, - "rest": { - "libraryClient": "PlacesClient", - "rpcs": { - "AutocompletePlaces": { - "methods": [ - "autocomplete_places" - ] - }, - "GetPhotoMedia": { - "methods": [ - "get_photo_media" - ] - }, - "GetPlace": { - "methods": [ - "get_place" - ] - }, - "SearchNearby": { - "methods": [ - "search_nearby" - ] - }, - "SearchText": { - "methods": [ - "search_text" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/gapic_version.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-maps-places/v1/google/maps/places_v1/py.typed b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/py.typed deleted file mode 100644 index ae821546ded2..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-maps-places package uses inline types. diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/__init__.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-maps-places/v1/google/maps/places_v1/services/places/__init__.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/__init__.py deleted file mode 100644 index 3842d6478d3e..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 PlacesClient -from .async_client import PlacesAsyncClient - -__all__ = ( - 'PlacesClient', - 'PlacesAsyncClient', -) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/async_client.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/async_client.py deleted file mode 100644 index 11accc1ee01f..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/async_client.py +++ /dev/null @@ -1,724 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.places_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 - - -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.geo.type.types import viewport -from google.maps.places_v1.types import contextual_content -from google.maps.places_v1.types import ev_charging -from google.maps.places_v1.types import fuel_options -from google.maps.places_v1.types import photo -from google.maps.places_v1.types import place -from google.maps.places_v1.types import places_service -from google.maps.places_v1.types import price_range -from google.maps.places_v1.types import review -from google.maps.places_v1.types import routing_summary -from google.type import latlng_pb2 # type: ignore -from google.type import localized_text_pb2 # type: ignore -from .transports.base import PlacesTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import PlacesGrpcAsyncIOTransport -from .client import PlacesClient - -try: - from google.api_core import client_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 PlacesAsyncClient: - """Service definition for the Places API. Note: every request (except - for Autocomplete requests) requires a field mask set outside of the - request proto (``all/*``, is not assumed). The field mask can be set - via the HTTP header ``X-Goog-FieldMask``. See: - https://developers.google.com/maps/documentation/places/web-service/choose-fields - """ - - _client: PlacesClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = PlacesClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = PlacesClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = PlacesClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = PlacesClient._DEFAULT_UNIVERSE - - photo_path = staticmethod(PlacesClient.photo_path) - parse_photo_path = staticmethod(PlacesClient.parse_photo_path) - photo_media_path = staticmethod(PlacesClient.photo_media_path) - parse_photo_media_path = staticmethod(PlacesClient.parse_photo_media_path) - place_path = staticmethod(PlacesClient.place_path) - parse_place_path = staticmethod(PlacesClient.parse_place_path) - review_path = staticmethod(PlacesClient.review_path) - parse_review_path = staticmethod(PlacesClient.parse_review_path) - common_billing_account_path = staticmethod(PlacesClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(PlacesClient.parse_common_billing_account_path) - common_folder_path = staticmethod(PlacesClient.common_folder_path) - parse_common_folder_path = staticmethod(PlacesClient.parse_common_folder_path) - common_organization_path = staticmethod(PlacesClient.common_organization_path) - parse_common_organization_path = staticmethod(PlacesClient.parse_common_organization_path) - common_project_path = staticmethod(PlacesClient.common_project_path) - parse_common_project_path = staticmethod(PlacesClient.parse_common_project_path) - common_location_path = staticmethod(PlacesClient.common_location_path) - parse_common_location_path = staticmethod(PlacesClient.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: - PlacesAsyncClient: The constructed client. - """ - return PlacesClient.from_service_account_info.__func__(PlacesAsyncClient, 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: - PlacesAsyncClient: The constructed client. - """ - return PlacesClient.from_service_account_file.__func__(PlacesAsyncClient, 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 PlacesClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> PlacesTransport: - """Returns the transport used by the client instance. - - Returns: - PlacesTransport: 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 = PlacesClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, PlacesTransport, Callable[..., PlacesTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the places 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,PlacesTransport,Callable[..., PlacesTransport]]]): - 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 PlacesTransport 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 = PlacesClient( - 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.maps.places_v1.PlacesAsyncClient`.", - extra = { - "serviceName": "google.maps.places.v1.Places", - "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.maps.places.v1.Places", - "credentialsType": None, - } - ) - - async def search_nearby(self, - request: Optional[Union[places_service.SearchNearbyRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> places_service.SearchNearbyResponse: - r"""Search for places near locations. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import places_v1 - - async def sample_search_nearby(): - # Create a client - client = places_v1.PlacesAsyncClient() - - # Initialize request argument(s) - location_restriction = places_v1.LocationRestriction() - location_restriction.circle.radius = 0.648 - - request = places_v1.SearchNearbyRequest( - location_restriction=location_restriction, - ) - - # Make the request - response = await client.search_nearby(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.places_v1.types.SearchNearbyRequest, dict]]): - The request object. Request proto for Search Nearby. - 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.maps.places_v1.types.SearchNearbyResponse: - Response proto for Search Nearby. - """ - # 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, places_service.SearchNearbyRequest): - request = places_service.SearchNearbyRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.search_nearby] - - # 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 search_text(self, - request: Optional[Union[places_service.SearchTextRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> places_service.SearchTextResponse: - r"""Text query based place search. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import places_v1 - - async def sample_search_text(): - # Create a client - client = places_v1.PlacesAsyncClient() - - # Initialize request argument(s) - request = places_v1.SearchTextRequest( - text_query="text_query_value", - ) - - # Make the request - response = await client.search_text(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.places_v1.types.SearchTextRequest, dict]]): - The request object. Request proto for SearchText. - 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.maps.places_v1.types.SearchTextResponse: - Response proto for SearchText. - """ - # 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, places_service.SearchTextRequest): - request = places_service.SearchTextRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.search_text] - - # 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_photo_media(self, - request: Optional[Union[places_service.GetPhotoMediaRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> places_service.PhotoMedia: - r"""Get a photo media with a photo reference string. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import places_v1 - - async def sample_get_photo_media(): - # Create a client - client = places_v1.PlacesAsyncClient() - - # Initialize request argument(s) - request = places_v1.GetPhotoMediaRequest( - name="name_value", - ) - - # Make the request - response = await client.get_photo_media(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.places_v1.types.GetPhotoMediaRequest, dict]]): - The request object. Request for fetching a photo of a - place using a photo resource name. - name (:class:`str`): - Required. The resource name of a photo media in the - format: - ``places/{place_id}/photos/{photo_reference}/media``. - - The resource name of a photo as returned in a Place - object's ``photos.name`` field comes with the format - ``places/{place_id}/photos/{photo_reference}``. You need - to append ``/media`` at the end of the photo resource to - get the photo media resource name. - - 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.maps.places_v1.types.PhotoMedia: - A photo media from Places 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, places_service.GetPhotoMediaRequest): - request = places_service.GetPhotoMediaRequest(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_photo_media] - - # Certain 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_place(self, - request: Optional[Union[places_service.GetPlaceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> place.Place: - r"""Get the details of a place based on its resource name, which is - a string in the ``places/{place_id}`` format. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import places_v1 - - async def sample_get_place(): - # Create a client - client = places_v1.PlacesAsyncClient() - - # Initialize request argument(s) - request = places_v1.GetPlaceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_place(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.places_v1.types.GetPlaceRequest, dict]]): - The request object. Request for fetching a Place based on its resource name, - which is a string in the ``places/{place_id}`` format. - name (:class:`str`): - Required. The resource name of a place, in the - ``places/{place_id}`` format. - - 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.maps.places_v1.types.Place: - All the information representing a - Place. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, places_service.GetPlaceRequest): - request = places_service.GetPlaceRequest(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_place] - - # Certain 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 autocomplete_places(self, - request: Optional[Union[places_service.AutocompletePlacesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> places_service.AutocompletePlacesResponse: - r"""Returns predictions for the given input. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import places_v1 - - async def sample_autocomplete_places(): - # Create a client - client = places_v1.PlacesAsyncClient() - - # Initialize request argument(s) - request = places_v1.AutocompletePlacesRequest( - input="input_value", - ) - - # Make the request - response = await client.autocomplete_places(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.places_v1.types.AutocompletePlacesRequest, dict]]): - The request object. Request proto for AutocompletePlaces. - 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.maps.places_v1.types.AutocompletePlacesResponse: - Response proto for - AutocompletePlaces. - - """ - # 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, places_service.AutocompletePlacesRequest): - request = places_service.AutocompletePlacesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.autocomplete_places] - - # 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) -> "PlacesAsyncClient": - 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__) - - -__all__ = ( - "PlacesAsyncClient", -) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/client.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/client.py deleted file mode 100644 index e5eafbb91b62..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/client.py +++ /dev/null @@ -1,1085 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -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.maps.places_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 - -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.geo.type.types import viewport -from google.maps.places_v1.types import contextual_content -from google.maps.places_v1.types import ev_charging -from google.maps.places_v1.types import fuel_options -from google.maps.places_v1.types import photo -from google.maps.places_v1.types import place -from google.maps.places_v1.types import places_service -from google.maps.places_v1.types import price_range -from google.maps.places_v1.types import review -from google.maps.places_v1.types import routing_summary -from google.type import latlng_pb2 # type: ignore -from google.type import localized_text_pb2 # type: ignore -from .transports.base import PlacesTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import PlacesGrpcTransport -from .transports.grpc_asyncio import PlacesGrpcAsyncIOTransport -from .transports.rest import PlacesRestTransport - - -class PlacesClientMeta(type): - """Metaclass for the Places 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[PlacesTransport]] - _transport_registry["grpc"] = PlacesGrpcTransport - _transport_registry["grpc_asyncio"] = PlacesGrpcAsyncIOTransport - _transport_registry["rest"] = PlacesRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[PlacesTransport]: - """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 PlacesClient(metaclass=PlacesClientMeta): - """Service definition for the Places API. Note: every request (except - for Autocomplete requests) requires a field mask set outside of the - request proto (``all/*``, is not assumed). The field mask can be set - via the HTTP header ``X-Goog-FieldMask``. See: - https://developers.google.com/maps/documentation/places/web-service/choose-fields - """ - - @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 = "places.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "places.{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: - PlacesClient: 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: - PlacesClient: 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) -> PlacesTransport: - """Returns the transport used by the client instance. - - Returns: - PlacesTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def photo_path(place: str,photo: str,) -> str: - """Returns a fully-qualified photo string.""" - return "places/{place}/photos/{photo}".format(place=place, photo=photo, ) - - @staticmethod - def parse_photo_path(path: str) -> Dict[str,str]: - """Parses a photo path into its component segments.""" - m = re.match(r"^places/(?P.+?)/photos/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def photo_media_path(place_id: str,photo_reference: str,) -> str: - """Returns a fully-qualified photo_media string.""" - return "places/{place_id}/photos/{photo_reference}/media".format(place_id=place_id, photo_reference=photo_reference, ) - - @staticmethod - def parse_photo_media_path(path: str) -> Dict[str,str]: - """Parses a photo_media path into its component segments.""" - m = re.match(r"^places/(?P.+?)/photos/(?P.+?)/media$", path) - return m.groupdict() if m else {} - - @staticmethod - def place_path(place_id: str,) -> str: - """Returns a fully-qualified place string.""" - return "places/{place_id}".format(place_id=place_id, ) - - @staticmethod - def parse_place_path(path: str) -> Dict[str,str]: - """Parses a place path into its component segments.""" - m = re.match(r"^places/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def review_path(place: str,review: str,) -> str: - """Returns a fully-qualified review string.""" - return "places/{place}/reviews/{review}".format(place=place, review=review, ) - - @staticmethod - def parse_review_path(path: str) -> Dict[str,str]: - """Parses a review path into its component segments.""" - m = re.match(r"^places/(?P.+?)/reviews/(?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 = PlacesClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = PlacesClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = PlacesClient._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 = PlacesClient._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 - - @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, PlacesTransport, Callable[..., PlacesTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the places 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,PlacesTransport,Callable[..., PlacesTransport]]]): - 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 PlacesTransport 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 = PlacesClient._read_environment_variables() - self._client_cert_source = PlacesClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = PlacesClient._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, PlacesTransport) - if transport_provided: - # transport is a PlacesTransport 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(PlacesTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - PlacesClient._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[PlacesTransport], Callable[..., PlacesTransport]] = ( - PlacesClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., PlacesTransport], 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.maps.places_v1.PlacesClient`.", - extra = { - "serviceName": "google.maps.places.v1.Places", - "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.maps.places.v1.Places", - "credentialsType": None, - } - ) - - def search_nearby(self, - request: Optional[Union[places_service.SearchNearbyRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> places_service.SearchNearbyResponse: - r"""Search for places near locations. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import places_v1 - - def sample_search_nearby(): - # Create a client - client = places_v1.PlacesClient() - - # Initialize request argument(s) - location_restriction = places_v1.LocationRestriction() - location_restriction.circle.radius = 0.648 - - request = places_v1.SearchNearbyRequest( - location_restriction=location_restriction, - ) - - # Make the request - response = client.search_nearby(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.places_v1.types.SearchNearbyRequest, dict]): - The request object. Request proto for Search Nearby. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.maps.places_v1.types.SearchNearbyResponse: - Response proto for Search Nearby. - """ - # 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, places_service.SearchNearbyRequest): - request = places_service.SearchNearbyRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.search_nearby] - - # 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 search_text(self, - request: Optional[Union[places_service.SearchTextRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> places_service.SearchTextResponse: - r"""Text query based place search. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import places_v1 - - def sample_search_text(): - # Create a client - client = places_v1.PlacesClient() - - # Initialize request argument(s) - request = places_v1.SearchTextRequest( - text_query="text_query_value", - ) - - # Make the request - response = client.search_text(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.places_v1.types.SearchTextRequest, dict]): - The request object. Request proto for SearchText. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.maps.places_v1.types.SearchTextResponse: - Response proto for SearchText. - """ - # 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, places_service.SearchTextRequest): - request = places_service.SearchTextRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.search_text] - - # 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_photo_media(self, - request: Optional[Union[places_service.GetPhotoMediaRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> places_service.PhotoMedia: - r"""Get a photo media with a photo reference string. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import places_v1 - - def sample_get_photo_media(): - # Create a client - client = places_v1.PlacesClient() - - # Initialize request argument(s) - request = places_v1.GetPhotoMediaRequest( - name="name_value", - ) - - # Make the request - response = client.get_photo_media(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.places_v1.types.GetPhotoMediaRequest, dict]): - The request object. Request for fetching a photo of a - place using a photo resource name. - name (str): - Required. The resource name of a photo media in the - format: - ``places/{place_id}/photos/{photo_reference}/media``. - - The resource name of a photo as returned in a Place - object's ``photos.name`` field comes with the format - ``places/{place_id}/photos/{photo_reference}``. You need - to append ``/media`` at the end of the photo resource to - get the photo media resource name. - - 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.maps.places_v1.types.PhotoMedia: - A photo media from Places 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, places_service.GetPhotoMediaRequest): - request = places_service.GetPhotoMediaRequest(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_photo_media] - - # Certain 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_place(self, - request: Optional[Union[places_service.GetPlaceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> place.Place: - r"""Get the details of a place based on its resource name, which is - a string in the ``places/{place_id}`` format. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import places_v1 - - def sample_get_place(): - # Create a client - client = places_v1.PlacesClient() - - # Initialize request argument(s) - request = places_v1.GetPlaceRequest( - name="name_value", - ) - - # Make the request - response = client.get_place(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.places_v1.types.GetPlaceRequest, dict]): - The request object. Request for fetching a Place based on its resource name, - which is a string in the ``places/{place_id}`` format. - name (str): - Required. The resource name of a place, in the - ``places/{place_id}`` format. - - 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.maps.places_v1.types.Place: - All the information representing a - Place. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, places_service.GetPlaceRequest): - request = places_service.GetPlaceRequest(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_place] - - # Certain 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 autocomplete_places(self, - request: Optional[Union[places_service.AutocompletePlacesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> places_service.AutocompletePlacesResponse: - r"""Returns predictions for the given input. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import places_v1 - - def sample_autocomplete_places(): - # Create a client - client = places_v1.PlacesClient() - - # Initialize request argument(s) - request = places_v1.AutocompletePlacesRequest( - input="input_value", - ) - - # Make the request - response = client.autocomplete_places(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.places_v1.types.AutocompletePlacesRequest, dict]): - The request object. Request proto for AutocompletePlaces. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.maps.places_v1.types.AutocompletePlacesResponse: - Response proto for - AutocompletePlaces. - - """ - # 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, places_service.AutocompletePlacesRequest): - request = places_service.AutocompletePlacesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.autocomplete_places] - - # 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) -> "PlacesClient": - 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__) - - -__all__ = ( - "PlacesClient", -) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/README.rst b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/README.rst deleted file mode 100644 index 954b9149d54e..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`PlacesTransport` is the ABC for all transports. -- public child `PlacesGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `PlacesGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BasePlacesRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `PlacesRestTransport` 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-maps-places/v1/google/maps/places_v1/services/places/transports/__init__.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/__init__.py deleted file mode 100644 index 6400d3052ce1..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 PlacesTransport -from .grpc import PlacesGrpcTransport -from .grpc_asyncio import PlacesGrpcAsyncIOTransport -from .rest import PlacesRestTransport -from .rest import PlacesRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[PlacesTransport]] -_transport_registry['grpc'] = PlacesGrpcTransport -_transport_registry['grpc_asyncio'] = PlacesGrpcAsyncIOTransport -_transport_registry['rest'] = PlacesRestTransport - -__all__ = ( - 'PlacesTransport', - 'PlacesGrpcTransport', - 'PlacesGrpcAsyncIOTransport', - 'PlacesRestTransport', - 'PlacesRestInterceptor', -) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/base.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/base.py deleted file mode 100644 index 54e226142a89..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/base.py +++ /dev/null @@ -1,210 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.places_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 - -from google.maps.places_v1.types import place -from google.maps.places_v1.types import places_service - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class PlacesTransport(abc.ABC): - """Abstract transport class for Places.""" - - AUTH_SCOPES = ( - ) - - DEFAULT_HOST: str = 'places.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: 'places.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to 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.search_nearby: gapic_v1.method.wrap_method( - self.search_nearby, - default_timeout=None, - client_info=client_info, - ), - self.search_text: gapic_v1.method.wrap_method( - self.search_text, - default_timeout=None, - client_info=client_info, - ), - self.get_photo_media: gapic_v1.method.wrap_method( - self.get_photo_media, - default_timeout=None, - client_info=client_info, - ), - self.get_place: gapic_v1.method.wrap_method( - self.get_place, - default_timeout=None, - client_info=client_info, - ), - self.autocomplete_places: gapic_v1.method.wrap_method( - self.autocomplete_places, - 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 search_nearby(self) -> Callable[ - [places_service.SearchNearbyRequest], - Union[ - places_service.SearchNearbyResponse, - Awaitable[places_service.SearchNearbyResponse] - ]]: - raise NotImplementedError() - - @property - def search_text(self) -> Callable[ - [places_service.SearchTextRequest], - Union[ - places_service.SearchTextResponse, - Awaitable[places_service.SearchTextResponse] - ]]: - raise NotImplementedError() - - @property - def get_photo_media(self) -> Callable[ - [places_service.GetPhotoMediaRequest], - Union[ - places_service.PhotoMedia, - Awaitable[places_service.PhotoMedia] - ]]: - raise NotImplementedError() - - @property - def get_place(self) -> Callable[ - [places_service.GetPlaceRequest], - Union[ - place.Place, - Awaitable[place.Place] - ]]: - raise NotImplementedError() - - @property - def autocomplete_places(self) -> Callable[ - [places_service.AutocompletePlacesRequest], - Union[ - places_service.AutocompletePlacesResponse, - Awaitable[places_service.AutocompletePlacesResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'PlacesTransport', -) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/grpc.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/grpc.py deleted file mode 100644 index 84c3a151b6bf..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/grpc.py +++ /dev/null @@ -1,457 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.places_v1.types import place -from google.maps.places_v1.types import places_service -from .base import PlacesTransport, 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.maps.places.v1.Places", - "rpcName": 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.maps.places.v1.Places", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class PlacesGrpcTransport(PlacesTransport): - """gRPC backend transport for Places. - - Service definition for the Places API. Note: every request (except - for Autocomplete requests) requires a field mask set outside of the - request proto (``all/*``, is not assumed). The field mask can be set - via the HTTP header ``X-Goog-FieldMask``. See: - https://developers.google.com/maps/documentation/places/web-service/choose-fields - - This 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 = 'places.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: 'places.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to 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 = 'places.googleapis.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 search_nearby(self) -> Callable[ - [places_service.SearchNearbyRequest], - places_service.SearchNearbyResponse]: - r"""Return a callable for the search nearby method over gRPC. - - Search for places near locations. - - Returns: - Callable[[~.SearchNearbyRequest], - ~.SearchNearbyResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search_nearby' not in self._stubs: - self._stubs['search_nearby'] = self._logged_channel.unary_unary( - '/google.maps.places.v1.Places/SearchNearby', - request_serializer=places_service.SearchNearbyRequest.serialize, - response_deserializer=places_service.SearchNearbyResponse.deserialize, - ) - return self._stubs['search_nearby'] - - @property - def search_text(self) -> Callable[ - [places_service.SearchTextRequest], - places_service.SearchTextResponse]: - r"""Return a callable for the search text method over gRPC. - - Text query based place search. - - Returns: - Callable[[~.SearchTextRequest], - ~.SearchTextResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search_text' not in self._stubs: - self._stubs['search_text'] = self._logged_channel.unary_unary( - '/google.maps.places.v1.Places/SearchText', - request_serializer=places_service.SearchTextRequest.serialize, - response_deserializer=places_service.SearchTextResponse.deserialize, - ) - return self._stubs['search_text'] - - @property - def get_photo_media(self) -> Callable[ - [places_service.GetPhotoMediaRequest], - places_service.PhotoMedia]: - r"""Return a callable for the get photo media method over gRPC. - - Get a photo media with a photo reference string. - - Returns: - Callable[[~.GetPhotoMediaRequest], - ~.PhotoMedia]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_photo_media' not in self._stubs: - self._stubs['get_photo_media'] = self._logged_channel.unary_unary( - '/google.maps.places.v1.Places/GetPhotoMedia', - request_serializer=places_service.GetPhotoMediaRequest.serialize, - response_deserializer=places_service.PhotoMedia.deserialize, - ) - return self._stubs['get_photo_media'] - - @property - def get_place(self) -> Callable[ - [places_service.GetPlaceRequest], - place.Place]: - r"""Return a callable for the get place method over gRPC. - - Get the details of a place based on its resource name, which is - a string in the ``places/{place_id}`` format. - - Returns: - Callable[[~.GetPlaceRequest], - ~.Place]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_place' not in self._stubs: - self._stubs['get_place'] = self._logged_channel.unary_unary( - '/google.maps.places.v1.Places/GetPlace', - request_serializer=places_service.GetPlaceRequest.serialize, - response_deserializer=place.Place.deserialize, - ) - return self._stubs['get_place'] - - @property - def autocomplete_places(self) -> Callable[ - [places_service.AutocompletePlacesRequest], - places_service.AutocompletePlacesResponse]: - r"""Return a callable for the autocomplete places method over gRPC. - - Returns predictions for the given input. - - Returns: - Callable[[~.AutocompletePlacesRequest], - ~.AutocompletePlacesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'autocomplete_places' not in self._stubs: - self._stubs['autocomplete_places'] = self._logged_channel.unary_unary( - '/google.maps.places.v1.Places/AutocompletePlaces', - request_serializer=places_service.AutocompletePlacesRequest.serialize, - response_deserializer=places_service.AutocompletePlacesResponse.deserialize, - ) - return self._stubs['autocomplete_places'] - - def close(self): - self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'PlacesGrpcTransport', -) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/grpc_asyncio.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/grpc_asyncio.py deleted file mode 100644 index f2be3e2b000e..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/grpc_asyncio.py +++ /dev/null @@ -1,497 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.places_v1.types import place -from google.maps.places_v1.types import places_service -from .base import PlacesTransport, DEFAULT_CLIENT_INFO -from .grpc import PlacesGrpcTransport - -try: - from google.api_core import client_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.maps.places.v1.Places", - "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.maps.places.v1.Places", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class PlacesGrpcAsyncIOTransport(PlacesTransport): - """gRPC AsyncIO backend transport for Places. - - Service definition for the Places API. Note: every request (except - for Autocomplete requests) requires a field mask set outside of the - request proto (``all/*``, is not assumed). The field mask can be set - via the HTTP header ``X-Goog-FieldMask``. See: - https://developers.google.com/maps/documentation/places/web-service/choose-fields - - This 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 = 'places.googleapis.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 = 'places.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: 'places.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to 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 search_nearby(self) -> Callable[ - [places_service.SearchNearbyRequest], - Awaitable[places_service.SearchNearbyResponse]]: - r"""Return a callable for the search nearby method over gRPC. - - Search for places near locations. - - Returns: - Callable[[~.SearchNearbyRequest], - Awaitable[~.SearchNearbyResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search_nearby' not in self._stubs: - self._stubs['search_nearby'] = self._logged_channel.unary_unary( - '/google.maps.places.v1.Places/SearchNearby', - request_serializer=places_service.SearchNearbyRequest.serialize, - response_deserializer=places_service.SearchNearbyResponse.deserialize, - ) - return self._stubs['search_nearby'] - - @property - def search_text(self) -> Callable[ - [places_service.SearchTextRequest], - Awaitable[places_service.SearchTextResponse]]: - r"""Return a callable for the search text method over gRPC. - - Text query based place search. - - Returns: - Callable[[~.SearchTextRequest], - Awaitable[~.SearchTextResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search_text' not in self._stubs: - self._stubs['search_text'] = self._logged_channel.unary_unary( - '/google.maps.places.v1.Places/SearchText', - request_serializer=places_service.SearchTextRequest.serialize, - response_deserializer=places_service.SearchTextResponse.deserialize, - ) - return self._stubs['search_text'] - - @property - def get_photo_media(self) -> Callable[ - [places_service.GetPhotoMediaRequest], - Awaitable[places_service.PhotoMedia]]: - r"""Return a callable for the get photo media method over gRPC. - - Get a photo media with a photo reference string. - - Returns: - Callable[[~.GetPhotoMediaRequest], - Awaitable[~.PhotoMedia]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_photo_media' not in self._stubs: - self._stubs['get_photo_media'] = self._logged_channel.unary_unary( - '/google.maps.places.v1.Places/GetPhotoMedia', - request_serializer=places_service.GetPhotoMediaRequest.serialize, - response_deserializer=places_service.PhotoMedia.deserialize, - ) - return self._stubs['get_photo_media'] - - @property - def get_place(self) -> Callable[ - [places_service.GetPlaceRequest], - Awaitable[place.Place]]: - r"""Return a callable for the get place method over gRPC. - - Get the details of a place based on its resource name, which is - a string in the ``places/{place_id}`` format. - - Returns: - Callable[[~.GetPlaceRequest], - Awaitable[~.Place]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_place' not in self._stubs: - self._stubs['get_place'] = self._logged_channel.unary_unary( - '/google.maps.places.v1.Places/GetPlace', - request_serializer=places_service.GetPlaceRequest.serialize, - response_deserializer=place.Place.deserialize, - ) - return self._stubs['get_place'] - - @property - def autocomplete_places(self) -> Callable[ - [places_service.AutocompletePlacesRequest], - Awaitable[places_service.AutocompletePlacesResponse]]: - r"""Return a callable for the autocomplete places method over gRPC. - - Returns predictions for the given input. - - Returns: - Callable[[~.AutocompletePlacesRequest], - Awaitable[~.AutocompletePlacesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'autocomplete_places' not in self._stubs: - self._stubs['autocomplete_places'] = self._logged_channel.unary_unary( - '/google.maps.places.v1.Places/AutocompletePlaces', - request_serializer=places_service.AutocompletePlacesRequest.serialize, - response_deserializer=places_service.AutocompletePlacesResponse.deserialize, - ) - return self._stubs['autocomplete_places'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.search_nearby: self._wrap_method( - self.search_nearby, - default_timeout=None, - client_info=client_info, - ), - self.search_text: self._wrap_method( - self.search_text, - default_timeout=None, - client_info=client_info, - ), - self.get_photo_media: self._wrap_method( - self.get_photo_media, - default_timeout=None, - client_info=client_info, - ), - self.get_place: self._wrap_method( - self.get_place, - default_timeout=None, - client_info=client_info, - ), - self.autocomplete_places: self._wrap_method( - self.autocomplete_places, - 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__ = ( - 'PlacesGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/rest.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/rest.py deleted file mode 100644 index db320d32a841..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/rest.py +++ /dev/null @@ -1,946 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -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.maps.places_v1.types import place -from google.maps.places_v1.types import places_service - - -from .rest_base import _BasePlacesRestTransport -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}", -) - - -class PlacesRestInterceptor: - """Interceptor for Places. - - 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 PlacesRestTransport. - - .. code-block:: python - class MyCustomPlacesInterceptor(PlacesRestInterceptor): - def pre_autocomplete_places(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_autocomplete_places(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_photo_media(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_photo_media(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_place(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_place(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_search_nearby(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_search_nearby(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_search_text(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_search_text(self, response): - logging.log(f"Received response: {response}") - return response - - transport = PlacesRestTransport(interceptor=MyCustomPlacesInterceptor()) - client = PlacesClient(transport=transport) - - - """ - def pre_autocomplete_places(self, request: places_service.AutocompletePlacesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[places_service.AutocompletePlacesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for autocomplete_places - - Override in a subclass to manipulate the request or metadata - before they are sent to the Places server. - """ - return request, metadata - - def post_autocomplete_places(self, response: places_service.AutocompletePlacesResponse) -> places_service.AutocompletePlacesResponse: - """Post-rpc interceptor for autocomplete_places - - Override in a subclass to manipulate the response - after it is returned by the Places server but before - it is returned to user code. - """ - return response - - def pre_get_photo_media(self, request: places_service.GetPhotoMediaRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[places_service.GetPhotoMediaRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_photo_media - - Override in a subclass to manipulate the request or metadata - before they are sent to the Places server. - """ - return request, metadata - - def post_get_photo_media(self, response: places_service.PhotoMedia) -> places_service.PhotoMedia: - """Post-rpc interceptor for get_photo_media - - Override in a subclass to manipulate the response - after it is returned by the Places server but before - it is returned to user code. - """ - return response - - def pre_get_place(self, request: places_service.GetPlaceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[places_service.GetPlaceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_place - - Override in a subclass to manipulate the request or metadata - before they are sent to the Places server. - """ - return request, metadata - - def post_get_place(self, response: place.Place) -> place.Place: - """Post-rpc interceptor for get_place - - Override in a subclass to manipulate the response - after it is returned by the Places server but before - it is returned to user code. - """ - return response - - def pre_search_nearby(self, request: places_service.SearchNearbyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[places_service.SearchNearbyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for search_nearby - - Override in a subclass to manipulate the request or metadata - before they are sent to the Places server. - """ - return request, metadata - - def post_search_nearby(self, response: places_service.SearchNearbyResponse) -> places_service.SearchNearbyResponse: - """Post-rpc interceptor for search_nearby - - Override in a subclass to manipulate the response - after it is returned by the Places server but before - it is returned to user code. - """ - return response - - def pre_search_text(self, request: places_service.SearchTextRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[places_service.SearchTextRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for search_text - - Override in a subclass to manipulate the request or metadata - before they are sent to the Places server. - """ - return request, metadata - - def post_search_text(self, response: places_service.SearchTextResponse) -> places_service.SearchTextResponse: - """Post-rpc interceptor for search_text - - Override in a subclass to manipulate the response - after it is returned by the Places server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class PlacesRestStub: - _session: AuthorizedSession - _host: str - _interceptor: PlacesRestInterceptor - - -class PlacesRestTransport(_BasePlacesRestTransport): - """REST backend synchronous transport for Places. - - Service definition for the Places API. Note: every request (except - for Autocomplete requests) requires a field mask set outside of the - request proto (``all/*``, is not assumed). The field mask can be set - via the HTTP header ``X-Goog-FieldMask``. See: - https://developers.google.com/maps/documentation/places/web-service/choose-fields - - This 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 = 'places.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[PlacesRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'places.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to 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 PlacesRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _AutocompletePlaces(_BasePlacesRestTransport._BaseAutocompletePlaces, PlacesRestStub): - def __hash__(self): - return hash("PlacesRestTransport.AutocompletePlaces") - - @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: places_service.AutocompletePlacesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> places_service.AutocompletePlacesResponse: - r"""Call the autocomplete places method over HTTP. - - Args: - request (~.places_service.AutocompletePlacesRequest): - The request object. Request proto for AutocompletePlaces. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.places_service.AutocompletePlacesResponse: - Response proto for - AutocompletePlaces. - - """ - - http_options = _BasePlacesRestTransport._BaseAutocompletePlaces._get_http_options() - - request, metadata = self._interceptor.pre_autocomplete_places(request, metadata) - transcoded_request = _BasePlacesRestTransport._BaseAutocompletePlaces._get_transcoded_request(http_options, request) - - body = _BasePlacesRestTransport._BaseAutocompletePlaces._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BasePlacesRestTransport._BaseAutocompletePlaces._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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.maps.places_v1.PlacesClient.AutocompletePlaces", - extra = { - "serviceName": "google.maps.places.v1.Places", - "rpcName": "AutocompletePlaces", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = PlacesRestTransport._AutocompletePlaces._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 = places_service.AutocompletePlacesResponse() - pb_resp = places_service.AutocompletePlacesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_autocomplete_places(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = places_service.AutocompletePlacesResponse.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.maps.places_v1.PlacesClient.autocomplete_places", - extra = { - "serviceName": "google.maps.places.v1.Places", - "rpcName": "AutocompletePlaces", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetPhotoMedia(_BasePlacesRestTransport._BaseGetPhotoMedia, PlacesRestStub): - def __hash__(self): - return hash("PlacesRestTransport.GetPhotoMedia") - - @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: places_service.GetPhotoMediaRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> places_service.PhotoMedia: - r"""Call the get photo media method over HTTP. - - Args: - request (~.places_service.GetPhotoMediaRequest): - The request object. Request for fetching a photo of a - place using a photo resource name. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.places_service.PhotoMedia: - A photo media from Places API. - """ - - http_options = _BasePlacesRestTransport._BaseGetPhotoMedia._get_http_options() - - request, metadata = self._interceptor.pre_get_photo_media(request, metadata) - transcoded_request = _BasePlacesRestTransport._BaseGetPhotoMedia._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BasePlacesRestTransport._BaseGetPhotoMedia._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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.maps.places_v1.PlacesClient.GetPhotoMedia", - extra = { - "serviceName": "google.maps.places.v1.Places", - "rpcName": "GetPhotoMedia", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = PlacesRestTransport._GetPhotoMedia._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 = places_service.PhotoMedia() - pb_resp = places_service.PhotoMedia.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_photo_media(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = places_service.PhotoMedia.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.maps.places_v1.PlacesClient.get_photo_media", - extra = { - "serviceName": "google.maps.places.v1.Places", - "rpcName": "GetPhotoMedia", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetPlace(_BasePlacesRestTransport._BaseGetPlace, PlacesRestStub): - def __hash__(self): - return hash("PlacesRestTransport.GetPlace") - - @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: places_service.GetPlaceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> place.Place: - r"""Call the get place method over HTTP. - - Args: - request (~.places_service.GetPlaceRequest): - The request object. Request for fetching a Place based on its resource name, - which is a string in the ``places/{place_id}`` format. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.place.Place: - All the information representing a - Place. - - """ - - http_options = _BasePlacesRestTransport._BaseGetPlace._get_http_options() - - request, metadata = self._interceptor.pre_get_place(request, metadata) - transcoded_request = _BasePlacesRestTransport._BaseGetPlace._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BasePlacesRestTransport._BaseGetPlace._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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.maps.places_v1.PlacesClient.GetPlace", - extra = { - "serviceName": "google.maps.places.v1.Places", - "rpcName": "GetPlace", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = PlacesRestTransport._GetPlace._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 = place.Place() - pb_resp = place.Place.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_place(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = place.Place.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.maps.places_v1.PlacesClient.get_place", - extra = { - "serviceName": "google.maps.places.v1.Places", - "rpcName": "GetPlace", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _SearchNearby(_BasePlacesRestTransport._BaseSearchNearby, PlacesRestStub): - def __hash__(self): - return hash("PlacesRestTransport.SearchNearby") - - @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: places_service.SearchNearbyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> places_service.SearchNearbyResponse: - r"""Call the search nearby method over HTTP. - - Args: - request (~.places_service.SearchNearbyRequest): - The request object. Request proto for Search Nearby. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.places_service.SearchNearbyResponse: - Response proto for Search Nearby. - """ - - http_options = _BasePlacesRestTransport._BaseSearchNearby._get_http_options() - - request, metadata = self._interceptor.pre_search_nearby(request, metadata) - transcoded_request = _BasePlacesRestTransport._BaseSearchNearby._get_transcoded_request(http_options, request) - - body = _BasePlacesRestTransport._BaseSearchNearby._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BasePlacesRestTransport._BaseSearchNearby._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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.maps.places_v1.PlacesClient.SearchNearby", - extra = { - "serviceName": "google.maps.places.v1.Places", - "rpcName": "SearchNearby", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = PlacesRestTransport._SearchNearby._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 = places_service.SearchNearbyResponse() - pb_resp = places_service.SearchNearbyResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_search_nearby(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = places_service.SearchNearbyResponse.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.maps.places_v1.PlacesClient.search_nearby", - extra = { - "serviceName": "google.maps.places.v1.Places", - "rpcName": "SearchNearby", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _SearchText(_BasePlacesRestTransport._BaseSearchText, PlacesRestStub): - def __hash__(self): - return hash("PlacesRestTransport.SearchText") - - @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: places_service.SearchTextRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> places_service.SearchTextResponse: - r"""Call the search text method over HTTP. - - Args: - request (~.places_service.SearchTextRequest): - The request object. Request proto for SearchText. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.places_service.SearchTextResponse: - Response proto for SearchText. - """ - - http_options = _BasePlacesRestTransport._BaseSearchText._get_http_options() - - request, metadata = self._interceptor.pre_search_text(request, metadata) - transcoded_request = _BasePlacesRestTransport._BaseSearchText._get_transcoded_request(http_options, request) - - body = _BasePlacesRestTransport._BaseSearchText._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BasePlacesRestTransport._BaseSearchText._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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.maps.places_v1.PlacesClient.SearchText", - extra = { - "serviceName": "google.maps.places.v1.Places", - "rpcName": "SearchText", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = PlacesRestTransport._SearchText._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 = places_service.SearchTextResponse() - pb_resp = places_service.SearchTextResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_search_text(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = places_service.SearchTextResponse.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.maps.places_v1.PlacesClient.search_text", - extra = { - "serviceName": "google.maps.places.v1.Places", - "rpcName": "SearchText", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def autocomplete_places(self) -> Callable[ - [places_service.AutocompletePlacesRequest], - places_service.AutocompletePlacesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._AutocompletePlaces(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_photo_media(self) -> Callable[ - [places_service.GetPhotoMediaRequest], - places_service.PhotoMedia]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetPhotoMedia(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_place(self) -> Callable[ - [places_service.GetPlaceRequest], - place.Place]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetPlace(self._session, self._host, self._interceptor) # type: ignore - - @property - def search_nearby(self) -> Callable[ - [places_service.SearchNearbyRequest], - places_service.SearchNearbyResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._SearchNearby(self._session, self._host, self._interceptor) # type: ignore - - @property - def search_text(self) -> Callable[ - [places_service.SearchTextRequest], - places_service.SearchTextResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._SearchText(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'PlacesRestTransport', -) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/rest_base.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/rest_base.py deleted file mode 100644 index b20551b4308c..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/rest_base.py +++ /dev/null @@ -1,307 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 PlacesTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.maps.places_v1.types import place -from google.maps.places_v1.types import places_service - - -class _BasePlacesRestTransport(PlacesTransport): - """Base REST backend transport for Places. - - 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 = 'places.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: 'places.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 _BaseAutocompletePlaces: - 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': '/v1/places:autocomplete', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = places_service.AutocompletePlacesRequest.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(_BasePlacesRestTransport._BaseAutocompletePlaces._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetPhotoMedia: - 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': '/v1/{name=places/*/photos/*/media}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = places_service.GetPhotoMediaRequest.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(_BasePlacesRestTransport._BaseGetPhotoMedia._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetPlace: - 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': '/v1/{name=places/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = places_service.GetPlaceRequest.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(_BasePlacesRestTransport._BaseGetPlace._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseSearchNearby: - 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': '/v1/places:searchNearby', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = places_service.SearchNearbyRequest.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(_BasePlacesRestTransport._BaseSearchNearby._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseSearchText: - 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': '/v1/places:searchText', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = places_service.SearchTextRequest.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(_BasePlacesRestTransport._BaseSearchText._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BasePlacesRestTransport', -) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/__init__.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/__init__.py deleted file mode 100644 index 7795dad518e6..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/__init__.py +++ /dev/null @@ -1,108 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .attribution import ( - AuthorAttribution, -) -from .content_block import ( - ContentBlock, -) -from .contextual_content import ( - ContextualContent, -) -from .ev_charging import ( - EVChargeOptions, - EVConnectorType, -) -from .fuel_options import ( - FuelOptions, -) -from .geometry import ( - Circle, -) -from .photo import ( - Photo, -) -from .place import ( - Place, - PriceLevel, -) -from .places_service import ( - AutocompletePlacesRequest, - AutocompletePlacesResponse, - GetPhotoMediaRequest, - GetPlaceRequest, - PhotoMedia, - RoutingParameters, - SearchNearbyRequest, - SearchNearbyResponse, - SearchTextRequest, - SearchTextResponse, -) -from .polyline import ( - Polyline, -) -from .price_range import ( - PriceRange, -) -from .reference import ( - References, -) -from .review import ( - Review, -) -from .route_modifiers import ( - RouteModifiers, -) -from .routing_preference import ( - RoutingPreference, -) -from .routing_summary import ( - RoutingSummary, -) -from .travel_mode import ( - TravelMode, -) - -__all__ = ( - 'AuthorAttribution', - 'ContentBlock', - 'ContextualContent', - 'EVChargeOptions', - 'EVConnectorType', - 'FuelOptions', - 'Circle', - 'Photo', - 'Place', - 'PriceLevel', - 'AutocompletePlacesRequest', - 'AutocompletePlacesResponse', - 'GetPhotoMediaRequest', - 'GetPlaceRequest', - 'PhotoMedia', - 'RoutingParameters', - 'SearchNearbyRequest', - 'SearchNearbyResponse', - 'SearchTextRequest', - 'SearchTextResponse', - 'Polyline', - 'PriceRange', - 'References', - 'Review', - 'RouteModifiers', - 'RoutingPreference', - 'RoutingSummary', - 'TravelMode', -) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/attribution.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/attribution.py deleted file mode 100644 index a22226438126..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/attribution.py +++ /dev/null @@ -1,65 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.places.v1', - manifest={ - 'AuthorAttribution', - }, -) - - -class AuthorAttribution(proto.Message): - r"""Information about the author of the UGC data. Used in - [Photo][google.maps.places.v1.Photo], and - [Review][google.maps.places.v1.Review]. - - Attributes: - display_name (str): - Name of the author of the - [Photo][google.maps.places.v1.Photo] or - [Review][google.maps.places.v1.Review]. - uri (str): - URI of the author of the - [Photo][google.maps.places.v1.Photo] or - [Review][google.maps.places.v1.Review]. - photo_uri (str): - Profile photo URI of the author of the - [Photo][google.maps.places.v1.Photo] or - [Review][google.maps.places.v1.Review]. - """ - - display_name: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - ) - photo_uri: str = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/content_block.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/content_block.py deleted file mode 100644 index d5f47e4b7a99..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/content_block.py +++ /dev/null @@ -1,68 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.places_v1.types import reference -from google.type import localized_text_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.places.v1', - manifest={ - 'ContentBlock', - }, -) - - -class ContentBlock(proto.Message): - r"""A block of content that can be served individually. - - Attributes: - topic (str): - The topic of the content, for example - "overview" or "restaurant". - content (google.type.localized_text_pb2.LocalizedText): - Content related to the topic. - references (google.maps.places_v1.types.References): - Experimental: See - https://developers.google.com/maps/documentation/places/web-service/experimental/places-generative - for more details. - - References that are related to this block of - content. - """ - - topic: str = proto.Field( - proto.STRING, - number=1, - ) - content: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=2, - message=localized_text_pb2.LocalizedText, - ) - references: reference.References = proto.Field( - proto.MESSAGE, - number=3, - message=reference.References, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/contextual_content.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/contextual_content.py deleted file mode 100644 index d1dbb7caa603..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/contextual_content.py +++ /dev/null @@ -1,218 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.places_v1.types import photo -from google.maps.places_v1.types import review as gmp_review - - -__protobuf__ = proto.module( - package='google.maps.places.v1', - manifest={ - 'ContextualContent', - }, -) - - -class ContextualContent(proto.Message): - r"""Experimental: See - https://developers.google.com/maps/documentation/places/web-service/experimental/places-generative - for more details. - - Content that is contextual to the place query. - - Attributes: - reviews (MutableSequence[google.maps.places_v1.types.Review]): - List of reviews about this place, contexual - to the place query. - photos (MutableSequence[google.maps.places_v1.types.Photo]): - Information (including references) about - photos of this place, contexual to the place - query. - justifications (MutableSequence[google.maps.places_v1.types.ContextualContent.Justification]): - Experimental: See - https://developers.google.com/maps/documentation/places/web-service/experimental/places-generative - for more details. - - Justifications for the place. - """ - - class Justification(proto.Message): - r"""Experimental: See - https://developers.google.com/maps/documentation/places/web-service/experimental/places-generative - for more details. - - Justifications for the place. Justifications answers the - question of why a place could interest an end user. - - 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: - review_justification (google.maps.places_v1.types.ContextualContent.Justification.ReviewJustification): - Experimental: See - https://developers.google.com/maps/documentation/places/web-service/experimental/places-generative - for more details. - - This field is a member of `oneof`_ ``justification``. - business_availability_attributes_justification (google.maps.places_v1.types.ContextualContent.Justification.BusinessAvailabilityAttributesJustification): - Experimental: See - https://developers.google.com/maps/documentation/places/web-service/experimental/places-generative - for more details. - - This field is a member of `oneof`_ ``justification``. - """ - - class ReviewJustification(proto.Message): - r"""Experimental: See - https://developers.google.com/maps/documentation/places/web-service/experimental/places-generative - for more details. - - User review justifications. This highlights a section of the - user review that would interest an end user. For instance, if - the search query is "firewood pizza", the review justification - highlights the text relevant to the search query. - - Attributes: - highlighted_text (google.maps.places_v1.types.ContextualContent.Justification.ReviewJustification.HighlightedText): - - review (google.maps.places_v1.types.Review): - The review that the highlighted text is - generated from. - """ - - class HighlightedText(proto.Message): - r"""The text highlighted by the justification. This is a subset - of the review itself. The exact word to highlight is marked by - the HighlightedTextRange. There could be several words in the - text being highlighted. - - Attributes: - text (str): - - highlighted_text_ranges (MutableSequence[google.maps.places_v1.types.ContextualContent.Justification.ReviewJustification.HighlightedText.HighlightedTextRange]): - The list of the ranges of the highlighted - text. - """ - - class HighlightedTextRange(proto.Message): - r"""The range of highlighted text. - - Attributes: - start_index (int): - - end_index (int): - - """ - - start_index: int = proto.Field( - proto.INT32, - number=1, - ) - end_index: int = proto.Field( - proto.INT32, - number=2, - ) - - text: str = proto.Field( - proto.STRING, - number=1, - ) - highlighted_text_ranges: MutableSequence['ContextualContent.Justification.ReviewJustification.HighlightedText.HighlightedTextRange'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='ContextualContent.Justification.ReviewJustification.HighlightedText.HighlightedTextRange', - ) - - highlighted_text: 'ContextualContent.Justification.ReviewJustification.HighlightedText' = proto.Field( - proto.MESSAGE, - number=1, - message='ContextualContent.Justification.ReviewJustification.HighlightedText', - ) - review: gmp_review.Review = proto.Field( - proto.MESSAGE, - number=2, - message=gmp_review.Review, - ) - - class BusinessAvailabilityAttributesJustification(proto.Message): - r"""Experimental: See - https://developers.google.com/maps/documentation/places/web-service/experimental/places-generative - for more details. - BusinessAvailabilityAttributes justifications. This shows some - attributes a business has that could interest an end user. - - Attributes: - takeout (bool): - If a place provides takeout. - delivery (bool): - If a place provides delivery. - dine_in (bool): - If a place provides dine-in. - """ - - takeout: bool = proto.Field( - proto.BOOL, - number=1, - ) - delivery: bool = proto.Field( - proto.BOOL, - number=2, - ) - dine_in: bool = proto.Field( - proto.BOOL, - number=3, - ) - - review_justification: 'ContextualContent.Justification.ReviewJustification' = proto.Field( - proto.MESSAGE, - number=1, - oneof='justification', - message='ContextualContent.Justification.ReviewJustification', - ) - business_availability_attributes_justification: 'ContextualContent.Justification.BusinessAvailabilityAttributesJustification' = proto.Field( - proto.MESSAGE, - number=2, - oneof='justification', - message='ContextualContent.Justification.BusinessAvailabilityAttributesJustification', - ) - - reviews: MutableSequence[gmp_review.Review] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gmp_review.Review, - ) - photos: MutableSequence[photo.Photo] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=photo.Photo, - ) - justifications: MutableSequence[Justification] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=Justification, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/ev_charging.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/ev_charging.py deleted file mode 100644 index 17763d21f927..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/ev_charging.py +++ /dev/null @@ -1,176 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.places.v1', - manifest={ - 'EVConnectorType', - 'EVChargeOptions', - }, -) - - -class EVConnectorType(proto.Enum): - r"""See - http://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=6872107 for - additional information/context on EV charging connector types. - - Values: - EV_CONNECTOR_TYPE_UNSPECIFIED (0): - Unspecified connector. - EV_CONNECTOR_TYPE_OTHER (1): - Other connector types. - EV_CONNECTOR_TYPE_J1772 (2): - J1772 type 1 connector. - EV_CONNECTOR_TYPE_TYPE_2 (3): - IEC 62196 type 2 connector. Often referred to - as MENNEKES. - EV_CONNECTOR_TYPE_CHADEMO (4): - CHAdeMO type connector. - EV_CONNECTOR_TYPE_CCS_COMBO_1 (5): - Combined Charging System (AC and DC). Based - on SAE. Type-1 J-1772 connector - EV_CONNECTOR_TYPE_CCS_COMBO_2 (6): - Combined Charging System (AC and DC). Based - on Type-2 Mennekes connector - EV_CONNECTOR_TYPE_TESLA (7): - The generic TESLA connector. This is NACS in - the North America but can be non-NACS in other - parts of the world (e.g. CCS Combo 2 (CCS2) or - GB/T). This value is less representative of an - actual connector type, and more represents the - ability to charge a Tesla brand vehicle at a - Tesla owned charging station. - EV_CONNECTOR_TYPE_UNSPECIFIED_GB_T (8): - GB/T type corresponds to the GB/T standard in China. This - type covers all GB_T types. - EV_CONNECTOR_TYPE_UNSPECIFIED_WALL_OUTLET (9): - Unspecified wall outlet. - """ - EV_CONNECTOR_TYPE_UNSPECIFIED = 0 - EV_CONNECTOR_TYPE_OTHER = 1 - EV_CONNECTOR_TYPE_J1772 = 2 - EV_CONNECTOR_TYPE_TYPE_2 = 3 - EV_CONNECTOR_TYPE_CHADEMO = 4 - EV_CONNECTOR_TYPE_CCS_COMBO_1 = 5 - EV_CONNECTOR_TYPE_CCS_COMBO_2 = 6 - EV_CONNECTOR_TYPE_TESLA = 7 - EV_CONNECTOR_TYPE_UNSPECIFIED_GB_T = 8 - EV_CONNECTOR_TYPE_UNSPECIFIED_WALL_OUTLET = 9 - - -class EVChargeOptions(proto.Message): - r"""Information about the EV Charge Station hosted in Place. Terminology - follows - https://afdc.energy.gov/fuels/electricity_infrastructure.html One - port could charge one car at a time. One port has one or more - connectors. One station has one or more ports. - - Attributes: - connector_count (int): - Number of connectors at this station. - However, because some ports can have multiple - connectors but only be able to charge one car at - a time (e.g.) the number of connectors may be - greater than the total number of cars which can - charge simultaneously. - connector_aggregation (MutableSequence[google.maps.places_v1.types.EVChargeOptions.ConnectorAggregation]): - A list of EV charging connector aggregations - that contain connectors of the same type and - same charge rate. - """ - - class ConnectorAggregation(proto.Message): - r"""EV charging information grouped by [type, max_charge_rate_kw]. Shows - EV charge aggregation of connectors that have the same type and max - charge rate in kw. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - type_ (google.maps.places_v1.types.EVConnectorType): - The connector type of this aggregation. - max_charge_rate_kw (float): - The static max charging rate in kw of each - connector in the aggregation. - count (int): - Number of connectors in this aggregation. - available_count (int): - Number of connectors in this aggregation that - are currently available. - - This field is a member of `oneof`_ ``_available_count``. - out_of_service_count (int): - Number of connectors in this aggregation that - are currently out of service. - - This field is a member of `oneof`_ ``_out_of_service_count``. - availability_last_update_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when the connector availability - information in this aggregation was last - updated. - """ - - type_: 'EVConnectorType' = proto.Field( - proto.ENUM, - number=1, - enum='EVConnectorType', - ) - max_charge_rate_kw: float = proto.Field( - proto.DOUBLE, - number=2, - ) - count: int = proto.Field( - proto.INT32, - number=3, - ) - available_count: int = proto.Field( - proto.INT32, - number=4, - optional=True, - ) - out_of_service_count: int = proto.Field( - proto.INT32, - number=5, - optional=True, - ) - availability_last_update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - - connector_count: int = proto.Field( - proto.INT32, - number=1, - ) - connector_aggregation: MutableSequence[ConnectorAggregation] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=ConnectorAggregation, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/fuel_options.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/fuel_options.py deleted file mode 100644 index e1395160614d..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/fuel_options.py +++ /dev/null @@ -1,143 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 timestamp_pb2 # type: ignore -from google.type import money_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.places.v1', - manifest={ - 'FuelOptions', - }, -) - - -class FuelOptions(proto.Message): - r"""The most recent information about fuel options in a gas - station. This information is updated regularly. - - Attributes: - fuel_prices (MutableSequence[google.maps.places_v1.types.FuelOptions.FuelPrice]): - The last known fuel price for each type of - fuel this station has. There is one entry per - fuel type this station has. Order is not - important. - """ - - class FuelPrice(proto.Message): - r"""Fuel price information for a given type. - - Attributes: - type_ (google.maps.places_v1.types.FuelOptions.FuelPrice.FuelType): - The type of fuel. - price (google.type.money_pb2.Money): - The price of the fuel. - update_time (google.protobuf.timestamp_pb2.Timestamp): - The time the fuel price was last updated. - """ - class FuelType(proto.Enum): - r"""Types of fuel. - - Values: - FUEL_TYPE_UNSPECIFIED (0): - Unspecified fuel type. - DIESEL (1): - Diesel fuel. - REGULAR_UNLEADED (2): - Regular unleaded. - MIDGRADE (3): - Midgrade. - PREMIUM (4): - Premium. - SP91 (5): - SP 91. - SP91_E10 (6): - SP 91 E10. - SP92 (7): - SP 92. - SP95 (8): - SP 95. - SP95_E10 (9): - SP95 E10. - SP98 (10): - SP 98. - SP99 (11): - SP 99. - SP100 (12): - SP 100. - LPG (13): - LPG. - E80 (14): - E 80. - E85 (15): - E 85. - METHANE (16): - Methane. - BIO_DIESEL (17): - Bio-diesel. - TRUCK_DIESEL (18): - Truck diesel. - """ - FUEL_TYPE_UNSPECIFIED = 0 - DIESEL = 1 - REGULAR_UNLEADED = 2 - MIDGRADE = 3 - PREMIUM = 4 - SP91 = 5 - SP91_E10 = 6 - SP92 = 7 - SP95 = 8 - SP95_E10 = 9 - SP98 = 10 - SP99 = 11 - SP100 = 12 - LPG = 13 - E80 = 14 - E85 = 15 - METHANE = 16 - BIO_DIESEL = 17 - TRUCK_DIESEL = 18 - - type_: 'FuelOptions.FuelPrice.FuelType' = proto.Field( - proto.ENUM, - number=1, - enum='FuelOptions.FuelPrice.FuelType', - ) - price: money_pb2.Money = proto.Field( - proto.MESSAGE, - number=2, - message=money_pb2.Money, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - fuel_prices: MutableSequence[FuelPrice] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=FuelPrice, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/geometry.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/geometry.py deleted file mode 100644 index b3d1cf8c1eb3..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/geometry.py +++ /dev/null @@ -1,58 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 latlng_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.places.v1', - manifest={ - 'Circle', - }, -) - - -class Circle(proto.Message): - r"""Circle with a LatLng as center and radius. - - Attributes: - center (google.type.latlng_pb2.LatLng): - Required. Center latitude and longitude. - - The range of latitude must be within [-90.0, 90.0]. The - range of the longitude must be within [-180.0, 180.0]. - radius (float): - Required. Radius measured in meters. The radius must be - within [0.0, 50000.0]. - """ - - center: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=1, - message=latlng_pb2.LatLng, - ) - radius: float = proto.Field( - proto.DOUBLE, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/photo.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/photo.py deleted file mode 100644 index 45bc33ecb53e..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/photo.py +++ /dev/null @@ -1,69 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.places_v1.types import attribution - - -__protobuf__ = proto.module( - package='google.maps.places.v1', - manifest={ - 'Photo', - }, -) - - -class Photo(proto.Message): - r"""Information about a photo of a place. - - Attributes: - name (str): - Identifier. A reference representing this place photo which - may be used to look up this place photo again (also called - the API "resource" name: - ``places/{place_id}/photos/{photo}``). - width_px (int): - The maximum available width, in pixels. - height_px (int): - The maximum available height, in pixels. - author_attributions (MutableSequence[google.maps.places_v1.types.AuthorAttribution]): - This photo's authors. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - width_px: int = proto.Field( - proto.INT32, - number=2, - ) - height_px: int = proto.Field( - proto.INT32, - number=3, - ) - author_attributions: MutableSequence[attribution.AuthorAttribution] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=attribution.AuthorAttribution, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/place.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/place.py deleted file mode 100644 index 34e44adedb46..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/place.py +++ /dev/null @@ -1,1286 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.geo.type.types import viewport as ggt_viewport -from google.maps.places_v1.types import content_block -from google.maps.places_v1.types import ev_charging -from google.maps.places_v1.types import fuel_options as gmp_fuel_options -from google.maps.places_v1.types import photo -from google.maps.places_v1.types import price_range as gmp_price_range -from google.maps.places_v1.types import reference -from google.maps.places_v1.types import review -from google.protobuf import timestamp_pb2 # type: ignore -from google.type import date_pb2 # type: ignore -from google.type import latlng_pb2 # type: ignore -from google.type import localized_text_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.places.v1', - manifest={ - 'PriceLevel', - 'Place', - }, -) - - -class PriceLevel(proto.Enum): - r"""Price level of the place. - - Values: - PRICE_LEVEL_UNSPECIFIED (0): - Place price level is unspecified or unknown. - PRICE_LEVEL_FREE (1): - Place provides free services. - PRICE_LEVEL_INEXPENSIVE (2): - Place provides inexpensive services. - PRICE_LEVEL_MODERATE (3): - Place provides moderately priced services. - PRICE_LEVEL_EXPENSIVE (4): - Place provides expensive services. - PRICE_LEVEL_VERY_EXPENSIVE (5): - Place provides very expensive services. - """ - PRICE_LEVEL_UNSPECIFIED = 0 - PRICE_LEVEL_FREE = 1 - PRICE_LEVEL_INEXPENSIVE = 2 - PRICE_LEVEL_MODERATE = 3 - PRICE_LEVEL_EXPENSIVE = 4 - PRICE_LEVEL_VERY_EXPENSIVE = 5 - - -class Place(proto.Message): - r"""All the information representing a Place. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - This Place's resource name, in ``places/{place_id}`` format. - Can be used to look up the Place. - id (str): - The unique identifier of a place. - display_name (google.type.localized_text_pb2.LocalizedText): - The localized name of the place, suitable as - a short human-readable description. For example, - "Google Sydney", "Starbucks", "Pyrmont", etc. - types (MutableSequence[str]): - A set of type tags for this result. For - example, "political" and "locality". For the - complete list of possible values, see Table A - and Table B at - https://developers.google.com/maps/documentation/places/web-service/place-types - primary_type (str): - The primary type of the given result. This - type must one of the Places API supported types. - For example, "restaurant", "cafe", "airport", - etc. A place can only have a single primary - type. For the complete list of possible values, - see Table A and Table B at - https://developers.google.com/maps/documentation/places/web-service/place-types - primary_type_display_name (google.type.localized_text_pb2.LocalizedText): - The display name of the primary type, - localized to the request language if applicable. - For the complete list of possible values, see - Table A and Table B at - https://developers.google.com/maps/documentation/places/web-service/place-types - national_phone_number (str): - A human-readable phone number for the place, - in national format. - international_phone_number (str): - A human-readable phone number for the place, - in international format. - formatted_address (str): - A full, human-readable address for this - place. - short_formatted_address (str): - A short, human-readable address for this - place. - address_components (MutableSequence[google.maps.places_v1.types.Place.AddressComponent]): - Repeated components for each locality level. Note the - following facts about the address_components[] array: - - - The array of address components may contain more - components than the formatted_address. - - The array does not necessarily include all the political - entities that contain an address, apart from those - included in the formatted_address. To retrieve all the - political entities that contain a specific address, you - should use reverse geocoding, passing the - latitude/longitude of the address as a parameter to the - request. - - The format of the response is not guaranteed to remain - the same between requests. In particular, the number of - address_components varies based on the address requested - and can change over time for the same address. A - component can change position in the array. The type of - the component can change. A particular component may be - missing in a later response. - plus_code (google.maps.places_v1.types.Place.PlusCode): - Plus code of the place location lat/long. - location (google.type.latlng_pb2.LatLng): - The position of this place. - viewport (google.geo.type.types.Viewport): - A viewport suitable for displaying the place - on an average-sized map. This viewport should - not be used as the physical boundary or the - service area of the business. - rating (float): - A rating between 1.0 and 5.0, based on user - reviews of this place. - google_maps_uri (str): - A URL providing more information about this - place. - website_uri (str): - The authoritative website for this place, - e.g. a business' homepage. Note that for places - that are part of a chain (e.g. an IKEA store), - this will usually be the website for the - individual store, not the overall chain. - reviews (MutableSequence[google.maps.places_v1.types.Review]): - List of reviews about this place, sorted by - relevance. A maximum of 5 reviews can be - returned. - regular_opening_hours (google.maps.places_v1.types.Place.OpeningHours): - The regular hours of operation. - utc_offset_minutes (int): - Number of minutes this place's timezone is - currently offset from UTC. This is expressed in - minutes to support timezones that are offset by - fractions of an hour, e.g. X hours and 15 - minutes. - - This field is a member of `oneof`_ ``_utc_offset_minutes``. - photos (MutableSequence[google.maps.places_v1.types.Photo]): - Information (including references) about - photos of this place. A maximum of 10 photos can - be returned. - adr_format_address (str): - The place's address in adr microformat: - http://microformats.org/wiki/adr. - business_status (google.maps.places_v1.types.Place.BusinessStatus): - - price_level (google.maps.places_v1.types.PriceLevel): - Price level of the place. - attributions (MutableSequence[google.maps.places_v1.types.Place.Attribution]): - A set of data provider that must be shown - with this result. - user_rating_count (int): - The total number of reviews (with or without - text) for this place. - - This field is a member of `oneof`_ ``_user_rating_count``. - icon_mask_base_uri (str): - A truncated URL to an icon mask. User can - access different icon type by appending type - suffix to the end (eg, ".svg" or ".png"). - icon_background_color (str): - Background color for icon_mask in hex format, e.g. #909CE1. - takeout (bool): - Specifies if the business supports takeout. - - This field is a member of `oneof`_ ``_takeout``. - delivery (bool): - Specifies if the business supports delivery. - - This field is a member of `oneof`_ ``_delivery``. - dine_in (bool): - Specifies if the business supports indoor or - outdoor seating options. - - This field is a member of `oneof`_ ``_dine_in``. - curbside_pickup (bool): - Specifies if the business supports curbside - pickup. - - This field is a member of `oneof`_ ``_curbside_pickup``. - reservable (bool): - Specifies if the place supports reservations. - - This field is a member of `oneof`_ ``_reservable``. - serves_breakfast (bool): - Specifies if the place serves breakfast. - - This field is a member of `oneof`_ ``_serves_breakfast``. - serves_lunch (bool): - Specifies if the place serves lunch. - - This field is a member of `oneof`_ ``_serves_lunch``. - serves_dinner (bool): - Specifies if the place serves dinner. - - This field is a member of `oneof`_ ``_serves_dinner``. - serves_beer (bool): - Specifies if the place serves beer. - - This field is a member of `oneof`_ ``_serves_beer``. - serves_wine (bool): - Specifies if the place serves wine. - - This field is a member of `oneof`_ ``_serves_wine``. - serves_brunch (bool): - Specifies if the place serves brunch. - - This field is a member of `oneof`_ ``_serves_brunch``. - serves_vegetarian_food (bool): - Specifies if the place serves vegetarian - food. - - This field is a member of `oneof`_ ``_serves_vegetarian_food``. - current_opening_hours (google.maps.places_v1.types.Place.OpeningHours): - The hours of operation for the next seven days (including - today). The time period starts at midnight on the date of - the request and ends at 11:59 pm six days later. This field - includes the special_days subfield of all hours, set for - dates that have exceptional hours. - current_secondary_opening_hours (MutableSequence[google.maps.places_v1.types.Place.OpeningHours]): - Contains an array of entries for the next seven days - including information about secondary hours of a business. - Secondary hours are different from a business's main hours. - For example, a restaurant can specify drive through hours or - delivery hours as its secondary hours. This field populates - the type subfield, which draws from a predefined list of - opening hours types (such as DRIVE_THROUGH, PICKUP, or - TAKEOUT) based on the types of the place. This field - includes the special_days subfield of all hours, set for - dates that have exceptional hours. - regular_secondary_opening_hours (MutableSequence[google.maps.places_v1.types.Place.OpeningHours]): - Contains an array of entries for information about regular - secondary hours of a business. Secondary hours are different - from a business's main hours. For example, a restaurant can - specify drive through hours or delivery hours as its - secondary hours. This field populates the type subfield, - which draws from a predefined list of opening hours types - (such as DRIVE_THROUGH, PICKUP, or TAKEOUT) based on the - types of the place. - editorial_summary (google.type.localized_text_pb2.LocalizedText): - Contains a summary of the place. A summary is - comprised of a textual overview, and also - includes the language code for these if - applicable. Summary text must be presented as-is - and can not be modified or altered. - outdoor_seating (bool): - Place provides outdoor seating. - - This field is a member of `oneof`_ ``_outdoor_seating``. - live_music (bool): - Place provides live music. - - This field is a member of `oneof`_ ``_live_music``. - menu_for_children (bool): - Place has a children's menu. - - This field is a member of `oneof`_ ``_menu_for_children``. - serves_cocktails (bool): - Place serves cocktails. - - This field is a member of `oneof`_ ``_serves_cocktails``. - serves_dessert (bool): - Place serves dessert. - - This field is a member of `oneof`_ ``_serves_dessert``. - serves_coffee (bool): - Place serves coffee. - - This field is a member of `oneof`_ ``_serves_coffee``. - good_for_children (bool): - Place is good for children. - - This field is a member of `oneof`_ ``_good_for_children``. - allows_dogs (bool): - Place allows dogs. - - This field is a member of `oneof`_ ``_allows_dogs``. - restroom (bool): - Place has restroom. - - This field is a member of `oneof`_ ``_restroom``. - good_for_groups (bool): - Place accommodates groups. - - This field is a member of `oneof`_ ``_good_for_groups``. - good_for_watching_sports (bool): - Place is suitable for watching sports. - - This field is a member of `oneof`_ ``_good_for_watching_sports``. - payment_options (google.maps.places_v1.types.Place.PaymentOptions): - Payment options the place accepts. If a - payment option data is not available, the - payment option field will be unset. - parking_options (google.maps.places_v1.types.Place.ParkingOptions): - Options of parking provided by the place. - sub_destinations (MutableSequence[google.maps.places_v1.types.Place.SubDestination]): - A list of sub destinations related to the - place. - accessibility_options (google.maps.places_v1.types.Place.AccessibilityOptions): - Information about the accessibility options a - place offers. - - This field is a member of `oneof`_ ``_accessibility_options``. - fuel_options (google.maps.places_v1.types.FuelOptions): - The most recent information about fuel - options in a gas station. This information is - updated regularly. - ev_charge_options (google.maps.places_v1.types.EVChargeOptions): - Information of ev charging options. - generative_summary (google.maps.places_v1.types.Place.GenerativeSummary): - Experimental: See - https://developers.google.com/maps/documentation/places/web-service/experimental/places-generative - for more details. - - AI-generated summary of the place. - area_summary (google.maps.places_v1.types.Place.AreaSummary): - Experimental: See - https://developers.google.com/maps/documentation/places/web-service/experimental/places-generative - for more details. - - AI-generated summary of the area that the place - is in. - containing_places (MutableSequence[google.maps.places_v1.types.Place.ContainingPlace]): - List of places in which the current place is - located. - pure_service_area_business (bool): - Indicates whether the place is a pure service - area business. Pure service area business is a - business that visits or delivers to customers - directly but does not serve customers at their - business address. For example, businesses like - cleaning services or plumbers. Those businesses - may not have a physical address or location on - Google Maps. - - This field is a member of `oneof`_ ``_pure_service_area_business``. - price_range (google.maps.places_v1.types.PriceRange): - The price range associated with a Place. - """ - class BusinessStatus(proto.Enum): - r"""Business status for the place. - - Values: - BUSINESS_STATUS_UNSPECIFIED (0): - Default value. This value is unused. - OPERATIONAL (1): - The establishment is operational, not - necessarily open now. - CLOSED_TEMPORARILY (2): - The establishment is temporarily closed. - CLOSED_PERMANENTLY (3): - The establishment is permanently closed. - """ - BUSINESS_STATUS_UNSPECIFIED = 0 - OPERATIONAL = 1 - CLOSED_TEMPORARILY = 2 - CLOSED_PERMANENTLY = 3 - - class AddressComponent(proto.Message): - r"""The structured components that form the formatted address, if - this information is available. - - Attributes: - long_text (str): - The full text description or name of the address component. - For example, an address component for the country Australia - may have a long_name of "Australia". - short_text (str): - An abbreviated textual name for the address component, if - available. For example, an address component for the country - of Australia may have a short_name of "AU". - types (MutableSequence[str]): - An array indicating the type(s) of the - address component. - language_code (str): - The language used to format this components, - in CLDR notation. - """ - - long_text: str = proto.Field( - proto.STRING, - number=1, - ) - short_text: str = proto.Field( - proto.STRING, - number=2, - ) - types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - language_code: str = proto.Field( - proto.STRING, - number=4, - ) - - class PlusCode(proto.Message): - r"""Plus code (http://plus.codes) is a location reference with - two formats: global code defining a 14mx14m (1/8000th of a - degree) or smaller rectangle, and compound code, replacing the - prefix with a reference location. - - Attributes: - global_code (str): - Place's global (full) code, such as - "9FWM33GV+HQ", representing an 1/8000 by 1/8000 - degree area (~14 by 14 meters). - compound_code (str): - Place's compound code, such as "33GV+HQ, - Ramberg, Norway", containing the suffix of the - global code and replacing the prefix with a - formatted name of a reference entity. - """ - - global_code: str = proto.Field( - proto.STRING, - number=1, - ) - compound_code: str = proto.Field( - proto.STRING, - number=2, - ) - - class OpeningHours(proto.Message): - r"""Information about business hour of the place. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - open_now (bool): - Whether the opening hours period is currently - active. For regular opening hours and current - opening hours, this field means whether the - place is open. For secondary opening hours and - current secondary opening hours, this field - means whether the secondary hours of this place - is active. - - This field is a member of `oneof`_ ``_open_now``. - periods (MutableSequence[google.maps.places_v1.types.Place.OpeningHours.Period]): - The periods that this place is open during - the week. The periods are in chronological - order, starting with Sunday in the place-local - timezone. An empty (but not absent) value - indicates a place that is never open, e.g. - because it is closed temporarily for - renovations. - weekday_descriptions (MutableSequence[str]): - Localized strings describing the opening - hours of this place, one string for each day of - the week. Will be empty if the hours are - unknown or could not be converted to localized - text. Example: "Sun: 18:00–06:00". - secondary_hours_type (google.maps.places_v1.types.Place.OpeningHours.SecondaryHoursType): - A type string used to identify the type of - secondary hours. - special_days (MutableSequence[google.maps.places_v1.types.Place.OpeningHours.SpecialDay]): - Structured information for special days that fall within the - period that the returned opening hours cover. Special days - are days that could impact the business hours of a place, - e.g. Christmas day. Set for current_opening_hours and - current_secondary_opening_hours if there are exceptional - hours. - next_open_time (google.protobuf.timestamp_pb2.Timestamp): - The next time the current opening hours - period starts up to 7 days in the future. This - field is only populated if the opening hours - period is not active at the time of serving the - request. - next_close_time (google.protobuf.timestamp_pb2.Timestamp): - The next time the current opening hours - period ends up to 7 days in the future. This - field is only populated if the opening hours - period is active at the time of serving the - request. - """ - class SecondaryHoursType(proto.Enum): - r"""A type used to identify the type of secondary hours. - - Values: - SECONDARY_HOURS_TYPE_UNSPECIFIED (0): - Default value when secondary hour type is not - specified. - DRIVE_THROUGH (1): - The drive-through hour for banks, - restaurants, or pharmacies. - HAPPY_HOUR (2): - The happy hour. - DELIVERY (3): - The delivery hour. - TAKEOUT (4): - The takeout hour. - KITCHEN (5): - The kitchen hour. - BREAKFAST (6): - The breakfast hour. - LUNCH (7): - The lunch hour. - DINNER (8): - The dinner hour. - BRUNCH (9): - The brunch hour. - PICKUP (10): - The pickup hour. - ACCESS (11): - The access hours for storage places. - SENIOR_HOURS (12): - The special hours for seniors. - ONLINE_SERVICE_HOURS (13): - The online service hours. - """ - SECONDARY_HOURS_TYPE_UNSPECIFIED = 0 - DRIVE_THROUGH = 1 - HAPPY_HOUR = 2 - DELIVERY = 3 - TAKEOUT = 4 - KITCHEN = 5 - BREAKFAST = 6 - LUNCH = 7 - DINNER = 8 - BRUNCH = 9 - PICKUP = 10 - ACCESS = 11 - SENIOR_HOURS = 12 - ONLINE_SERVICE_HOURS = 13 - - class Period(proto.Message): - r"""A period the place remains in open_now status. - - Attributes: - open_ (google.maps.places_v1.types.Place.OpeningHours.Period.Point): - The time that the place starts to be open. - close (google.maps.places_v1.types.Place.OpeningHours.Period.Point): - The time that the place starts to be closed. - """ - - class Point(proto.Message): - r"""Status changing points. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - day (int): - A day of the week, as an integer in the range - 0-6. 0 is Sunday, 1 is Monday, etc. - - This field is a member of `oneof`_ ``_day``. - hour (int): - The hour in 2 digits. Ranges from 00 to 23. - - This field is a member of `oneof`_ ``_hour``. - minute (int): - The minute in 2 digits. Ranges from 00 to 59. - - This field is a member of `oneof`_ ``_minute``. - date (google.type.date_pb2.Date): - Date in the local timezone for the place. - truncated (bool): - Whether or not this endpoint was truncated. Truncation - occurs when the real hours are outside the times we are - willing to return hours between, so we truncate the hours - back to these boundaries. This ensures that at most 24 \* 7 - hours from midnight of the day of the request are returned. - """ - - day: int = proto.Field( - proto.INT32, - number=1, - optional=True, - ) - hour: int = proto.Field( - proto.INT32, - number=2, - optional=True, - ) - minute: int = proto.Field( - proto.INT32, - number=3, - optional=True, - ) - date: date_pb2.Date = proto.Field( - proto.MESSAGE, - number=6, - message=date_pb2.Date, - ) - truncated: bool = proto.Field( - proto.BOOL, - number=5, - ) - - open_: 'Place.OpeningHours.Period.Point' = proto.Field( - proto.MESSAGE, - number=1, - message='Place.OpeningHours.Period.Point', - ) - close: 'Place.OpeningHours.Period.Point' = proto.Field( - proto.MESSAGE, - number=2, - message='Place.OpeningHours.Period.Point', - ) - - class SpecialDay(proto.Message): - r"""Structured information for special days that fall within the - period that the returned opening hours cover. Special days are - days that could impact the business hours of a place, e.g. - Christmas day. - - Attributes: - date (google.type.date_pb2.Date): - The date of this special day. - """ - - date: date_pb2.Date = proto.Field( - proto.MESSAGE, - number=1, - message=date_pb2.Date, - ) - - open_now: bool = proto.Field( - proto.BOOL, - number=1, - optional=True, - ) - periods: MutableSequence['Place.OpeningHours.Period'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Place.OpeningHours.Period', - ) - weekday_descriptions: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - secondary_hours_type: 'Place.OpeningHours.SecondaryHoursType' = proto.Field( - proto.ENUM, - number=4, - enum='Place.OpeningHours.SecondaryHoursType', - ) - special_days: MutableSequence['Place.OpeningHours.SpecialDay'] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message='Place.OpeningHours.SpecialDay', - ) - next_open_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - next_close_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - - class Attribution(proto.Message): - r"""Information about data providers of this place. - - Attributes: - provider (str): - Name of the Place's data provider. - provider_uri (str): - URI to the Place's data provider. - """ - - provider: str = proto.Field( - proto.STRING, - number=1, - ) - provider_uri: str = proto.Field( - proto.STRING, - number=2, - ) - - class PaymentOptions(proto.Message): - r"""Payment options the place accepts. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - accepts_credit_cards (bool): - Place accepts credit cards as payment. - - This field is a member of `oneof`_ ``_accepts_credit_cards``. - accepts_debit_cards (bool): - Place accepts debit cards as payment. - - This field is a member of `oneof`_ ``_accepts_debit_cards``. - accepts_cash_only (bool): - Place accepts cash only as payment. Places - with this attribute may still accept other - payment methods. - - This field is a member of `oneof`_ ``_accepts_cash_only``. - accepts_nfc (bool): - Place accepts NFC payments. - - This field is a member of `oneof`_ ``_accepts_nfc``. - """ - - accepts_credit_cards: bool = proto.Field( - proto.BOOL, - number=1, - optional=True, - ) - accepts_debit_cards: bool = proto.Field( - proto.BOOL, - number=2, - optional=True, - ) - accepts_cash_only: bool = proto.Field( - proto.BOOL, - number=3, - optional=True, - ) - accepts_nfc: bool = proto.Field( - proto.BOOL, - number=4, - optional=True, - ) - - class ParkingOptions(proto.Message): - r"""Information about parking options for the place. A parking - lot could support more than one option at the same time. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - free_parking_lot (bool): - Place offers free parking lots. - - This field is a member of `oneof`_ ``_free_parking_lot``. - paid_parking_lot (bool): - Place offers paid parking lots. - - This field is a member of `oneof`_ ``_paid_parking_lot``. - free_street_parking (bool): - Place offers free street parking. - - This field is a member of `oneof`_ ``_free_street_parking``. - paid_street_parking (bool): - Place offers paid street parking. - - This field is a member of `oneof`_ ``_paid_street_parking``. - valet_parking (bool): - Place offers valet parking. - - This field is a member of `oneof`_ ``_valet_parking``. - free_garage_parking (bool): - Place offers free garage parking. - - This field is a member of `oneof`_ ``_free_garage_parking``. - paid_garage_parking (bool): - Place offers paid garage parking. - - This field is a member of `oneof`_ ``_paid_garage_parking``. - """ - - free_parking_lot: bool = proto.Field( - proto.BOOL, - number=1, - optional=True, - ) - paid_parking_lot: bool = proto.Field( - proto.BOOL, - number=2, - optional=True, - ) - free_street_parking: bool = proto.Field( - proto.BOOL, - number=3, - optional=True, - ) - paid_street_parking: bool = proto.Field( - proto.BOOL, - number=4, - optional=True, - ) - valet_parking: bool = proto.Field( - proto.BOOL, - number=5, - optional=True, - ) - free_garage_parking: bool = proto.Field( - proto.BOOL, - number=6, - optional=True, - ) - paid_garage_parking: bool = proto.Field( - proto.BOOL, - number=7, - optional=True, - ) - - class SubDestination(proto.Message): - r"""Place resource name and id of sub destinations that relate to - the place. For example, different terminals are different - destinations of an airport. - - Attributes: - name (str): - The resource name of the sub destination. - id (str): - The place id of the sub destination. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - id: str = proto.Field( - proto.STRING, - number=2, - ) - - class AccessibilityOptions(proto.Message): - r"""Information about the accessibility options a place offers. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - wheelchair_accessible_parking (bool): - Place offers wheelchair accessible parking. - - This field is a member of `oneof`_ ``_wheelchair_accessible_parking``. - wheelchair_accessible_entrance (bool): - Places has wheelchair accessible entrance. - - This field is a member of `oneof`_ ``_wheelchair_accessible_entrance``. - wheelchair_accessible_restroom (bool): - Place has wheelchair accessible restroom. - - This field is a member of `oneof`_ ``_wheelchair_accessible_restroom``. - wheelchair_accessible_seating (bool): - Place has wheelchair accessible seating. - - This field is a member of `oneof`_ ``_wheelchair_accessible_seating``. - """ - - wheelchair_accessible_parking: bool = proto.Field( - proto.BOOL, - number=1, - optional=True, - ) - wheelchair_accessible_entrance: bool = proto.Field( - proto.BOOL, - number=2, - optional=True, - ) - wheelchair_accessible_restroom: bool = proto.Field( - proto.BOOL, - number=3, - optional=True, - ) - wheelchair_accessible_seating: bool = proto.Field( - proto.BOOL, - number=4, - optional=True, - ) - - class GenerativeSummary(proto.Message): - r"""Experimental: See - https://developers.google.com/maps/documentation/places/web-service/experimental/places-generative - for more details. - - AI-generated summary of the place. - - Attributes: - overview (google.type.localized_text_pb2.LocalizedText): - The overview of the place. - description (google.type.localized_text_pb2.LocalizedText): - The detailed description of the place. - references (google.maps.places_v1.types.References): - References that are used to generate the - summary description. - """ - - overview: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=1, - message=localized_text_pb2.LocalizedText, - ) - description: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=2, - message=localized_text_pb2.LocalizedText, - ) - references: reference.References = proto.Field( - proto.MESSAGE, - number=3, - message=reference.References, - ) - - class AreaSummary(proto.Message): - r"""Experimental: See - https://developers.google.com/maps/documentation/places/web-service/experimental/places-generative - for more details. - - AI-generated summary of the area that the place is in. - - Attributes: - content_blocks (MutableSequence[google.maps.places_v1.types.ContentBlock]): - Content blocks that compose the area summary. - Each block has a separate topic about the area. - """ - - content_blocks: MutableSequence[content_block.ContentBlock] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=content_block.ContentBlock, - ) - - class ContainingPlace(proto.Message): - r"""Info about the place in which this place is located. - - Attributes: - name (str): - The resource name of the place in which this - place is located. - id (str): - The place id of the place in which this place - is located. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - id: str = proto.Field( - proto.STRING, - number=2, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - id: str = proto.Field( - proto.STRING, - number=2, - ) - display_name: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=31, - message=localized_text_pb2.LocalizedText, - ) - types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - primary_type: str = proto.Field( - proto.STRING, - number=50, - ) - primary_type_display_name: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=32, - message=localized_text_pb2.LocalizedText, - ) - national_phone_number: str = proto.Field( - proto.STRING, - number=7, - ) - international_phone_number: str = proto.Field( - proto.STRING, - number=8, - ) - formatted_address: str = proto.Field( - proto.STRING, - number=9, - ) - short_formatted_address: str = proto.Field( - proto.STRING, - number=51, - ) - address_components: MutableSequence[AddressComponent] = proto.RepeatedField( - proto.MESSAGE, - number=10, - message=AddressComponent, - ) - plus_code: PlusCode = proto.Field( - proto.MESSAGE, - number=11, - message=PlusCode, - ) - location: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=12, - message=latlng_pb2.LatLng, - ) - viewport: ggt_viewport.Viewport = proto.Field( - proto.MESSAGE, - number=13, - message=ggt_viewport.Viewport, - ) - rating: float = proto.Field( - proto.DOUBLE, - number=14, - ) - google_maps_uri: str = proto.Field( - proto.STRING, - number=15, - ) - website_uri: str = proto.Field( - proto.STRING, - number=16, - ) - reviews: MutableSequence[review.Review] = proto.RepeatedField( - proto.MESSAGE, - number=53, - message=review.Review, - ) - regular_opening_hours: OpeningHours = proto.Field( - proto.MESSAGE, - number=21, - message=OpeningHours, - ) - utc_offset_minutes: int = proto.Field( - proto.INT32, - number=22, - optional=True, - ) - photos: MutableSequence[photo.Photo] = proto.RepeatedField( - proto.MESSAGE, - number=54, - message=photo.Photo, - ) - adr_format_address: str = proto.Field( - proto.STRING, - number=24, - ) - business_status: BusinessStatus = proto.Field( - proto.ENUM, - number=25, - enum=BusinessStatus, - ) - price_level: 'PriceLevel' = proto.Field( - proto.ENUM, - number=26, - enum='PriceLevel', - ) - attributions: MutableSequence[Attribution] = proto.RepeatedField( - proto.MESSAGE, - number=27, - message=Attribution, - ) - user_rating_count: int = proto.Field( - proto.INT32, - number=28, - optional=True, - ) - icon_mask_base_uri: str = proto.Field( - proto.STRING, - number=29, - ) - icon_background_color: str = proto.Field( - proto.STRING, - number=30, - ) - takeout: bool = proto.Field( - proto.BOOL, - number=33, - optional=True, - ) - delivery: bool = proto.Field( - proto.BOOL, - number=34, - optional=True, - ) - dine_in: bool = proto.Field( - proto.BOOL, - number=35, - optional=True, - ) - curbside_pickup: bool = proto.Field( - proto.BOOL, - number=36, - optional=True, - ) - reservable: bool = proto.Field( - proto.BOOL, - number=38, - optional=True, - ) - serves_breakfast: bool = proto.Field( - proto.BOOL, - number=39, - optional=True, - ) - serves_lunch: bool = proto.Field( - proto.BOOL, - number=40, - optional=True, - ) - serves_dinner: bool = proto.Field( - proto.BOOL, - number=41, - optional=True, - ) - serves_beer: bool = proto.Field( - proto.BOOL, - number=42, - optional=True, - ) - serves_wine: bool = proto.Field( - proto.BOOL, - number=43, - optional=True, - ) - serves_brunch: bool = proto.Field( - proto.BOOL, - number=44, - optional=True, - ) - serves_vegetarian_food: bool = proto.Field( - proto.BOOL, - number=45, - optional=True, - ) - current_opening_hours: OpeningHours = proto.Field( - proto.MESSAGE, - number=46, - message=OpeningHours, - ) - current_secondary_opening_hours: MutableSequence[OpeningHours] = proto.RepeatedField( - proto.MESSAGE, - number=47, - message=OpeningHours, - ) - regular_secondary_opening_hours: MutableSequence[OpeningHours] = proto.RepeatedField( - proto.MESSAGE, - number=49, - message=OpeningHours, - ) - editorial_summary: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=52, - message=localized_text_pb2.LocalizedText, - ) - outdoor_seating: bool = proto.Field( - proto.BOOL, - number=55, - optional=True, - ) - live_music: bool = proto.Field( - proto.BOOL, - number=56, - optional=True, - ) - menu_for_children: bool = proto.Field( - proto.BOOL, - number=57, - optional=True, - ) - serves_cocktails: bool = proto.Field( - proto.BOOL, - number=58, - optional=True, - ) - serves_dessert: bool = proto.Field( - proto.BOOL, - number=59, - optional=True, - ) - serves_coffee: bool = proto.Field( - proto.BOOL, - number=60, - optional=True, - ) - good_for_children: bool = proto.Field( - proto.BOOL, - number=62, - optional=True, - ) - allows_dogs: bool = proto.Field( - proto.BOOL, - number=63, - optional=True, - ) - restroom: bool = proto.Field( - proto.BOOL, - number=64, - optional=True, - ) - good_for_groups: bool = proto.Field( - proto.BOOL, - number=65, - optional=True, - ) - good_for_watching_sports: bool = proto.Field( - proto.BOOL, - number=66, - optional=True, - ) - payment_options: PaymentOptions = proto.Field( - proto.MESSAGE, - number=67, - message=PaymentOptions, - ) - parking_options: ParkingOptions = proto.Field( - proto.MESSAGE, - number=70, - message=ParkingOptions, - ) - sub_destinations: MutableSequence[SubDestination] = proto.RepeatedField( - proto.MESSAGE, - number=71, - message=SubDestination, - ) - accessibility_options: AccessibilityOptions = proto.Field( - proto.MESSAGE, - number=72, - optional=True, - message=AccessibilityOptions, - ) - fuel_options: gmp_fuel_options.FuelOptions = proto.Field( - proto.MESSAGE, - number=78, - message=gmp_fuel_options.FuelOptions, - ) - ev_charge_options: ev_charging.EVChargeOptions = proto.Field( - proto.MESSAGE, - number=79, - message=ev_charging.EVChargeOptions, - ) - generative_summary: GenerativeSummary = proto.Field( - proto.MESSAGE, - number=80, - message=GenerativeSummary, - ) - area_summary: AreaSummary = proto.Field( - proto.MESSAGE, - number=81, - message=AreaSummary, - ) - containing_places: MutableSequence[ContainingPlace] = proto.RepeatedField( - proto.MESSAGE, - number=82, - message=ContainingPlace, - ) - pure_service_area_business: bool = proto.Field( - proto.BOOL, - number=83, - optional=True, - ) - price_range: gmp_price_range.PriceRange = proto.Field( - proto.MESSAGE, - number=86, - message=gmp_price_range.PriceRange, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/places_service.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/places_service.py deleted file mode 100644 index efd86f57ba22..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/places_service.py +++ /dev/null @@ -1,1340 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.geo.type.types import viewport -from google.maps.places_v1.types import contextual_content -from google.maps.places_v1.types import ev_charging -from google.maps.places_v1.types import geometry -from google.maps.places_v1.types import place as gmp_place -from google.maps.places_v1.types import polyline as gmp_polyline -from google.maps.places_v1.types import route_modifiers as gmp_route_modifiers -from google.maps.places_v1.types import routing_preference as gmp_routing_preference -from google.maps.places_v1.types import routing_summary -from google.maps.places_v1.types import travel_mode as gmp_travel_mode -from google.type import latlng_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.places.v1', - manifest={ - 'RoutingParameters', - 'SearchNearbyRequest', - 'SearchNearbyResponse', - 'SearchTextRequest', - 'SearchTextResponse', - 'GetPhotoMediaRequest', - 'PhotoMedia', - 'GetPlaceRequest', - 'AutocompletePlacesRequest', - 'AutocompletePlacesResponse', - }, -) - - -class RoutingParameters(proto.Message): - r"""Parameters to configure the routing calculations to the - places in the response, both along a route (where result ranking - will be influenced) and for calculating travel times on results. - - Attributes: - origin (google.type.latlng_pb2.LatLng): - Optional. An explicit routing origin that - overrides the origin defined in the polyline. By - default, the polyline origin is used. - travel_mode (google.maps.places_v1.types.TravelMode): - Optional. The travel mode. - route_modifiers (google.maps.places_v1.types.RouteModifiers): - Optional. The route modifiers. - routing_preference (google.maps.places_v1.types.RoutingPreference): - Optional. Specifies how to compute the routing summaries. - The server attempts to use the selected routing preference - to compute the route. The traffic aware routing preference - is only available for the ``DRIVE`` or ``TWO_WHEELER`` - ``travelMode``. - """ - - origin: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=1, - message=latlng_pb2.LatLng, - ) - travel_mode: gmp_travel_mode.TravelMode = proto.Field( - proto.ENUM, - number=2, - enum=gmp_travel_mode.TravelMode, - ) - route_modifiers: gmp_route_modifiers.RouteModifiers = proto.Field( - proto.MESSAGE, - number=3, - message=gmp_route_modifiers.RouteModifiers, - ) - routing_preference: gmp_routing_preference.RoutingPreference = proto.Field( - proto.ENUM, - number=4, - enum=gmp_routing_preference.RoutingPreference, - ) - - -class SearchNearbyRequest(proto.Message): - r"""Request proto for Search Nearby. - - Attributes: - language_code (str): - Place details will be displayed with the - preferred language if available. If the language - code is unspecified or unrecognized, place - details of any language may be returned, with a - preference for English if such details exist. - - Current list of supported languages: - - https://developers.google.com/maps/faq#languagesupport. - region_code (str): - The Unicode country/region code (CLDR) of the location where - the request is coming from. This parameter is used to - display the place details, like region-specific place name, - if available. The parameter can affect results based on - applicable law. - - For more information, see - https://www.unicode.org/cldr/charts/latest/supplemental/territory_language_information.html. - - Note that 3-digit region codes are not currently supported. - included_types (MutableSequence[str]): - Included Place type (eg, "restaurant" or "gas_station") from - https://developers.google.com/maps/documentation/places/web-service/place-types. - - Up to 50 types from `Table - A `__ - may be specified. - - If there are any conflicting types, i.e. a type appears in - both included_types and excluded_types, an INVALID_ARGUMENT - error is returned. - - If a Place type is specified with multiple type - restrictions, only places that satisfy all of the - restrictions are returned. For example, if we have - {included_types = ["restaurant"], excluded_primary_types = - ["restaurant"]}, the returned places provide "restaurant" - related services but do not operate primarily as - "restaurants". - excluded_types (MutableSequence[str]): - Excluded Place type (eg, "restaurant" or "gas_station") from - https://developers.google.com/maps/documentation/places/web-service/place-types. - - Up to 50 types from `Table - A `__ - may be specified. - - If the client provides both included_types (e.g. restaurant) - and excluded_types (e.g. cafe), then the response should - include places that are restaurant but not cafe. The - response includes places that match at least one of the - included_types and none of the excluded_types. - - If there are any conflicting types, i.e. a type appears in - both included_types and excluded_types, an INVALID_ARGUMENT - error is returned. - - If a Place type is specified with multiple type - restrictions, only places that satisfy all of the - restrictions are returned. For example, if we have - {included_types = ["restaurant"], excluded_primary_types = - ["restaurant"]}, the returned places provide "restaurant" - related services but do not operate primarily as - "restaurants". - included_primary_types (MutableSequence[str]): - Included primary Place type (e.g. "restaurant" or - "gas_station") from - https://developers.google.com/maps/documentation/places/web-service/place-types. - A place can only have a single primary type from the - supported types table associated with it. - - Up to 50 types from `Table - A `__ - may be specified. - - If there are any conflicting primary types, i.e. a type - appears in both included_primary_types and - excluded_primary_types, an INVALID_ARGUMENT error is - returned. - - If a Place type is specified with multiple type - restrictions, only places that satisfy all of the - restrictions are returned. For example, if we have - {included_types = ["restaurant"], excluded_primary_types = - ["restaurant"]}, the returned places provide "restaurant" - related services but do not operate primarily as - "restaurants". - excluded_primary_types (MutableSequence[str]): - Excluded primary Place type (e.g. "restaurant" or - "gas_station") from - https://developers.google.com/maps/documentation/places/web-service/place-types. - - Up to 50 types from `Table - A `__ - may be specified. - - If there are any conflicting primary types, i.e. a type - appears in both included_primary_types and - excluded_primary_types, an INVALID_ARGUMENT error is - returned. - - If a Place type is specified with multiple type - restrictions, only places that satisfy all of the - restrictions are returned. For example, if we have - {included_types = ["restaurant"], excluded_primary_types = - ["restaurant"]}, the returned places provide "restaurant" - related services but do not operate primarily as - "restaurants". - max_result_count (int): - Maximum number of results to return. It must be between 1 - and 20 (default), inclusively. If the number is unset, it - falls back to the upper limit. If the number is set to - negative or exceeds the upper limit, an INVALID_ARGUMENT - error is returned. - location_restriction (google.maps.places_v1.types.SearchNearbyRequest.LocationRestriction): - Required. The region to search. - rank_preference (google.maps.places_v1.types.SearchNearbyRequest.RankPreference): - How results will be ranked in the response. - routing_parameters (google.maps.places_v1.types.RoutingParameters): - Optional. Parameters that affect the routing - to the search results. - """ - class RankPreference(proto.Enum): - r"""How results will be ranked in the response. - - Values: - RANK_PREFERENCE_UNSPECIFIED (0): - RankPreference value not set. Will use rank - by POPULARITY by default. - DISTANCE (1): - Ranks results by distance. - POPULARITY (2): - Ranks results by popularity. - """ - RANK_PREFERENCE_UNSPECIFIED = 0 - DISTANCE = 1 - POPULARITY = 2 - - class LocationRestriction(proto.Message): - r"""The region to search. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - circle (google.maps.places_v1.types.Circle): - A circle defined by center point and radius. - - This field is a member of `oneof`_ ``type``. - """ - - circle: geometry.Circle = proto.Field( - proto.MESSAGE, - number=2, - oneof='type', - message=geometry.Circle, - ) - - language_code: str = proto.Field( - proto.STRING, - number=1, - ) - region_code: str = proto.Field( - proto.STRING, - number=2, - ) - included_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - excluded_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - included_primary_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - excluded_primary_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=6, - ) - max_result_count: int = proto.Field( - proto.INT32, - number=7, - ) - location_restriction: LocationRestriction = proto.Field( - proto.MESSAGE, - number=8, - message=LocationRestriction, - ) - rank_preference: RankPreference = proto.Field( - proto.ENUM, - number=9, - enum=RankPreference, - ) - routing_parameters: 'RoutingParameters' = proto.Field( - proto.MESSAGE, - number=10, - message='RoutingParameters', - ) - - -class SearchNearbyResponse(proto.Message): - r"""Response proto for Search Nearby. - - Attributes: - places (MutableSequence[google.maps.places_v1.types.Place]): - A list of places that meets user's - requirements like places types, number of places - and specific location restriction. - routing_summaries (MutableSequence[google.maps.places_v1.types.RoutingSummary]): - A list of routing summaries where each entry associates to - the corresponding place in the same index in the ``places`` - field. If the routing summary is not available for one of - the places, it will contain an empty entry. This list should - have as many entries as the list of places if requested. - """ - - places: MutableSequence[gmp_place.Place] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gmp_place.Place, - ) - routing_summaries: MutableSequence[routing_summary.RoutingSummary] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=routing_summary.RoutingSummary, - ) - - -class SearchTextRequest(proto.Message): - r"""Request proto for SearchText. - - Attributes: - text_query (str): - Required. The text query for textual search. - language_code (str): - Place details will be displayed with the - preferred language if available. If the language - code is unspecified or unrecognized, place - details of any language may be returned, with a - preference for English if such details exist. - - Current list of supported languages: - - https://developers.google.com/maps/faq#languagesupport. - region_code (str): - The Unicode country/region code (CLDR) of the location where - the request is coming from. This parameter is used to - display the place details, like region-specific place name, - if available. The parameter can affect results based on - applicable law. - - For more information, see - https://www.unicode.org/cldr/charts/latest/supplemental/territory_language_information.html. - - Note that 3-digit region codes are not currently supported. - rank_preference (google.maps.places_v1.types.SearchTextRequest.RankPreference): - How results will be ranked in the response. - included_type (str): - The requested place type. Full list of types - supported: - https://developers.google.com/maps/documentation/places/web-service/place-types. - Only support one included type. - open_now (bool): - Used to restrict the search to places that - are currently open. The default is false. - min_rating (float): - Filter out results whose average user rating is strictly - less than this limit. A valid value must be a float between - 0 and 5 (inclusively) at a 0.5 cadence i.e. [0, 0.5, 1.0, - ... , 5.0] inclusively. The input rating will round up to - the nearest 0.5(ceiling). For instance, a rating of 0.6 will - eliminate all results with a less than 1.0 rating. - max_result_count (int): - Maximum number of results to return. It must be between 1 - and 20, inclusively. The default is 20. If the number is - unset, it falls back to the upper limit. If the number is - set to negative or exceeds the upper limit, an - INVALID_ARGUMENT error is returned. - price_levels (MutableSequence[google.maps.places_v1.types.PriceLevel]): - Used to restrict the search to places that - are marked as certain price levels. Users can - choose any combinations of price levels. Default - to select all price levels. - strict_type_filtering (bool): - Used to set strict type filtering for included_type. If set - to true, only results of the same type will be returned. - Default to false. - location_bias (google.maps.places_v1.types.SearchTextRequest.LocationBias): - The region to search. This location serves as a bias which - means results around given location might be returned. - Cannot be set along with location_restriction. - location_restriction (google.maps.places_v1.types.SearchTextRequest.LocationRestriction): - The region to search. This location serves as a restriction - which means results outside given location will not be - returned. Cannot be set along with location_bias. - ev_options (google.maps.places_v1.types.SearchTextRequest.EVOptions): - Optional. Set the searchable EV options of a - place search request. - routing_parameters (google.maps.places_v1.types.RoutingParameters): - Optional. Additional parameters for routing - to results. - search_along_route_parameters (google.maps.places_v1.types.SearchTextRequest.SearchAlongRouteParameters): - Optional. Additional parameters proto for - searching along a route. - include_pure_service_area_businesses (bool): - Optional. Include pure service area businesses if the field - is set to true. Pure service area business is a business - that visits or delivers to customers directly but does not - serve customers at their business address. For example, - businesses like cleaning services or plumbers. Those - businesses do not have a physical address or location on - Google Maps. Places will not return fields including - ``location``, ``plus_code``, and other location related - fields for these businesses. - """ - class RankPreference(proto.Enum): - r"""How results will be ranked in the response. - - Values: - RANK_PREFERENCE_UNSPECIFIED (0): - For a categorical query such as "Restaurants - in New York City", RELEVANCE is the default. For - non-categorical queries such as "Mountain View, - CA" we recommend that you leave rankPreference - unset. - DISTANCE (1): - Ranks results by distance. - RELEVANCE (2): - Ranks results by relevance. Sort order - determined by normal ranking stack. - """ - RANK_PREFERENCE_UNSPECIFIED = 0 - DISTANCE = 1 - RELEVANCE = 2 - - class LocationBias(proto.Message): - r"""The region to search. This location serves as a bias which - means results around given location might be returned. - - 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: - rectangle (google.geo.type.types.Viewport): - A rectangle box defined by northeast and southwest corner. - ``rectangle.high()`` must be the northeast point of the - rectangle viewport. ``rectangle.low()`` must be the - southwest point of the rectangle viewport. - ``rectangle.low().latitude()`` cannot be greater than - ``rectangle.high().latitude()``. This will result in an - empty latitude range. A rectangle viewport cannot be wider - than 180 degrees. - - This field is a member of `oneof`_ ``type``. - circle (google.maps.places_v1.types.Circle): - A circle defined by center point and radius. - - This field is a member of `oneof`_ ``type``. - """ - - rectangle: viewport.Viewport = proto.Field( - proto.MESSAGE, - number=1, - oneof='type', - message=viewport.Viewport, - ) - circle: geometry.Circle = proto.Field( - proto.MESSAGE, - number=2, - oneof='type', - message=geometry.Circle, - ) - - class LocationRestriction(proto.Message): - r"""The region to search. This location serves as a restriction - which means results outside given location will not be returned. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - rectangle (google.geo.type.types.Viewport): - A rectangle box defined by northeast and southwest corner. - ``rectangle.high()`` must be the northeast point of the - rectangle viewport. ``rectangle.low()`` must be the - southwest point of the rectangle viewport. - ``rectangle.low().latitude()`` cannot be greater than - ``rectangle.high().latitude()``. This will result in an - empty latitude range. A rectangle viewport cannot be wider - than 180 degrees. - - This field is a member of `oneof`_ ``type``. - """ - - rectangle: viewport.Viewport = proto.Field( - proto.MESSAGE, - number=1, - oneof='type', - message=viewport.Viewport, - ) - - class EVOptions(proto.Message): - r"""Searchable EV options of a place search request. - - Attributes: - minimum_charging_rate_kw (float): - Optional. Minimum required charging rate in - kilowatts. A place with a charging rate less - than the specified rate is filtered out. - connector_types (MutableSequence[google.maps.places_v1.types.EVConnectorType]): - Optional. The list of preferred EV connector - types. A place that does not support any of the - listed connector types is filtered out. - """ - - minimum_charging_rate_kw: float = proto.Field( - proto.DOUBLE, - number=1, - ) - connector_types: MutableSequence[ev_charging.EVConnectorType] = proto.RepeatedField( - proto.ENUM, - number=2, - enum=ev_charging.EVConnectorType, - ) - - class SearchAlongRouteParameters(proto.Message): - r"""Specifies a precalculated polyline from the `Routes - API `__ - defining the route to search. Searching along a route is similar to - using the ``locationBias`` or ``locationRestriction`` request option - to bias the search results. However, while the ``locationBias`` and - ``locationRestriction`` options let you specify a region to bias the - search results, this option lets you bias the results along a trip - route. - - Results are not guaranteed to be along the route provided, but - rather are ranked within the search area defined by the polyline - and, optionally, by the ``locationBias`` or ``locationRestriction`` - based on minimal detour times from origin to destination. The - results might be along an alternate route, especially if the - provided polyline does not define an optimal route from origin to - destination. - - Attributes: - polyline (google.maps.places_v1.types.Polyline): - Required. The route polyline. - """ - - polyline: gmp_polyline.Polyline = proto.Field( - proto.MESSAGE, - number=1, - message=gmp_polyline.Polyline, - ) - - text_query: str = proto.Field( - proto.STRING, - number=1, - ) - language_code: str = proto.Field( - proto.STRING, - number=2, - ) - region_code: str = proto.Field( - proto.STRING, - number=3, - ) - rank_preference: RankPreference = proto.Field( - proto.ENUM, - number=4, - enum=RankPreference, - ) - included_type: str = proto.Field( - proto.STRING, - number=6, - ) - open_now: bool = proto.Field( - proto.BOOL, - number=7, - ) - min_rating: float = proto.Field( - proto.DOUBLE, - number=9, - ) - max_result_count: int = proto.Field( - proto.INT32, - number=10, - ) - price_levels: MutableSequence[gmp_place.PriceLevel] = proto.RepeatedField( - proto.ENUM, - number=11, - enum=gmp_place.PriceLevel, - ) - strict_type_filtering: bool = proto.Field( - proto.BOOL, - number=12, - ) - location_bias: LocationBias = proto.Field( - proto.MESSAGE, - number=13, - message=LocationBias, - ) - location_restriction: LocationRestriction = proto.Field( - proto.MESSAGE, - number=14, - message=LocationRestriction, - ) - ev_options: EVOptions = proto.Field( - proto.MESSAGE, - number=15, - message=EVOptions, - ) - routing_parameters: 'RoutingParameters' = proto.Field( - proto.MESSAGE, - number=16, - message='RoutingParameters', - ) - search_along_route_parameters: SearchAlongRouteParameters = proto.Field( - proto.MESSAGE, - number=17, - message=SearchAlongRouteParameters, - ) - include_pure_service_area_businesses: bool = proto.Field( - proto.BOOL, - number=20, - ) - - -class SearchTextResponse(proto.Message): - r"""Response proto for SearchText. - - Attributes: - places (MutableSequence[google.maps.places_v1.types.Place]): - A list of places that meet the user's text - search criteria. - routing_summaries (MutableSequence[google.maps.places_v1.types.RoutingSummary]): - A list of routing summaries where each entry associates to - the corresponding place in the same index in the ``places`` - field. If the routing summary is not available for one of - the places, it will contain an empty entry. This list will - have as many entries as the list of places if requested. - contextual_contents (MutableSequence[google.maps.places_v1.types.ContextualContent]): - Experimental: See - https://developers.google.com/maps/documentation/places/web-service/experimental/places-generative - for more details. - - A list of contextual contents where each entry associates to - the corresponding place in the same index in the places - field. The contents that are relevant to the ``text_query`` - in the request are preferred. If the contextual content is - not available for one of the places, it will return - non-contextual content. It will be empty only when the - content is unavailable for this place. This list will have - as many entries as the list of places if requested. - """ - - places: MutableSequence[gmp_place.Place] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gmp_place.Place, - ) - routing_summaries: MutableSequence[routing_summary.RoutingSummary] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=routing_summary.RoutingSummary, - ) - contextual_contents: MutableSequence[contextual_content.ContextualContent] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=contextual_content.ContextualContent, - ) - - -class GetPhotoMediaRequest(proto.Message): - r"""Request for fetching a photo of a place using a photo - resource name. - - Attributes: - name (str): - Required. The resource name of a photo media in the format: - ``places/{place_id}/photos/{photo_reference}/media``. - - The resource name of a photo as returned in a Place object's - ``photos.name`` field comes with the format - ``places/{place_id}/photos/{photo_reference}``. You need to - append ``/media`` at the end of the photo resource to get - the photo media resource name. - max_width_px (int): - Optional. Specifies the maximum desired width, in pixels, of - the image. If the image is smaller than the values - specified, the original image will be returned. If the image - is larger in either dimension, it will be scaled to match - the smaller of the two dimensions, restricted to its - original aspect ratio. Both the max_height_px and - max_width_px properties accept an integer between 1 and - 4800, inclusively. If the value is not within the allowed - range, an INVALID_ARGUMENT error will be returned. - - At least one of max_height_px or max_width_px needs to be - specified. If neither max_height_px nor max_width_px is - specified, an INVALID_ARGUMENT error will be returned. - max_height_px (int): - Optional. Specifies the maximum desired height, in pixels, - of the image. If the image is smaller than the values - specified, the original image will be returned. If the image - is larger in either dimension, it will be scaled to match - the smaller of the two dimensions, restricted to its - original aspect ratio. Both the max_height_px and - max_width_px properties accept an integer between 1 and - 4800, inclusively. If the value is not within the allowed - range, an INVALID_ARGUMENT error will be returned. - - At least one of max_height_px or max_width_px needs to be - specified. If neither max_height_px nor max_width_px is - specified, an INVALID_ARGUMENT error will be returned. - skip_http_redirect (bool): - Optional. If set, skip the default HTTP - redirect behavior and render a text format (for - example, in JSON format for HTTP use case) - response. If not set, an HTTP redirect will be - issued to redirect the call to the image media. - This option is ignored for non-HTTP requests. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - max_width_px: int = proto.Field( - proto.INT32, - number=2, - ) - max_height_px: int = proto.Field( - proto.INT32, - number=3, - ) - skip_http_redirect: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class PhotoMedia(proto.Message): - r"""A photo media from Places API. - - Attributes: - name (str): - The resource name of a photo media in the format: - ``places/{place_id}/photos/{photo_reference}/media``. - photo_uri (str): - A short-lived uri that can be used to render - the photo. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - photo_uri: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetPlaceRequest(proto.Message): - r"""Request for fetching a Place based on its resource name, which is a - string in the ``places/{place_id}`` format. - - Attributes: - name (str): - Required. The resource name of a place, in the - ``places/{place_id}`` format. - language_code (str): - Optional. Place details will be displayed - with the preferred language if available. - - Current list of supported languages: - - https://developers.google.com/maps/faq#languagesupport. - region_code (str): - Optional. The Unicode country/region code (CLDR) of the - location where the request is coming from. This parameter is - used to display the place details, like region-specific - place name, if available. The parameter can affect results - based on applicable law. For more information, see - https://www.unicode.org/cldr/charts/latest/supplemental/territory_language_information.html. - - Note that 3-digit region codes are not currently supported. - session_token (str): - Optional. A string which identifies an Autocomplete session - for billing purposes. Must be a URL and filename safe base64 - string with at most 36 ASCII characters in length. Otherwise - an INVALID_ARGUMENT error is returned. - - The session begins when the user starts typing a query, and - concludes when they select a place and a call to Place - Details or Address Validation is made. Each session can have - multiple queries, followed by one Place Details or Address - Validation request. The credentials used for each request - within a session must belong to the same Google Cloud - Console project. Once a session has concluded, the token is - no longer valid; your app must generate a fresh token for - each session. If the ``session_token`` parameter is omitted, - or if you reuse a session token, the session is charged as - if no session token was provided (each request is billed - separately). - - We recommend the following guidelines: - - - Use session tokens for all Place Autocomplete calls. - - Generate a fresh token for each session. Using a version - 4 UUID is recommended. - - Ensure that the credentials used for all Place - Autocomplete, Place Details, and Address Validation - requests within a session belong to the same Cloud - Console project. - - Be sure to pass a unique session token for each new - session. Using the same token for more than one session - will result in each request being billed individually. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - language_code: str = proto.Field( - proto.STRING, - number=2, - ) - region_code: str = proto.Field( - proto.STRING, - number=3, - ) - session_token: str = proto.Field( - proto.STRING, - number=4, - ) - - -class AutocompletePlacesRequest(proto.Message): - r"""Request proto for AutocompletePlaces. - - Attributes: - input (str): - Required. The text string on which to search. - location_bias (google.maps.places_v1.types.AutocompletePlacesRequest.LocationBias): - Optional. Bias results to a specified location. - - At most one of ``location_bias`` or ``location_restriction`` - should be set. If neither are set, the results will be - biased by IP address, meaning the IP address will be mapped - to an imprecise location and used as a biasing signal. - location_restriction (google.maps.places_v1.types.AutocompletePlacesRequest.LocationRestriction): - Optional. Restrict results to a specified location. - - At most one of ``location_bias`` or ``location_restriction`` - should be set. If neither are set, the results will be - biased by IP address, meaning the IP address will be mapped - to an imprecise location and used as a biasing signal. - included_primary_types (MutableSequence[str]): - Optional. Included primary Place type (for example, - "restaurant" or "gas_station") in Place Types - (https://developers.google.com/maps/documentation/places/web-service/place-types), - or only ``(regions)``, or only ``(cities)``. A Place is only - returned if its primary type is included in this list. Up to - 5 values can be specified. If no types are specified, all - Place types are returned. - included_region_codes (MutableSequence[str]): - Optional. Only include results in the specified regions, - specified as up to 15 CLDR two-character region codes. An - empty set will not restrict the results. If both - ``location_restriction`` and ``included_region_codes`` are - set, the results will be located in the area of - intersection. - language_code (str): - Optional. The language in which to return results. Defaults - to en-US. The results may be in mixed languages if the - language used in ``input`` is different from - ``language_code`` or if the returned Place does not have a - translation from the local language to ``language_code``. - region_code (str): - Optional. The region code, specified as a CLDR two-character - region code. This affects address formatting, result - ranking, and may influence what results are returned. This - does not restrict results to the specified region. To - restrict results to a region, use - ``region_code_restriction``. - origin (google.type.latlng_pb2.LatLng): - Optional. The origin point from which to calculate geodesic - distance to the destination (returned as - ``distance_meters``). If this value is omitted, geodesic - distance will not be returned. - input_offset (int): - Optional. A zero-based Unicode character offset of ``input`` - indicating the cursor position in ``input``. The cursor - position may influence what predictions are returned. - - If empty, defaults to the length of ``input``. - include_query_predictions (bool): - Optional. If true, the response will include - both Place and query predictions. Otherwise the - response will only return Place predictions. - session_token (str): - Optional. A string which identifies an Autocomplete session - for billing purposes. Must be a URL and filename safe base64 - string with at most 36 ASCII characters in length. Otherwise - an INVALID_ARGUMENT error is returned. - - The session begins when the user starts typing a query, and - concludes when they select a place and a call to Place - Details or Address Validation is made. Each session can have - multiple queries, followed by one Place Details or Address - Validation request. The credentials used for each request - within a session must belong to the same Google Cloud - Console project. Once a session has concluded, the token is - no longer valid; your app must generate a fresh token for - each session. If the ``session_token`` parameter is omitted, - or if you reuse a session token, the session is charged as - if no session token was provided (each request is billed - separately). - - We recommend the following guidelines: - - - Use session tokens for all Place Autocomplete calls. - - Generate a fresh token for each session. Using a version - 4 UUID is recommended. - - Ensure that the credentials used for all Place - Autocomplete, Place Details, and Address Validation - requests within a session belong to the same Cloud - Console project. - - Be sure to pass a unique session token for each new - session. Using the same token for more than one session - will result in each request being billed individually. - include_pure_service_area_businesses (bool): - Optional. Include pure service area businesses if the field - is set to true. Pure service area business is a business - that visits or delivers to customers directly but does not - serve customers at their business address. For example, - businesses like cleaning services or plumbers. Those - businesses do not have a physical address or location on - Google Maps. Places will not return fields including - ``location``, ``plus_code``, and other location related - fields for these businesses. - """ - - class LocationBias(proto.Message): - r"""The region to search. The results may be biased around the - specified region. - - 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: - rectangle (google.geo.type.types.Viewport): - A viewport defined by a northeast and a - southwest corner. - - This field is a member of `oneof`_ ``type``. - circle (google.maps.places_v1.types.Circle): - A circle defined by a center point and - radius. - - This field is a member of `oneof`_ ``type``. - """ - - rectangle: viewport.Viewport = proto.Field( - proto.MESSAGE, - number=1, - oneof='type', - message=viewport.Viewport, - ) - circle: geometry.Circle = proto.Field( - proto.MESSAGE, - number=2, - oneof='type', - message=geometry.Circle, - ) - - class LocationRestriction(proto.Message): - r"""The region to search. The results will be restricted to the - specified region. - - 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: - rectangle (google.geo.type.types.Viewport): - A viewport defined by a northeast and a - southwest corner. - - This field is a member of `oneof`_ ``type``. - circle (google.maps.places_v1.types.Circle): - A circle defined by a center point and - radius. - - This field is a member of `oneof`_ ``type``. - """ - - rectangle: viewport.Viewport = proto.Field( - proto.MESSAGE, - number=1, - oneof='type', - message=viewport.Viewport, - ) - circle: geometry.Circle = proto.Field( - proto.MESSAGE, - number=2, - oneof='type', - message=geometry.Circle, - ) - - input: str = proto.Field( - proto.STRING, - number=1, - ) - location_bias: LocationBias = proto.Field( - proto.MESSAGE, - number=2, - message=LocationBias, - ) - location_restriction: LocationRestriction = proto.Field( - proto.MESSAGE, - number=3, - message=LocationRestriction, - ) - included_primary_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - included_region_codes: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - language_code: str = proto.Field( - proto.STRING, - number=6, - ) - region_code: str = proto.Field( - proto.STRING, - number=7, - ) - origin: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=8, - message=latlng_pb2.LatLng, - ) - input_offset: int = proto.Field( - proto.INT32, - number=9, - ) - include_query_predictions: bool = proto.Field( - proto.BOOL, - number=10, - ) - session_token: str = proto.Field( - proto.STRING, - number=11, - ) - include_pure_service_area_businesses: bool = proto.Field( - proto.BOOL, - number=12, - ) - - -class AutocompletePlacesResponse(proto.Message): - r"""Response proto for AutocompletePlaces. - - Attributes: - suggestions (MutableSequence[google.maps.places_v1.types.AutocompletePlacesResponse.Suggestion]): - Contains a list of suggestions, ordered in - descending order of relevance. - """ - - class Suggestion(proto.Message): - r"""An Autocomplete suggestion result. - - 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: - place_prediction (google.maps.places_v1.types.AutocompletePlacesResponse.Suggestion.PlacePrediction): - A prediction for a Place. - - This field is a member of `oneof`_ ``kind``. - query_prediction (google.maps.places_v1.types.AutocompletePlacesResponse.Suggestion.QueryPrediction): - A prediction for a query. - - This field is a member of `oneof`_ ``kind``. - """ - - class StringRange(proto.Message): - r"""Identifies a substring within a given text. - - Attributes: - start_offset (int): - Zero-based offset of the first Unicode - character of the string (inclusive). - end_offset (int): - Zero-based offset of the last Unicode - character (exclusive). - """ - - start_offset: int = proto.Field( - proto.INT32, - number=1, - ) - end_offset: int = proto.Field( - proto.INT32, - number=2, - ) - - class FormattableText(proto.Message): - r"""Text representing a Place or query prediction. The text may - be used as is or formatted. - - Attributes: - text (str): - Text that may be used as is or formatted with ``matches``. - matches (MutableSequence[google.maps.places_v1.types.AutocompletePlacesResponse.Suggestion.StringRange]): - A list of string ranges identifying where the input request - matched in ``text``. The ranges can be used to format - specific parts of ``text``. The substrings may not be exact - matches of ``input`` if the matching was determined by - criteria other than string matching (for example, spell - corrections or transliterations). - - These values are Unicode character offsets of ``text``. The - ranges are guaranteed to be ordered in increasing offset - values. - """ - - text: str = proto.Field( - proto.STRING, - number=1, - ) - matches: MutableSequence['AutocompletePlacesResponse.Suggestion.StringRange'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='AutocompletePlacesResponse.Suggestion.StringRange', - ) - - class StructuredFormat(proto.Message): - r"""Contains a breakdown of a Place or query prediction into main - text and secondary text. - - For Place predictions, the main text contains the specific name - of the Place. For query predictions, the main text contains the - query. - - The secondary text contains additional disambiguating features - (such as a city or region) to further identify the Place or - refine the query. - - Attributes: - main_text (google.maps.places_v1.types.AutocompletePlacesResponse.Suggestion.FormattableText): - Represents the name of the Place or query. - secondary_text (google.maps.places_v1.types.AutocompletePlacesResponse.Suggestion.FormattableText): - Represents additional disambiguating features - (such as a city or region) to further identify - the Place or refine the query. - """ - - main_text: 'AutocompletePlacesResponse.Suggestion.FormattableText' = proto.Field( - proto.MESSAGE, - number=1, - message='AutocompletePlacesResponse.Suggestion.FormattableText', - ) - secondary_text: 'AutocompletePlacesResponse.Suggestion.FormattableText' = proto.Field( - proto.MESSAGE, - number=2, - message='AutocompletePlacesResponse.Suggestion.FormattableText', - ) - - class PlacePrediction(proto.Message): - r"""Prediction results for a Place Autocomplete prediction. - - Attributes: - place (str): - The resource name of the suggested Place. - This name can be used in other APIs that accept - Place names. - place_id (str): - The unique identifier of the suggested Place. - This identifier can be used in other APIs that - accept Place IDs. - text (google.maps.places_v1.types.AutocompletePlacesResponse.Suggestion.FormattableText): - Contains the human-readable name for the returned result. - For establishment results, this is usually the business name - and address. - - ``text`` is recommended for developers who wish to show a - single UI element. Developers who wish to show two separate, - but related, UI elements may want to use - ``structured_format`` instead. They are two different ways - to represent a Place prediction. Users should not try to - parse ``structured_format`` into ``text`` or vice versa. - - This text may be different from the ``display_name`` - returned by GetPlace. - - May be in mixed languages if the request ``input`` and - ``language_code`` are in different languages or if the Place - does not have a translation from the local language to - ``language_code``. - structured_format (google.maps.places_v1.types.AutocompletePlacesResponse.Suggestion.StructuredFormat): - A breakdown of the Place prediction into main text - containing the name of the Place and secondary text - containing additional disambiguating features (such as a - city or region). - - ``structured_format`` is recommended for developers who wish - to show two separate, but related, UI elements. Developers - who wish to show a single UI element may want to use - ``text`` instead. They are two different ways to represent a - Place prediction. Users should not try to parse - ``structured_format`` into ``text`` or vice versa. - types (MutableSequence[str]): - List of types that apply to this Place from - Table A or Table B in - https://developers.google.com/maps/documentation/places/web-service/place-types. - - A type is a categorization of a Place. Places - with shared types will share similar - characteristics. - distance_meters (int): - The length of the geodesic in meters from ``origin`` if - ``origin`` is specified. Certain predictions such as routes - may not populate this field. - """ - - place: str = proto.Field( - proto.STRING, - number=1, - ) - place_id: str = proto.Field( - proto.STRING, - number=2, - ) - text: 'AutocompletePlacesResponse.Suggestion.FormattableText' = proto.Field( - proto.MESSAGE, - number=3, - message='AutocompletePlacesResponse.Suggestion.FormattableText', - ) - structured_format: 'AutocompletePlacesResponse.Suggestion.StructuredFormat' = proto.Field( - proto.MESSAGE, - number=4, - message='AutocompletePlacesResponse.Suggestion.StructuredFormat', - ) - types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - distance_meters: int = proto.Field( - proto.INT32, - number=6, - ) - - class QueryPrediction(proto.Message): - r"""Prediction results for a Query Autocomplete prediction. - - Attributes: - text (google.maps.places_v1.types.AutocompletePlacesResponse.Suggestion.FormattableText): - The predicted text. This text does not represent a Place, - but rather a text query that could be used in a search - endpoint (for example, Text Search). - - ``text`` is recommended for developers who wish to show a - single UI element. Developers who wish to show two separate, - but related, UI elements may want to use - ``structured_format`` instead. They are two different ways - to represent a query prediction. Users should not try to - parse ``structured_format`` into ``text`` or vice versa. - - May be in mixed languages if the request ``input`` and - ``language_code`` are in different languages or if part of - the query does not have a translation from the local - language to ``language_code``. - structured_format (google.maps.places_v1.types.AutocompletePlacesResponse.Suggestion.StructuredFormat): - A breakdown of the query prediction into main text - containing the query and secondary text containing - additional disambiguating features (such as a city or - region). - - ``structured_format`` is recommended for developers who wish - to show two separate, but related, UI elements. Developers - who wish to show a single UI element may want to use - ``text`` instead. They are two different ways to represent a - query prediction. Users should not try to parse - ``structured_format`` into ``text`` or vice versa. - """ - - text: 'AutocompletePlacesResponse.Suggestion.FormattableText' = proto.Field( - proto.MESSAGE, - number=1, - message='AutocompletePlacesResponse.Suggestion.FormattableText', - ) - structured_format: 'AutocompletePlacesResponse.Suggestion.StructuredFormat' = proto.Field( - proto.MESSAGE, - number=2, - message='AutocompletePlacesResponse.Suggestion.StructuredFormat', - ) - - place_prediction: 'AutocompletePlacesResponse.Suggestion.PlacePrediction' = proto.Field( - proto.MESSAGE, - number=1, - oneof='kind', - message='AutocompletePlacesResponse.Suggestion.PlacePrediction', - ) - query_prediction: 'AutocompletePlacesResponse.Suggestion.QueryPrediction' = proto.Field( - proto.MESSAGE, - number=2, - oneof='kind', - message='AutocompletePlacesResponse.Suggestion.QueryPrediction', - ) - - suggestions: MutableSequence[Suggestion] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=Suggestion, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/polyline.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/polyline.py deleted file mode 100644 index 6c0ee26282c7..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/polyline.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.places.v1', - manifest={ - 'Polyline', - }, -) - - -class Polyline(proto.Message): - r"""A route polyline. Only supports an `encoded - polyline `__, - which can be passed as a string and includes compression with - minimal lossiness. This is the Routes API default output. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - encoded_polyline (str): - An `encoded - polyline `__, - as returned by the `Routes API by - default `__. - See the - `encoder `__ - and - `decoder `__ - tools. - - This field is a member of `oneof`_ ``polyline_type``. - """ - - encoded_polyline: str = proto.Field( - proto.STRING, - number=1, - oneof='polyline_type', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/price_range.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/price_range.py deleted file mode 100644 index 597eaba8af64..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/price_range.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 money_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.places.v1', - manifest={ - 'PriceRange', - }, -) - - -class PriceRange(proto.Message): - r"""The price range associated with a Place. ``end_price`` could be - unset, which indicates a range without upper bound (e.g. "More than - $100"). - - Attributes: - start_price (google.type.money_pb2.Money): - The low end of the price range (inclusive). - Price should be at or above this amount. - end_price (google.type.money_pb2.Money): - The high end of the price range (exclusive). - Price should be lower than this amount. - """ - - start_price: money_pb2.Money = proto.Field( - proto.MESSAGE, - number=1, - message=money_pb2.Money, - ) - end_price: money_pb2.Money = proto.Field( - proto.MESSAGE, - number=2, - message=money_pb2.Money, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/reference.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/reference.py deleted file mode 100644 index 5dee1df6fa73..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/reference.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.places_v1.types import review - - -__protobuf__ = proto.module( - package='google.maps.places.v1', - manifest={ - 'References', - }, -) - - -class References(proto.Message): - r"""Experimental: See - https://developers.google.com/maps/documentation/places/web-service/experimental/places-generative - for more details. - - Reference that the generative content is related to. - - Attributes: - reviews (MutableSequence[google.maps.places_v1.types.Review]): - Reviews that serve as references. - places (MutableSequence[str]): - The list of resource names of the referenced - places. This name can be used in other APIs that - accept Place resource names. - """ - - reviews: MutableSequence[review.Review] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=review.Review, - ) - places: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/review.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/review.py deleted file mode 100644 index 96e161266398..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/review.py +++ /dev/null @@ -1,94 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.places_v1.types import attribution -from google.protobuf import timestamp_pb2 # type: ignore -from google.type import localized_text_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.places.v1', - manifest={ - 'Review', - }, -) - - -class Review(proto.Message): - r"""Information about a review of a place. - - Attributes: - name (str): - A reference representing this place review which may be used - to look up this place review again (also called the API - "resource" name: ``places/{place_id}/reviews/{review}``). - relative_publish_time_description (str): - A string of formatted recent time, expressing - the review time relative to the current time in - a form appropriate for the language and country. - text (google.type.localized_text_pb2.LocalizedText): - The localized text of the review. - original_text (google.type.localized_text_pb2.LocalizedText): - The review text in its original language. - rating (float): - A number between 1.0 and 5.0, also called the - number of stars. - author_attribution (google.maps.places_v1.types.AuthorAttribution): - This review's author. - publish_time (google.protobuf.timestamp_pb2.Timestamp): - Timestamp for the review. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - relative_publish_time_description: str = proto.Field( - proto.STRING, - number=2, - ) - text: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=9, - message=localized_text_pb2.LocalizedText, - ) - original_text: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=12, - message=localized_text_pb2.LocalizedText, - ) - rating: float = proto.Field( - proto.DOUBLE, - number=7, - ) - author_attribution: attribution.AuthorAttribution = proto.Field( - proto.MESSAGE, - number=13, - message=attribution.AuthorAttribution, - ) - publish_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=14, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/route_modifiers.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/route_modifiers.py deleted file mode 100644 index 8ad10991ebd9..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/route_modifiers.py +++ /dev/null @@ -1,76 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.places.v1', - manifest={ - 'RouteModifiers', - }, -) - - -class RouteModifiers(proto.Message): - r"""Encapsulates a set of optional conditions to satisfy when - calculating the routes. - - Attributes: - avoid_tolls (bool): - Optional. When set to true, avoids toll roads where - reasonable, giving preference to routes not containing toll - roads. Applies only to the ``DRIVE`` and ``TWO_WHEELER`` - [``TravelMode``][google.maps.places.v1.TravelMode]. - avoid_highways (bool): - Optional. When set to true, avoids highways where - reasonable, giving preference to routes not containing - highways. Applies only to the ``DRIVE`` and ``TWO_WHEELER`` - [``TravelMode``][google.maps.places.v1.TravelMode]. - avoid_ferries (bool): - Optional. When set to true, avoids ferries where reasonable, - giving preference to routes not containing ferries. Applies - only to the ``DRIVE`` and ``TWO_WHEELER`` - [``TravelMode``][google.maps.places.v1.TravelMode]. - avoid_indoor (bool): - Optional. When set to true, avoids navigating indoors where - reasonable, giving preference to routes not containing - indoor navigation. Applies only to the ``WALK`` - [``TravelMode``][google.maps.places.v1.TravelMode]. - """ - - avoid_tolls: bool = proto.Field( - proto.BOOL, - number=1, - ) - avoid_highways: bool = proto.Field( - proto.BOOL, - number=2, - ) - avoid_ferries: bool = proto.Field( - proto.BOOL, - number=3, - ) - avoid_indoor: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/routing_preference.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/routing_preference.py deleted file mode 100644 index 56db65ad4e2a..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/routing_preference.py +++ /dev/null @@ -1,71 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.places.v1', - manifest={ - 'RoutingPreference', - }, -) - - -class RoutingPreference(proto.Enum): - r"""A set of values that specify factors to take into - consideration when calculating the route. - - Values: - ROUTING_PREFERENCE_UNSPECIFIED (0): - No routing preference specified. Default to - ``TRAFFIC_UNAWARE``. - TRAFFIC_UNAWARE (1): - Computes routes without taking live traffic conditions into - consideration. Suitable when traffic conditions don't matter - or are not applicable. Using this value produces the lowest - latency. Note: For - [``TravelMode``][google.maps.places.v1.TravelMode] ``DRIVE`` - and ``TWO_WHEELER``, the route and duration chosen are based - on road network and average time-independent traffic - conditions, not current road conditions. Consequently, - routes may include roads that are temporarily closed. - Results for a given request may vary over time due to - changes in the road network, updated average traffic - conditions, and the distributed nature of the service. - Results may also vary between nearly-equivalent routes at - any time or frequency. - TRAFFIC_AWARE (2): - Calculates routes taking live traffic conditions into - consideration. In contrast to ``TRAFFIC_AWARE_OPTIMAL``, - some optimizations are applied to significantly reduce - latency. - TRAFFIC_AWARE_OPTIMAL (3): - Calculates the routes taking live traffic - conditions into consideration, without applying - most performance optimizations. Using this value - produces the highest latency. - """ - ROUTING_PREFERENCE_UNSPECIFIED = 0 - TRAFFIC_UNAWARE = 1 - TRAFFIC_AWARE = 2 - TRAFFIC_AWARE_OPTIMAL = 3 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/routing_summary.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/routing_summary.py deleted file mode 100644 index 741e004f7541..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/routing_summary.py +++ /dev/null @@ -1,95 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 duration_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.places.v1', - manifest={ - 'RoutingSummary', - }, -) - - -class RoutingSummary(proto.Message): - r"""The duration and distance from the routing origin to a place in the - response, and a second leg from that place to the destination, if - requested. **Note:** Adding ``routingSummaries`` in the field mask - without also including either the ``routingParameters.origin`` - parameter or the - ``searchAlongRouteParameters.polyline.encodedPolyline`` parameter in - the request causes an error. - - Attributes: - legs (MutableSequence[google.maps.places_v1.types.RoutingSummary.Leg]): - The legs of the trip. - - When you calculate travel duration and distance from a set - origin, ``legs`` contains a single leg containing the - duration and distance from the origin to the destination. - When you do a search along route, ``legs`` contains two - legs: one from the origin to place, and one from the place - to the destination. - directions_uri (str): - A link to show directions on Google Maps using the waypoints - from the given routing summary. The route generated by this - link is not guaranteed to be the same as the route used to - generate the routing summary. The link uses information - provided in the request, from fields including - ``routingParameters`` and ``searchAlongRouteParameters`` - when applicable, to generate the directions link. - """ - - class Leg(proto.Message): - r"""A leg is a single portion of a journey from one location to - another. - - Attributes: - duration (google.protobuf.duration_pb2.Duration): - The time it takes to complete this leg of the - trip. - distance_meters (int): - The distance of this leg of the trip. - """ - - duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - distance_meters: int = proto.Field( - proto.INT32, - number=2, - ) - - legs: MutableSequence[Leg] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=Leg, - ) - directions_uri: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/travel_mode.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/travel_mode.py deleted file mode 100644 index 270ba1245921..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/travel_mode.py +++ /dev/null @@ -1,63 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.places.v1', - manifest={ - 'TravelMode', - }, -) - - -class TravelMode(proto.Enum): - r"""Travel mode options. These options map to what `Routes API - offers `__. - - Values: - TRAVEL_MODE_UNSPECIFIED (0): - No travel mode specified. Defaults to ``DRIVE``. - DRIVE (1): - Travel by passenger car. - BICYCLE (2): - Travel by bicycle. Not supported with - ``search_along_route_parameters``. - WALK (3): - Travel by walking. Not supported with - ``search_along_route_parameters``. - TWO_WHEELER (4): - Motorized two wheeled vehicles of all kinds such as scooters - and motorcycles. Note that this is distinct from the - ``BICYCLE`` travel mode which covers human-powered - transport. Not supported with - ``search_along_route_parameters``. Only supported in those - countries listed at `Countries and regions supported for - two-wheeled - vehicles `__. - """ - TRAVEL_MODE_UNSPECIFIED = 0 - DRIVE = 1 - BICYCLE = 2 - WALK = 3 - TWO_WHEELER = 4 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/mypy.ini b/owl-bot-staging/google-maps-places/v1/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-maps-places/v1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-maps-places/v1/noxfile.py b/owl-bot-staging/google-maps-places/v1/noxfile.py deleted file mode 100644 index ef3066e9ef06..000000000000 --- a/owl-bot-staging/google-maps-places/v1/noxfile.py +++ /dev/null @@ -1,280 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", - "3.12", - "3.13", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = 'google-maps-places' - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.13" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "prerelease_deps", -] - -@nox.session(python=ALL_PYTHON) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def unit(session, protobuf_implementation): - """Run the unit test suite.""" - - 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+") - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") - - # 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") - - session.run( - 'py.test', - '--quiet', - '--cov=google/maps/places_v1/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - -@nox.session(python=ALL_PYTHON[-1]) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def prerelease_deps(session, protobuf_implementation): - """Run the unit test suite against pre-release versions of dependencies.""" - - 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 test environment dependencies - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - - # Install the package without dependencies - session.install('-e', '.', '--no-deps') - - # We test the minimum dependency versions using the minimum Python - # version so the lowest python runtime that we test has a corresponding constraints - # file, located at `testing/constraints--.txt`, which contains all of the - # 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 - ) - ] - - session.install(*constraints_deps) - - prerel_deps = [ - "googleapis-common-protos", - "google-api-core", - "google-auth", - # Exclude grpcio!=1.67.0rc1 which does not support python 3.13 - "grpcio!=1.67.0rc1", - "grpcio-status", - "protobuf", - "proto-plus", - ] - - for dep in prerel_deps: - session.install("--pre", "--no-deps", "--upgrade", dep) - - # Remaining dependencies - other_deps = [ - "requests", - ] - session.install(*other_deps) - - # Print out prerelease package versions - - session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") - session.run("python", "-c", "import google.auth; print(google.auth.__version__)") - session.run("python", "-c", "import grpc; print(grpc.__version__)") - session.run( - "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" - ) - session.run( - "python", "-c", "import proto; print(proto.__version__)" - ) - - session.run( - 'py.test', - '--quiet', - '--cov=google/maps/places_v1/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - - -@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=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 docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==7.0.1", "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=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", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) diff --git a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_autocomplete_places_async.py b/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_autocomplete_places_async.py deleted file mode 100644 index abd008c9c11a..000000000000 --- a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_autocomplete_places_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AutocompletePlaces -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-places - - -# [START places_v1_generated_Places_AutocompletePlaces_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.maps import places_v1 - - -async def sample_autocomplete_places(): - # Create a client - client = places_v1.PlacesAsyncClient() - - # Initialize request argument(s) - request = places_v1.AutocompletePlacesRequest( - input="input_value", - ) - - # Make the request - response = await client.autocomplete_places(request=request) - - # Handle the response - print(response) - -# [END places_v1_generated_Places_AutocompletePlaces_async] diff --git a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_autocomplete_places_sync.py b/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_autocomplete_places_sync.py deleted file mode 100644 index cf942b606419..000000000000 --- a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_autocomplete_places_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AutocompletePlaces -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-places - - -# [START places_v1_generated_Places_AutocompletePlaces_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.maps import places_v1 - - -def sample_autocomplete_places(): - # Create a client - client = places_v1.PlacesClient() - - # Initialize request argument(s) - request = places_v1.AutocompletePlacesRequest( - input="input_value", - ) - - # Make the request - response = client.autocomplete_places(request=request) - - # Handle the response - print(response) - -# [END places_v1_generated_Places_AutocompletePlaces_sync] diff --git a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_photo_media_async.py b/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_photo_media_async.py deleted file mode 100644 index 45461ad3fabb..000000000000 --- a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_photo_media_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetPhotoMedia -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-places - - -# [START places_v1_generated_Places_GetPhotoMedia_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.maps import places_v1 - - -async def sample_get_photo_media(): - # Create a client - client = places_v1.PlacesAsyncClient() - - # Initialize request argument(s) - request = places_v1.GetPhotoMediaRequest( - name="name_value", - ) - - # Make the request - response = await client.get_photo_media(request=request) - - # Handle the response - print(response) - -# [END places_v1_generated_Places_GetPhotoMedia_async] diff --git a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_photo_media_sync.py b/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_photo_media_sync.py deleted file mode 100644 index 3f76e66b03dc..000000000000 --- a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_photo_media_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetPhotoMedia -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-places - - -# [START places_v1_generated_Places_GetPhotoMedia_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.maps import places_v1 - - -def sample_get_photo_media(): - # Create a client - client = places_v1.PlacesClient() - - # Initialize request argument(s) - request = places_v1.GetPhotoMediaRequest( - name="name_value", - ) - - # Make the request - response = client.get_photo_media(request=request) - - # Handle the response - print(response) - -# [END places_v1_generated_Places_GetPhotoMedia_sync] diff --git a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_place_async.py b/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_place_async.py deleted file mode 100644 index 405094ecdc49..000000000000 --- a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_place_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetPlace -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-places - - -# [START places_v1_generated_Places_GetPlace_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.maps import places_v1 - - -async def sample_get_place(): - # Create a client - client = places_v1.PlacesAsyncClient() - - # Initialize request argument(s) - request = places_v1.GetPlaceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_place(request=request) - - # Handle the response - print(response) - -# [END places_v1_generated_Places_GetPlace_async] diff --git a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_place_sync.py b/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_place_sync.py deleted file mode 100644 index 8f06103be971..000000000000 --- a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_place_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetPlace -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-places - - -# [START places_v1_generated_Places_GetPlace_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.maps import places_v1 - - -def sample_get_place(): - # Create a client - client = places_v1.PlacesClient() - - # Initialize request argument(s) - request = places_v1.GetPlaceRequest( - name="name_value", - ) - - # Make the request - response = client.get_place(request=request) - - # Handle the response - print(response) - -# [END places_v1_generated_Places_GetPlace_sync] diff --git a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_nearby_async.py b/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_nearby_async.py deleted file mode 100644 index ea224ebeb855..000000000000 --- a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_nearby_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SearchNearby -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-places - - -# [START places_v1_generated_Places_SearchNearby_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.maps import places_v1 - - -async def sample_search_nearby(): - # Create a client - client = places_v1.PlacesAsyncClient() - - # Initialize request argument(s) - location_restriction = places_v1.LocationRestriction() - location_restriction.circle.radius = 0.648 - - request = places_v1.SearchNearbyRequest( - location_restriction=location_restriction, - ) - - # Make the request - response = await client.search_nearby(request=request) - - # Handle the response - print(response) - -# [END places_v1_generated_Places_SearchNearby_async] diff --git a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_nearby_sync.py b/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_nearby_sync.py deleted file mode 100644 index 777bbc051f7f..000000000000 --- a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_nearby_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SearchNearby -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-places - - -# [START places_v1_generated_Places_SearchNearby_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.maps import places_v1 - - -def sample_search_nearby(): - # Create a client - client = places_v1.PlacesClient() - - # Initialize request argument(s) - location_restriction = places_v1.LocationRestriction() - location_restriction.circle.radius = 0.648 - - request = places_v1.SearchNearbyRequest( - location_restriction=location_restriction, - ) - - # Make the request - response = client.search_nearby(request=request) - - # Handle the response - print(response) - -# [END places_v1_generated_Places_SearchNearby_sync] diff --git a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_text_async.py b/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_text_async.py deleted file mode 100644 index 5f4b02670755..000000000000 --- a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_text_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SearchText -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-places - - -# [START places_v1_generated_Places_SearchText_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.maps import places_v1 - - -async def sample_search_text(): - # Create a client - client = places_v1.PlacesAsyncClient() - - # Initialize request argument(s) - request = places_v1.SearchTextRequest( - text_query="text_query_value", - ) - - # Make the request - response = await client.search_text(request=request) - - # Handle the response - print(response) - -# [END places_v1_generated_Places_SearchText_async] diff --git a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_text_sync.py b/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_text_sync.py deleted file mode 100644 index fc156bc302cd..000000000000 --- a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_text_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SearchText -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-places - - -# [START places_v1_generated_Places_SearchText_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.maps import places_v1 - - -def sample_search_text(): - # Create a client - client = places_v1.PlacesClient() - - # Initialize request argument(s) - request = places_v1.SearchTextRequest( - text_query="text_query_value", - ) - - # Make the request - response = client.search_text(request=request) - - # Handle the response - print(response) - -# [END places_v1_generated_Places_SearchText_sync] diff --git a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/snippet_metadata_google.maps.places.v1.json b/owl-bot-staging/google-maps-places/v1/samples/generated_samples/snippet_metadata_google.maps.places.v1.json deleted file mode 100644 index bea29a42b294..000000000000 --- a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/snippet_metadata_google.maps.places.v1.json +++ /dev/null @@ -1,796 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.maps.places.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "google-maps-places", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.places_v1.PlacesAsyncClient", - "shortName": "PlacesAsyncClient" - }, - "fullName": "google.maps.places_v1.PlacesAsyncClient.autocomplete_places", - "method": { - "fullName": "google.maps.places.v1.Places.AutocompletePlaces", - "service": { - "fullName": "google.maps.places.v1.Places", - "shortName": "Places" - }, - "shortName": "AutocompletePlaces" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.places_v1.types.AutocompletePlacesRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.maps.places_v1.types.AutocompletePlacesResponse", - "shortName": "autocomplete_places" - }, - "description": "Sample for AutocompletePlaces", - "file": "places_v1_generated_places_autocomplete_places_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "places_v1_generated_Places_AutocompletePlaces_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": "places_v1_generated_places_autocomplete_places_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.places_v1.PlacesClient", - "shortName": "PlacesClient" - }, - "fullName": "google.maps.places_v1.PlacesClient.autocomplete_places", - "method": { - "fullName": "google.maps.places.v1.Places.AutocompletePlaces", - "service": { - "fullName": "google.maps.places.v1.Places", - "shortName": "Places" - }, - "shortName": "AutocompletePlaces" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.places_v1.types.AutocompletePlacesRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.maps.places_v1.types.AutocompletePlacesResponse", - "shortName": "autocomplete_places" - }, - "description": "Sample for AutocompletePlaces", - "file": "places_v1_generated_places_autocomplete_places_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "places_v1_generated_Places_AutocompletePlaces_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": "places_v1_generated_places_autocomplete_places_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.places_v1.PlacesAsyncClient", - "shortName": "PlacesAsyncClient" - }, - "fullName": "google.maps.places_v1.PlacesAsyncClient.get_photo_media", - "method": { - "fullName": "google.maps.places.v1.Places.GetPhotoMedia", - "service": { - "fullName": "google.maps.places.v1.Places", - "shortName": "Places" - }, - "shortName": "GetPhotoMedia" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.places_v1.types.GetPhotoMediaRequest" - }, - { - "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.maps.places_v1.types.PhotoMedia", - "shortName": "get_photo_media" - }, - "description": "Sample for GetPhotoMedia", - "file": "places_v1_generated_places_get_photo_media_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "places_v1_generated_Places_GetPhotoMedia_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": "places_v1_generated_places_get_photo_media_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.places_v1.PlacesClient", - "shortName": "PlacesClient" - }, - "fullName": "google.maps.places_v1.PlacesClient.get_photo_media", - "method": { - "fullName": "google.maps.places.v1.Places.GetPhotoMedia", - "service": { - "fullName": "google.maps.places.v1.Places", - "shortName": "Places" - }, - "shortName": "GetPhotoMedia" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.places_v1.types.GetPhotoMediaRequest" - }, - { - "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.maps.places_v1.types.PhotoMedia", - "shortName": "get_photo_media" - }, - "description": "Sample for GetPhotoMedia", - "file": "places_v1_generated_places_get_photo_media_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "places_v1_generated_Places_GetPhotoMedia_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": "places_v1_generated_places_get_photo_media_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.places_v1.PlacesAsyncClient", - "shortName": "PlacesAsyncClient" - }, - "fullName": "google.maps.places_v1.PlacesAsyncClient.get_place", - "method": { - "fullName": "google.maps.places.v1.Places.GetPlace", - "service": { - "fullName": "google.maps.places.v1.Places", - "shortName": "Places" - }, - "shortName": "GetPlace" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.places_v1.types.GetPlaceRequest" - }, - { - "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.maps.places_v1.types.Place", - "shortName": "get_place" - }, - "description": "Sample for GetPlace", - "file": "places_v1_generated_places_get_place_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "places_v1_generated_Places_GetPlace_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": "places_v1_generated_places_get_place_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.places_v1.PlacesClient", - "shortName": "PlacesClient" - }, - "fullName": "google.maps.places_v1.PlacesClient.get_place", - "method": { - "fullName": "google.maps.places.v1.Places.GetPlace", - "service": { - "fullName": "google.maps.places.v1.Places", - "shortName": "Places" - }, - "shortName": "GetPlace" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.places_v1.types.GetPlaceRequest" - }, - { - "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.maps.places_v1.types.Place", - "shortName": "get_place" - }, - "description": "Sample for GetPlace", - "file": "places_v1_generated_places_get_place_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "places_v1_generated_Places_GetPlace_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": "places_v1_generated_places_get_place_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.places_v1.PlacesAsyncClient", - "shortName": "PlacesAsyncClient" - }, - "fullName": "google.maps.places_v1.PlacesAsyncClient.search_nearby", - "method": { - "fullName": "google.maps.places.v1.Places.SearchNearby", - "service": { - "fullName": "google.maps.places.v1.Places", - "shortName": "Places" - }, - "shortName": "SearchNearby" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.places_v1.types.SearchNearbyRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.maps.places_v1.types.SearchNearbyResponse", - "shortName": "search_nearby" - }, - "description": "Sample for SearchNearby", - "file": "places_v1_generated_places_search_nearby_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "places_v1_generated_Places_SearchNearby_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": "places_v1_generated_places_search_nearby_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.places_v1.PlacesClient", - "shortName": "PlacesClient" - }, - "fullName": "google.maps.places_v1.PlacesClient.search_nearby", - "method": { - "fullName": "google.maps.places.v1.Places.SearchNearby", - "service": { - "fullName": "google.maps.places.v1.Places", - "shortName": "Places" - }, - "shortName": "SearchNearby" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.places_v1.types.SearchNearbyRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.maps.places_v1.types.SearchNearbyResponse", - "shortName": "search_nearby" - }, - "description": "Sample for SearchNearby", - "file": "places_v1_generated_places_search_nearby_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "places_v1_generated_Places_SearchNearby_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": "places_v1_generated_places_search_nearby_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.places_v1.PlacesAsyncClient", - "shortName": "PlacesAsyncClient" - }, - "fullName": "google.maps.places_v1.PlacesAsyncClient.search_text", - "method": { - "fullName": "google.maps.places.v1.Places.SearchText", - "service": { - "fullName": "google.maps.places.v1.Places", - "shortName": "Places" - }, - "shortName": "SearchText" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.places_v1.types.SearchTextRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.maps.places_v1.types.SearchTextResponse", - "shortName": "search_text" - }, - "description": "Sample for SearchText", - "file": "places_v1_generated_places_search_text_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "places_v1_generated_Places_SearchText_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": "places_v1_generated_places_search_text_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.places_v1.PlacesClient", - "shortName": "PlacesClient" - }, - "fullName": "google.maps.places_v1.PlacesClient.search_text", - "method": { - "fullName": "google.maps.places.v1.Places.SearchText", - "service": { - "fullName": "google.maps.places.v1.Places", - "shortName": "Places" - }, - "shortName": "SearchText" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.places_v1.types.SearchTextRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.maps.places_v1.types.SearchTextResponse", - "shortName": "search_text" - }, - "description": "Sample for SearchText", - "file": "places_v1_generated_places_search_text_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "places_v1_generated_Places_SearchText_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": "places_v1_generated_places_search_text_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-maps-places/v1/scripts/fixup_places_v1_keywords.py b/owl-bot-staging/google-maps-places/v1/scripts/fixup_places_v1_keywords.py deleted file mode 100644 index c1c498261a9a..000000000000 --- a/owl-bot-staging/google-maps-places/v1/scripts/fixup_places_v1_keywords.py +++ /dev/null @@ -1,180 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 placesCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'autocomplete_places': ('input', 'location_bias', 'location_restriction', 'included_primary_types', 'included_region_codes', 'language_code', 'region_code', 'origin', 'input_offset', 'include_query_predictions', 'session_token', 'include_pure_service_area_businesses', ), - 'get_photo_media': ('name', 'max_width_px', 'max_height_px', 'skip_http_redirect', ), - 'get_place': ('name', 'language_code', 'region_code', 'session_token', ), - 'search_nearby': ('location_restriction', 'language_code', 'region_code', 'included_types', 'excluded_types', 'included_primary_types', 'excluded_primary_types', 'max_result_count', 'rank_preference', 'routing_parameters', ), - 'search_text': ('text_query', 'language_code', 'region_code', 'rank_preference', 'included_type', 'open_now', 'min_rating', 'max_result_count', 'price_levels', 'strict_type_filtering', 'location_bias', 'location_restriction', 'ev_options', 'routing_parameters', 'search_along_route_parameters', 'include_pure_service_area_businesses', ), - } - - 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=placesCallTransformer(), -): - """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 places 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-maps-places/v1/setup.py b/owl-bot-staging/google-maps-places/v1/setup.py deleted file mode 100644 index 90538f3b071c..000000000000 --- a/owl-bot-staging/google-maps-places/v1/setup.py +++ /dev/null @@ -1,99 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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-maps-places' - - -description = "Google Maps Places API client library" - -version = None - -with open(os.path.join(package_root, 'google/maps/places/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.0dev,!=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.0dev,!=2.24.0,!=2.25.0", - "proto-plus >= 1.22.3, <2.0.0dev", - "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'", - "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", - "google-geo-type >= 0.1.0, <1.0.0dev", -] -extras = { -} -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-places" - -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-maps-places/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-maps-places/v1/testing/constraints-3.10.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-places/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-geo-type diff --git a/owl-bot-staging/google-maps-places/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-maps-places/v1/testing/constraints-3.11.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-places/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-geo-type diff --git a/owl-bot-staging/google-maps-places/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-maps-places/v1/testing/constraints-3.12.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-places/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-geo-type diff --git a/owl-bot-staging/google-maps-places/v1/testing/constraints-3.13.txt b/owl-bot-staging/google-maps-places/v1/testing/constraints-3.13.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-places/v1/testing/constraints-3.13.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-geo-type diff --git a/owl-bot-staging/google-maps-places/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-maps-places/v1/testing/constraints-3.7.txt deleted file mode 100644 index 277853c664a0..000000000000 --- a/owl-bot-staging/google-maps-places/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.0dev", -# 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-geo-type==0.1.0 diff --git a/owl-bot-staging/google-maps-places/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-maps-places/v1/testing/constraints-3.8.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-places/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-geo-type diff --git a/owl-bot-staging/google-maps-places/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-maps-places/v1/testing/constraints-3.9.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-places/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-geo-type diff --git a/owl-bot-staging/google-maps-places/v1/tests/__init__.py b/owl-bot-staging/google-maps-places/v1/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-places/v1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-maps-places/v1/tests/unit/__init__.py b/owl-bot-staging/google-maps-places/v1/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-places/v1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-maps-places/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-maps-places/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-places/v1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-maps-places/v1/tests/unit/gapic/places_v1/__init__.py b/owl-bot-staging/google-maps-places/v1/tests/unit/gapic/places_v1/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-places/v1/tests/unit/gapic/places_v1/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-maps-places/v1/tests/unit/gapic/places_v1/test_places.py b/owl-bot-staging/google-maps-places/v1/tests/unit/gapic/places_v1/test_places.py deleted file mode 100644 index 2020fff86e8d..000000000000 --- a/owl-bot-staging/google-maps-places/v1/tests/unit/gapic/places_v1/test_places.py +++ /dev/null @@ -1,4467 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.geo.type.types import viewport -from google.maps.places_v1.services.places import PlacesAsyncClient -from google.maps.places_v1.services.places import PlacesClient -from google.maps.places_v1.services.places import transports -from google.maps.places_v1.types import contextual_content -from google.maps.places_v1.types import ev_charging -from google.maps.places_v1.types import fuel_options -from google.maps.places_v1.types import geometry -from google.maps.places_v1.types import photo -from google.maps.places_v1.types import place -from google.maps.places_v1.types import places_service -from google.maps.places_v1.types import polyline -from google.maps.places_v1.types import price_range -from google.maps.places_v1.types import review -from google.maps.places_v1.types import route_modifiers -from google.maps.places_v1.types import routing_preference -from google.maps.places_v1.types import routing_summary -from google.maps.places_v1.types import travel_mode -from google.oauth2 import service_account -from google.type import latlng_pb2 # type: ignore -from google.type import localized_text_pb2 # type: ignore -import google.auth - - -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 PlacesClient._get_default_mtls_endpoint(None) is None - assert PlacesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert PlacesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert PlacesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert PlacesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert PlacesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert PlacesClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert PlacesClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert PlacesClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - PlacesClient._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 PlacesClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert PlacesClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert PlacesClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - PlacesClient._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 PlacesClient._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 PlacesClient._get_client_cert_source(None, False) is None - assert PlacesClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert PlacesClient._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 PlacesClient._get_client_cert_source(None, True) is mock_default_cert_source - assert PlacesClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(PlacesClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PlacesClient)) -@mock.patch.object(PlacesAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PlacesAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = PlacesClient._DEFAULT_UNIVERSE - default_endpoint = PlacesClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = PlacesClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert PlacesClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert PlacesClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == PlacesClient.DEFAULT_MTLS_ENDPOINT - assert PlacesClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert PlacesClient._get_api_endpoint(None, None, default_universe, "always") == PlacesClient.DEFAULT_MTLS_ENDPOINT - assert PlacesClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == PlacesClient.DEFAULT_MTLS_ENDPOINT - assert PlacesClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert PlacesClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - PlacesClient._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 PlacesClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert PlacesClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert PlacesClient._get_universe_domain(None, None) == PlacesClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - PlacesClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - - -@pytest.mark.parametrize("client_class,transport_name", [ - (PlacesClient, "grpc"), - (PlacesAsyncClient, "grpc_asyncio"), - (PlacesClient, "rest"), -]) -def test_places_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 == ( - 'places.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://places.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.PlacesGrpcTransport, "grpc"), - (transports.PlacesGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.PlacesRestTransport, "rest"), -]) -def test_places_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", [ - (PlacesClient, "grpc"), - (PlacesAsyncClient, "grpc_asyncio"), - (PlacesClient, "rest"), -]) -def test_places_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 == ( - 'places.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://places.googleapis.com' - ) - - -def test_places_client_get_transport_class(): - transport = PlacesClient.get_transport_class() - available_transports = [ - transports.PlacesGrpcTransport, - transports.PlacesRestTransport, - ] - assert transport in available_transports - - transport = PlacesClient.get_transport_class("grpc") - assert transport == transports.PlacesGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (PlacesClient, transports.PlacesGrpcTransport, "grpc"), - (PlacesAsyncClient, transports.PlacesGrpcAsyncIOTransport, "grpc_asyncio"), - (PlacesClient, transports.PlacesRestTransport, "rest"), -]) -@mock.patch.object(PlacesClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PlacesClient)) -@mock.patch.object(PlacesAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PlacesAsyncClient)) -def test_places_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(PlacesClient, '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(PlacesClient, '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", [ - (PlacesClient, transports.PlacesGrpcTransport, "grpc", "true"), - (PlacesAsyncClient, transports.PlacesGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (PlacesClient, transports.PlacesGrpcTransport, "grpc", "false"), - (PlacesAsyncClient, transports.PlacesGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (PlacesClient, transports.PlacesRestTransport, "rest", "true"), - (PlacesClient, transports.PlacesRestTransport, "rest", "false"), -]) -@mock.patch.object(PlacesClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PlacesClient)) -@mock.patch.object(PlacesAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PlacesAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_places_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", [ - PlacesClient, PlacesAsyncClient -]) -@mock.patch.object(PlacesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PlacesClient)) -@mock.patch.object(PlacesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PlacesAsyncClient)) -def test_places_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", [ - PlacesClient, PlacesAsyncClient -]) -@mock.patch.object(PlacesClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PlacesClient)) -@mock.patch.object(PlacesAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PlacesAsyncClient)) -def test_places_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = PlacesClient._DEFAULT_UNIVERSE - default_endpoint = PlacesClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = PlacesClient._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", [ - (PlacesClient, transports.PlacesGrpcTransport, "grpc"), - (PlacesAsyncClient, transports.PlacesGrpcAsyncIOTransport, "grpc_asyncio"), - (PlacesClient, transports.PlacesRestTransport, "rest"), -]) -def test_places_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", [ - (PlacesClient, transports.PlacesGrpcTransport, "grpc", grpc_helpers), - (PlacesAsyncClient, transports.PlacesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (PlacesClient, transports.PlacesRestTransport, "rest", None), -]) -def test_places_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_places_client_client_options_from_dict(): - with mock.patch('google.maps.places_v1.services.places.transports.PlacesGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = PlacesClient( - 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", [ - (PlacesClient, transports.PlacesGrpcTransport, "grpc", grpc_helpers), - (PlacesAsyncClient, transports.PlacesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_places_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( - "places.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( -), - scopes=None, - default_host="places.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - places_service.SearchNearbyRequest, - dict, -]) -def test_search_nearby(request_type, transport: str = 'grpc'): - client = PlacesClient( - 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.search_nearby), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = places_service.SearchNearbyResponse( - ) - response = client.search_nearby(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = places_service.SearchNearbyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, places_service.SearchNearbyResponse) - - -def test_search_nearby_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 = PlacesClient( - 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 = places_service.SearchNearbyRequest( - language_code='language_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.search_nearby), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.search_nearby(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == places_service.SearchNearbyRequest( - language_code='language_code_value', - region_code='region_code_value', - ) - -def test_search_nearby_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = PlacesClient( - 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.search_nearby in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.search_nearby] = mock_rpc - request = {} - client.search_nearby(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.search_nearby(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_search_nearby_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = PlacesAsyncClient( - 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.search_nearby in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.search_nearby] = mock_rpc - - request = {} - await client.search_nearby(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.search_nearby(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_search_nearby_async(transport: str = 'grpc_asyncio', request_type=places_service.SearchNearbyRequest): - client = PlacesAsyncClient( - 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.search_nearby), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(places_service.SearchNearbyResponse( - )) - response = await client.search_nearby(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = places_service.SearchNearbyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, places_service.SearchNearbyResponse) - - -@pytest.mark.asyncio -async def test_search_nearby_async_from_dict(): - await test_search_nearby_async(request_type=dict) - - -@pytest.mark.parametrize("request_type", [ - places_service.SearchTextRequest, - dict, -]) -def test_search_text(request_type, transport: str = 'grpc'): - client = PlacesClient( - 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.search_text), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = places_service.SearchTextResponse( - ) - response = client.search_text(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = places_service.SearchTextRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, places_service.SearchTextResponse) - - -def test_search_text_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 = PlacesClient( - 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 = places_service.SearchTextRequest( - text_query='text_query_value', - language_code='language_code_value', - region_code='region_code_value', - included_type='included_type_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_text), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.search_text(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == places_service.SearchTextRequest( - text_query='text_query_value', - language_code='language_code_value', - region_code='region_code_value', - included_type='included_type_value', - ) - -def test_search_text_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = PlacesClient( - 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.search_text in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.search_text] = mock_rpc - request = {} - client.search_text(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.search_text(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_search_text_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = PlacesAsyncClient( - 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.search_text in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.search_text] = mock_rpc - - request = {} - await client.search_text(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.search_text(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_search_text_async(transport: str = 'grpc_asyncio', request_type=places_service.SearchTextRequest): - client = PlacesAsyncClient( - 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.search_text), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(places_service.SearchTextResponse( - )) - response = await client.search_text(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = places_service.SearchTextRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, places_service.SearchTextResponse) - - -@pytest.mark.asyncio -async def test_search_text_async_from_dict(): - await test_search_text_async(request_type=dict) - - -@pytest.mark.parametrize("request_type", [ - places_service.GetPhotoMediaRequest, - dict, -]) -def test_get_photo_media(request_type, transport: str = 'grpc'): - client = PlacesClient( - 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_photo_media), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = places_service.PhotoMedia( - name='name_value', - photo_uri='photo_uri_value', - ) - response = client.get_photo_media(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = places_service.GetPhotoMediaRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, places_service.PhotoMedia) - assert response.name == 'name_value' - assert response.photo_uri == 'photo_uri_value' - - -def test_get_photo_media_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 = PlacesClient( - 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 = places_service.GetPhotoMediaRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_photo_media), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_photo_media(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == places_service.GetPhotoMediaRequest( - name='name_value', - ) - -def test_get_photo_media_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = PlacesClient( - 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_photo_media in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_photo_media] = mock_rpc - request = {} - client.get_photo_media(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_photo_media(request) - - # Establish that a new wrapper 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_photo_media_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = PlacesAsyncClient( - 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_photo_media in client._client._transport._wrapped_methods - - # 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_photo_media] = mock_rpc - - request = {} - await client.get_photo_media(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_photo_media(request) - - # Establish that a new wrapper 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_photo_media_async(transport: str = 'grpc_asyncio', request_type=places_service.GetPhotoMediaRequest): - client = PlacesAsyncClient( - 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_photo_media), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(places_service.PhotoMedia( - name='name_value', - photo_uri='photo_uri_value', - )) - response = await client.get_photo_media(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = places_service.GetPhotoMediaRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, places_service.PhotoMedia) - assert response.name == 'name_value' - assert response.photo_uri == 'photo_uri_value' - - -@pytest.mark.asyncio -async def test_get_photo_media_async_from_dict(): - await test_get_photo_media_async(request_type=dict) - -def test_get_photo_media_field_headers(): - client = PlacesClient( - 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 = places_service.GetPhotoMediaRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_photo_media), - '__call__') as call: - call.return_value = places_service.PhotoMedia() - client.get_photo_media(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_photo_media_field_headers_async(): - client = PlacesAsyncClient( - 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 = places_service.GetPhotoMediaRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_photo_media), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(places_service.PhotoMedia()) - await client.get_photo_media(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_photo_media_flattened(): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_photo_media), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = places_service.PhotoMedia() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_photo_media( - 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_photo_media_flattened_error(): - client = PlacesClient( - 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_photo_media( - places_service.GetPhotoMediaRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_photo_media_flattened_async(): - client = PlacesAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_photo_media), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = places_service.PhotoMedia() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(places_service.PhotoMedia()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_photo_media( - 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_photo_media_flattened_error_async(): - client = PlacesAsyncClient( - 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_photo_media( - places_service.GetPhotoMediaRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - places_service.GetPlaceRequest, - dict, -]) -def test_get_place(request_type, transport: str = 'grpc'): - client = PlacesClient( - 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_place), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = place.Place( - name='name_value', - id='id_value', - types=['types_value'], - primary_type='primary_type_value', - national_phone_number='national_phone_number_value', - international_phone_number='international_phone_number_value', - formatted_address='formatted_address_value', - short_formatted_address='short_formatted_address_value', - rating=0.645, - google_maps_uri='google_maps_uri_value', - website_uri='website_uri_value', - utc_offset_minutes=1942, - adr_format_address='adr_format_address_value', - business_status=place.Place.BusinessStatus.OPERATIONAL, - price_level=place.PriceLevel.PRICE_LEVEL_FREE, - user_rating_count=1835, - icon_mask_base_uri='icon_mask_base_uri_value', - icon_background_color='icon_background_color_value', - takeout=True, - delivery=True, - dine_in=True, - curbside_pickup=True, - reservable=True, - serves_breakfast=True, - serves_lunch=True, - serves_dinner=True, - serves_beer=True, - serves_wine=True, - serves_brunch=True, - serves_vegetarian_food=True, - outdoor_seating=True, - live_music=True, - menu_for_children=True, - serves_cocktails=True, - serves_dessert=True, - serves_coffee=True, - good_for_children=True, - allows_dogs=True, - restroom=True, - good_for_groups=True, - good_for_watching_sports=True, - pure_service_area_business=True, - ) - response = client.get_place(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = places_service.GetPlaceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, place.Place) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.types == ['types_value'] - assert response.primary_type == 'primary_type_value' - assert response.national_phone_number == 'national_phone_number_value' - assert response.international_phone_number == 'international_phone_number_value' - assert response.formatted_address == 'formatted_address_value' - assert response.short_formatted_address == 'short_formatted_address_value' - assert math.isclose(response.rating, 0.645, rel_tol=1e-6) - assert response.google_maps_uri == 'google_maps_uri_value' - assert response.website_uri == 'website_uri_value' - assert response.utc_offset_minutes == 1942 - assert response.adr_format_address == 'adr_format_address_value' - assert response.business_status == place.Place.BusinessStatus.OPERATIONAL - assert response.price_level == place.PriceLevel.PRICE_LEVEL_FREE - assert response.user_rating_count == 1835 - assert response.icon_mask_base_uri == 'icon_mask_base_uri_value' - assert response.icon_background_color == 'icon_background_color_value' - assert response.takeout is True - assert response.delivery is True - assert response.dine_in is True - assert response.curbside_pickup is True - assert response.reservable is True - assert response.serves_breakfast is True - assert response.serves_lunch is True - assert response.serves_dinner is True - assert response.serves_beer is True - assert response.serves_wine is True - assert response.serves_brunch is True - assert response.serves_vegetarian_food is True - assert response.outdoor_seating is True - assert response.live_music is True - assert response.menu_for_children is True - assert response.serves_cocktails is True - assert response.serves_dessert is True - assert response.serves_coffee is True - assert response.good_for_children is True - assert response.allows_dogs is True - assert response.restroom is True - assert response.good_for_groups is True - assert response.good_for_watching_sports is True - assert response.pure_service_area_business is True - - -def test_get_place_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 = PlacesClient( - 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 = places_service.GetPlaceRequest( - name='name_value', - language_code='language_code_value', - region_code='region_code_value', - session_token='session_token_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_place), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_place(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == places_service.GetPlaceRequest( - name='name_value', - language_code='language_code_value', - region_code='region_code_value', - session_token='session_token_value', - ) - -def test_get_place_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = PlacesClient( - 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_place in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_place] = mock_rpc - request = {} - client.get_place(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_place(request) - - # Establish that a new wrapper 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_place_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = PlacesAsyncClient( - 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_place in client._client._transport._wrapped_methods - - # 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_place] = mock_rpc - - request = {} - await client.get_place(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_place(request) - - # Establish that a new wrapper 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_place_async(transport: str = 'grpc_asyncio', request_type=places_service.GetPlaceRequest): - client = PlacesAsyncClient( - 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_place), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(place.Place( - name='name_value', - id='id_value', - types=['types_value'], - primary_type='primary_type_value', - national_phone_number='national_phone_number_value', - international_phone_number='international_phone_number_value', - formatted_address='formatted_address_value', - short_formatted_address='short_formatted_address_value', - rating=0.645, - google_maps_uri='google_maps_uri_value', - website_uri='website_uri_value', - utc_offset_minutes=1942, - adr_format_address='adr_format_address_value', - business_status=place.Place.BusinessStatus.OPERATIONAL, - price_level=place.PriceLevel.PRICE_LEVEL_FREE, - user_rating_count=1835, - icon_mask_base_uri='icon_mask_base_uri_value', - icon_background_color='icon_background_color_value', - takeout=True, - delivery=True, - dine_in=True, - curbside_pickup=True, - reservable=True, - serves_breakfast=True, - serves_lunch=True, - serves_dinner=True, - serves_beer=True, - serves_wine=True, - serves_brunch=True, - serves_vegetarian_food=True, - outdoor_seating=True, - live_music=True, - menu_for_children=True, - serves_cocktails=True, - serves_dessert=True, - serves_coffee=True, - good_for_children=True, - allows_dogs=True, - restroom=True, - good_for_groups=True, - good_for_watching_sports=True, - pure_service_area_business=True, - )) - response = await client.get_place(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = places_service.GetPlaceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, place.Place) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.types == ['types_value'] - assert response.primary_type == 'primary_type_value' - assert response.national_phone_number == 'national_phone_number_value' - assert response.international_phone_number == 'international_phone_number_value' - assert response.formatted_address == 'formatted_address_value' - assert response.short_formatted_address == 'short_formatted_address_value' - assert math.isclose(response.rating, 0.645, rel_tol=1e-6) - assert response.google_maps_uri == 'google_maps_uri_value' - assert response.website_uri == 'website_uri_value' - assert response.utc_offset_minutes == 1942 - assert response.adr_format_address == 'adr_format_address_value' - assert response.business_status == place.Place.BusinessStatus.OPERATIONAL - assert response.price_level == place.PriceLevel.PRICE_LEVEL_FREE - assert response.user_rating_count == 1835 - assert response.icon_mask_base_uri == 'icon_mask_base_uri_value' - assert response.icon_background_color == 'icon_background_color_value' - assert response.takeout is True - assert response.delivery is True - assert response.dine_in is True - assert response.curbside_pickup is True - assert response.reservable is True - assert response.serves_breakfast is True - assert response.serves_lunch is True - assert response.serves_dinner is True - assert response.serves_beer is True - assert response.serves_wine is True - assert response.serves_brunch is True - assert response.serves_vegetarian_food is True - assert response.outdoor_seating is True - assert response.live_music is True - assert response.menu_for_children is True - assert response.serves_cocktails is True - assert response.serves_dessert is True - assert response.serves_coffee is True - assert response.good_for_children is True - assert response.allows_dogs is True - assert response.restroom is True - assert response.good_for_groups is True - assert response.good_for_watching_sports is True - assert response.pure_service_area_business is True - - -@pytest.mark.asyncio -async def test_get_place_async_from_dict(): - await test_get_place_async(request_type=dict) - -def test_get_place_field_headers(): - client = PlacesClient( - 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 = places_service.GetPlaceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_place), - '__call__') as call: - call.return_value = place.Place() - client.get_place(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_place_field_headers_async(): - client = PlacesAsyncClient( - 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 = places_service.GetPlaceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_place), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(place.Place()) - await client.get_place(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_place_flattened(): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_place), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = place.Place() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_place( - 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_place_flattened_error(): - client = PlacesClient( - 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_place( - places_service.GetPlaceRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_place_flattened_async(): - client = PlacesAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_place), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = place.Place() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(place.Place()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_place( - 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_place_flattened_error_async(): - client = PlacesAsyncClient( - 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_place( - places_service.GetPlaceRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - places_service.AutocompletePlacesRequest, - dict, -]) -def test_autocomplete_places(request_type, transport: str = 'grpc'): - client = PlacesClient( - 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.autocomplete_places), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = places_service.AutocompletePlacesResponse( - ) - response = client.autocomplete_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = places_service.AutocompletePlacesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, places_service.AutocompletePlacesResponse) - - -def test_autocomplete_places_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 = PlacesClient( - 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 = places_service.AutocompletePlacesRequest( - input='input_value', - language_code='language_code_value', - region_code='region_code_value', - session_token='session_token_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.autocomplete_places), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.autocomplete_places(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == places_service.AutocompletePlacesRequest( - input='input_value', - language_code='language_code_value', - region_code='region_code_value', - session_token='session_token_value', - ) - -def test_autocomplete_places_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = PlacesClient( - 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.autocomplete_places in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.autocomplete_places] = mock_rpc - request = {} - client.autocomplete_places(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.autocomplete_places(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_autocomplete_places_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = PlacesAsyncClient( - 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.autocomplete_places in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.autocomplete_places] = mock_rpc - - request = {} - await client.autocomplete_places(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.autocomplete_places(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_autocomplete_places_async(transport: str = 'grpc_asyncio', request_type=places_service.AutocompletePlacesRequest): - client = PlacesAsyncClient( - 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.autocomplete_places), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(places_service.AutocompletePlacesResponse( - )) - response = await client.autocomplete_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = places_service.AutocompletePlacesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, places_service.AutocompletePlacesResponse) - - -@pytest.mark.asyncio -async def test_autocomplete_places_async_from_dict(): - await test_autocomplete_places_async(request_type=dict) - - -def test_search_nearby_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 = PlacesClient( - 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.search_nearby in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.search_nearby] = mock_rpc - - request = {} - client.search_nearby(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.search_nearby(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_search_nearby_rest_required_fields(request_type=places_service.SearchNearbyRequest): - transport_class = transports.PlacesRestTransport - - 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()).search_nearby._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()).search_nearby._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = places_service.SearchNearbyResponse() - # 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 = places_service.SearchNearbyResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.search_nearby(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_search_nearby_rest_unset_required_fields(): - transport = transports.PlacesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.search_nearby._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("locationRestriction", ))) - - -def test_search_text_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 = PlacesClient( - 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.search_text in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.search_text] = mock_rpc - - request = {} - client.search_text(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.search_text(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_search_text_rest_required_fields(request_type=places_service.SearchTextRequest): - transport_class = transports.PlacesRestTransport - - request_init = {} - request_init["text_query"] = "" - request = 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()).search_text._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["textQuery"] = 'text_query_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).search_text._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "textQuery" in jsonified_request - assert jsonified_request["textQuery"] == 'text_query_value' - - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = places_service.SearchTextResponse() - # 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 = places_service.SearchTextResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.search_text(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_search_text_rest_unset_required_fields(): - transport = transports.PlacesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.search_text._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("textQuery", ))) - - -def test_get_photo_media_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 = PlacesClient( - 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_photo_media in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_photo_media] = mock_rpc - - request = {} - client.get_photo_media(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_photo_media(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_photo_media_rest_required_fields(request_type=places_service.GetPhotoMediaRequest): - transport_class = transports.PlacesRestTransport - - 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_photo_media._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_photo_media._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("max_height_px", "max_width_px", "skip_http_redirect", )) - 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 = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = places_service.PhotoMedia() - # 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 = places_service.PhotoMedia.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_photo_media(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_photo_media_rest_unset_required_fields(): - transport = transports.PlacesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_photo_media._get_unset_required_fields({}) - assert set(unset_fields) == (set(("maxHeightPx", "maxWidthPx", "skipHttpRedirect", )) & set(("name", ))) - - -def test_get_photo_media_rest_flattened(): - client = PlacesClient( - 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 = places_service.PhotoMedia() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'places/sample1/photos/sample2/media'} - - # 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 = places_service.PhotoMedia.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_photo_media(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=places/*/photos/*/media}" % client.transport._host, args[1]) - - -def test_get_photo_media_rest_flattened_error(transport: str = 'rest'): - client = PlacesClient( - 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_photo_media( - places_service.GetPhotoMediaRequest(), - name='name_value', - ) - - -def test_get_place_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 = PlacesClient( - 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_place in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_place] = mock_rpc - - request = {} - client.get_place(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_place(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_place_rest_required_fields(request_type=places_service.GetPlaceRequest): - transport_class = transports.PlacesRestTransport - - 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_place._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_place._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", "region_code", "session_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = place.Place() - # 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 = place.Place.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_place(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_place_rest_unset_required_fields(): - transport = transports.PlacesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_place._get_unset_required_fields({}) - assert set(unset_fields) == (set(("languageCode", "regionCode", "sessionToken", )) & set(("name", ))) - - -def test_get_place_rest_flattened(): - client = PlacesClient( - 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 = place.Place() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'places/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 = place.Place.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_place(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=places/*}" % client.transport._host, args[1]) - - -def test_get_place_rest_flattened_error(transport: str = 'rest'): - client = PlacesClient( - 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_place( - places_service.GetPlaceRequest(), - name='name_value', - ) - - -def test_autocomplete_places_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 = PlacesClient( - 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.autocomplete_places in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.autocomplete_places] = mock_rpc - - request = {} - client.autocomplete_places(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.autocomplete_places(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_autocomplete_places_rest_required_fields(request_type=places_service.AutocompletePlacesRequest): - transport_class = transports.PlacesRestTransport - - request_init = {} - request_init["input"] = "" - request = 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()).autocomplete_places._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["input"] = 'input_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).autocomplete_places._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "input" in jsonified_request - assert jsonified_request["input"] == 'input_value' - - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = places_service.AutocompletePlacesResponse() - # 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 = places_service.AutocompletePlacesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.autocomplete_places(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_autocomplete_places_rest_unset_required_fields(): - transport = transports.PlacesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.autocomplete_places._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("input", ))) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.PlacesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.PlacesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PlacesClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.PlacesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = PlacesClient( - 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 = PlacesClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.PlacesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PlacesClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.PlacesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = PlacesClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.PlacesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.PlacesGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.PlacesGrpcTransport, - transports.PlacesGrpcAsyncIOTransport, - transports.PlacesRestTransport, -]) -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 = PlacesClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = PlacesClient( - 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_search_nearby_empty_call_grpc(): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.search_nearby), - '__call__') as call: - call.return_value = places_service.SearchNearbyResponse() - client.search_nearby(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = places_service.SearchNearbyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_search_text_empty_call_grpc(): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.search_text), - '__call__') as call: - call.return_value = places_service.SearchTextResponse() - client.search_text(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = places_service.SearchTextRequest() - - assert args[0] == request_msg - - -# This 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_photo_media_empty_call_grpc(): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_photo_media), - '__call__') as call: - call.return_value = places_service.PhotoMedia() - client.get_photo_media(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = places_service.GetPhotoMediaRequest() - - assert args[0] == request_msg - - -# This 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_place_empty_call_grpc(): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_place), - '__call__') as call: - call.return_value = place.Place() - client.get_place(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = places_service.GetPlaceRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_autocomplete_places_empty_call_grpc(): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.autocomplete_places), - '__call__') as call: - call.return_value = places_service.AutocompletePlacesResponse() - client.autocomplete_places(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = places_service.AutocompletePlacesRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = PlacesAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = PlacesAsyncClient( - 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_search_nearby_empty_call_grpc_asyncio(): - client = PlacesAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.search_nearby), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(places_service.SearchNearbyResponse( - )) - await client.search_nearby(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = places_service.SearchNearbyRequest() - - assert args[0] == request_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_search_text_empty_call_grpc_asyncio(): - client = PlacesAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.search_text), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(places_service.SearchTextResponse( - )) - await client.search_text(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = places_service.SearchTextRequest() - - assert args[0] == request_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_photo_media_empty_call_grpc_asyncio(): - client = PlacesAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_photo_media), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(places_service.PhotoMedia( - name='name_value', - photo_uri='photo_uri_value', - )) - await client.get_photo_media(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = places_service.GetPhotoMediaRequest() - - assert args[0] == request_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_place_empty_call_grpc_asyncio(): - client = PlacesAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_place), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(place.Place( - name='name_value', - id='id_value', - types=['types_value'], - primary_type='primary_type_value', - national_phone_number='national_phone_number_value', - international_phone_number='international_phone_number_value', - formatted_address='formatted_address_value', - short_formatted_address='short_formatted_address_value', - rating=0.645, - google_maps_uri='google_maps_uri_value', - website_uri='website_uri_value', - utc_offset_minutes=1942, - adr_format_address='adr_format_address_value', - business_status=place.Place.BusinessStatus.OPERATIONAL, - price_level=place.PriceLevel.PRICE_LEVEL_FREE, - user_rating_count=1835, - icon_mask_base_uri='icon_mask_base_uri_value', - icon_background_color='icon_background_color_value', - takeout=True, - delivery=True, - dine_in=True, - curbside_pickup=True, - reservable=True, - serves_breakfast=True, - serves_lunch=True, - serves_dinner=True, - serves_beer=True, - serves_wine=True, - serves_brunch=True, - serves_vegetarian_food=True, - outdoor_seating=True, - live_music=True, - menu_for_children=True, - serves_cocktails=True, - serves_dessert=True, - serves_coffee=True, - good_for_children=True, - allows_dogs=True, - restroom=True, - good_for_groups=True, - good_for_watching_sports=True, - pure_service_area_business=True, - )) - await client.get_place(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = places_service.GetPlaceRequest() - - assert args[0] == request_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_autocomplete_places_empty_call_grpc_asyncio(): - client = PlacesAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.autocomplete_places), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(places_service.AutocompletePlacesResponse( - )) - await client.autocomplete_places(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = places_service.AutocompletePlacesRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = PlacesClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_search_nearby_rest_bad_request(request_type=places_service.SearchNearbyRequest): - client = PlacesClient( - 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.search_nearby(request) - - -@pytest.mark.parametrize("request_type", [ - places_service.SearchNearbyRequest, - dict, -]) -def test_search_nearby_rest_call_success(request_type): - client = PlacesClient( - 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 = places_service.SearchNearbyResponse( - ) - - # 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 = places_service.SearchNearbyResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.search_nearby(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, places_service.SearchNearbyResponse) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_search_nearby_rest_interceptors(null_interceptor): - transport = transports.PlacesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.PlacesRestInterceptor(), - ) - client = PlacesClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.PlacesRestInterceptor, "post_search_nearby") as post, \ - mock.patch.object(transports.PlacesRestInterceptor, "pre_search_nearby") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = places_service.SearchNearbyRequest.pb(places_service.SearchNearbyRequest()) - 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 = places_service.SearchNearbyResponse.to_json(places_service.SearchNearbyResponse()) - req.return_value.content = return_value - - request = places_service.SearchNearbyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = places_service.SearchNearbyResponse() - - client.search_nearby(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_search_text_rest_bad_request(request_type=places_service.SearchTextRequest): - client = PlacesClient( - 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.search_text(request) - - -@pytest.mark.parametrize("request_type", [ - places_service.SearchTextRequest, - dict, -]) -def test_search_text_rest_call_success(request_type): - client = PlacesClient( - 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 = places_service.SearchTextResponse( - ) - - # 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 = places_service.SearchTextResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.search_text(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, places_service.SearchTextResponse) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_search_text_rest_interceptors(null_interceptor): - transport = transports.PlacesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.PlacesRestInterceptor(), - ) - client = PlacesClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.PlacesRestInterceptor, "post_search_text") as post, \ - mock.patch.object(transports.PlacesRestInterceptor, "pre_search_text") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = places_service.SearchTextRequest.pb(places_service.SearchTextRequest()) - 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 = places_service.SearchTextResponse.to_json(places_service.SearchTextResponse()) - req.return_value.content = return_value - - request = places_service.SearchTextRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = places_service.SearchTextResponse() - - client.search_text(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_photo_media_rest_bad_request(request_type=places_service.GetPhotoMediaRequest): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'places/sample1/photos/sample2/media'} - request = request_type(**request_init) - - # Mock the 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_photo_media(request) - - -@pytest.mark.parametrize("request_type", [ - places_service.GetPhotoMediaRequest, - dict, -]) -def test_get_photo_media_rest_call_success(request_type): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'places/sample1/photos/sample2/media'} - request = request_type(**request_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 = places_service.PhotoMedia( - name='name_value', - photo_uri='photo_uri_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 = places_service.PhotoMedia.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_photo_media(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, places_service.PhotoMedia) - assert response.name == 'name_value' - assert response.photo_uri == 'photo_uri_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_photo_media_rest_interceptors(null_interceptor): - transport = transports.PlacesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.PlacesRestInterceptor(), - ) - client = PlacesClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.PlacesRestInterceptor, "post_get_photo_media") as post, \ - mock.patch.object(transports.PlacesRestInterceptor, "pre_get_photo_media") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = places_service.GetPhotoMediaRequest.pb(places_service.GetPhotoMediaRequest()) - 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 = places_service.PhotoMedia.to_json(places_service.PhotoMedia()) - req.return_value.content = return_value - - request = places_service.GetPhotoMediaRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = places_service.PhotoMedia() - - client.get_photo_media(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_place_rest_bad_request(request_type=places_service.GetPlaceRequest): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'places/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_place(request) - - -@pytest.mark.parametrize("request_type", [ - places_service.GetPlaceRequest, - dict, -]) -def test_get_place_rest_call_success(request_type): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'places/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 = place.Place( - name='name_value', - id='id_value', - types=['types_value'], - primary_type='primary_type_value', - national_phone_number='national_phone_number_value', - international_phone_number='international_phone_number_value', - formatted_address='formatted_address_value', - short_formatted_address='short_formatted_address_value', - rating=0.645, - google_maps_uri='google_maps_uri_value', - website_uri='website_uri_value', - utc_offset_minutes=1942, - adr_format_address='adr_format_address_value', - business_status=place.Place.BusinessStatus.OPERATIONAL, - price_level=place.PriceLevel.PRICE_LEVEL_FREE, - user_rating_count=1835, - icon_mask_base_uri='icon_mask_base_uri_value', - icon_background_color='icon_background_color_value', - takeout=True, - delivery=True, - dine_in=True, - curbside_pickup=True, - reservable=True, - serves_breakfast=True, - serves_lunch=True, - serves_dinner=True, - serves_beer=True, - serves_wine=True, - serves_brunch=True, - serves_vegetarian_food=True, - outdoor_seating=True, - live_music=True, - menu_for_children=True, - serves_cocktails=True, - serves_dessert=True, - serves_coffee=True, - good_for_children=True, - allows_dogs=True, - restroom=True, - good_for_groups=True, - good_for_watching_sports=True, - pure_service_area_business=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 = place.Place.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_place(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, place.Place) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.types == ['types_value'] - assert response.primary_type == 'primary_type_value' - assert response.national_phone_number == 'national_phone_number_value' - assert response.international_phone_number == 'international_phone_number_value' - assert response.formatted_address == 'formatted_address_value' - assert response.short_formatted_address == 'short_formatted_address_value' - assert math.isclose(response.rating, 0.645, rel_tol=1e-6) - assert response.google_maps_uri == 'google_maps_uri_value' - assert response.website_uri == 'website_uri_value' - assert response.utc_offset_minutes == 1942 - assert response.adr_format_address == 'adr_format_address_value' - assert response.business_status == place.Place.BusinessStatus.OPERATIONAL - assert response.price_level == place.PriceLevel.PRICE_LEVEL_FREE - assert response.user_rating_count == 1835 - assert response.icon_mask_base_uri == 'icon_mask_base_uri_value' - assert response.icon_background_color == 'icon_background_color_value' - assert response.takeout is True - assert response.delivery is True - assert response.dine_in is True - assert response.curbside_pickup is True - assert response.reservable is True - assert response.serves_breakfast is True - assert response.serves_lunch is True - assert response.serves_dinner is True - assert response.serves_beer is True - assert response.serves_wine is True - assert response.serves_brunch is True - assert response.serves_vegetarian_food is True - assert response.outdoor_seating is True - assert response.live_music is True - assert response.menu_for_children is True - assert response.serves_cocktails is True - assert response.serves_dessert is True - assert response.serves_coffee is True - assert response.good_for_children is True - assert response.allows_dogs is True - assert response.restroom is True - assert response.good_for_groups is True - assert response.good_for_watching_sports is True - assert response.pure_service_area_business is True - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_place_rest_interceptors(null_interceptor): - transport = transports.PlacesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.PlacesRestInterceptor(), - ) - client = PlacesClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.PlacesRestInterceptor, "post_get_place") as post, \ - mock.patch.object(transports.PlacesRestInterceptor, "pre_get_place") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = places_service.GetPlaceRequest.pb(places_service.GetPlaceRequest()) - 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 = place.Place.to_json(place.Place()) - req.return_value.content = return_value - - request = places_service.GetPlaceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = place.Place() - - client.get_place(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_autocomplete_places_rest_bad_request(request_type=places_service.AutocompletePlacesRequest): - client = PlacesClient( - 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.autocomplete_places(request) - - -@pytest.mark.parametrize("request_type", [ - places_service.AutocompletePlacesRequest, - dict, -]) -def test_autocomplete_places_rest_call_success(request_type): - client = PlacesClient( - 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 = places_service.AutocompletePlacesResponse( - ) - - # 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 = places_service.AutocompletePlacesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.autocomplete_places(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, places_service.AutocompletePlacesResponse) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_autocomplete_places_rest_interceptors(null_interceptor): - transport = transports.PlacesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.PlacesRestInterceptor(), - ) - client = PlacesClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.PlacesRestInterceptor, "post_autocomplete_places") as post, \ - mock.patch.object(transports.PlacesRestInterceptor, "pre_autocomplete_places") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = places_service.AutocompletePlacesRequest.pb(places_service.AutocompletePlacesRequest()) - 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 = places_service.AutocompletePlacesResponse.to_json(places_service.AutocompletePlacesResponse()) - req.return_value.content = return_value - - request = places_service.AutocompletePlacesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = places_service.AutocompletePlacesResponse() - - client.autocomplete_places(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - -def test_initialize_client_w_rest(): - client = PlacesClient( - 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_search_nearby_empty_call_rest(): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.search_nearby), - '__call__') as call: - client.search_nearby(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = places_service.SearchNearbyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_search_text_empty_call_rest(): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.search_text), - '__call__') as call: - client.search_text(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = places_service.SearchTextRequest() - - assert args[0] == request_msg - - -# This 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_photo_media_empty_call_rest(): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_photo_media), - '__call__') as call: - client.get_photo_media(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = places_service.GetPhotoMediaRequest() - - assert args[0] == request_msg - - -# This 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_place_empty_call_rest(): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_place), - '__call__') as call: - client.get_place(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = places_service.GetPlaceRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_autocomplete_places_empty_call_rest(): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.autocomplete_places), - '__call__') as call: - client.autocomplete_places(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = places_service.AutocompletePlacesRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.PlacesGrpcTransport, - ) - -def test_places_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.PlacesTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_places_base_transport(): - # Instantiate the base transport. - with mock.patch('google.maps.places_v1.services.places.transports.PlacesTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.PlacesTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'search_nearby', - 'search_text', - 'get_photo_media', - 'get_place', - 'autocomplete_places', - ) - 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_places_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.maps.places_v1.services.places.transports.PlacesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PlacesTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( -), - quota_project_id="octopus", - ) - - -def test_places_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.maps.places_v1.services.places.transports.PlacesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PlacesTransport() - adc.assert_called_once() - - -def test_places_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) - PlacesClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.PlacesGrpcTransport, - transports.PlacesGrpcAsyncIOTransport, - ], -) -def test_places_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=(), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.PlacesGrpcTransport, - transports.PlacesGrpcAsyncIOTransport, - transports.PlacesRestTransport, - ], -) -def test_places_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.PlacesGrpcTransport, grpc_helpers), - (transports.PlacesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_places_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( - "places.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( -), - scopes=["1", "2"], - default_host="places.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.PlacesGrpcTransport, transports.PlacesGrpcAsyncIOTransport]) -def test_places_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_places_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.PlacesRestTransport ( - 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_places_host_no_port(transport_name): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='places.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'places.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://places.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_places_host_with_port(transport_name): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='places.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'places.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://places.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_places_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = PlacesClient( - credentials=creds1, - transport=transport_name, - ) - client2 = PlacesClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.search_nearby._session - session2 = client2.transport.search_nearby._session - assert session1 != session2 - session1 = client1.transport.search_text._session - session2 = client2.transport.search_text._session - assert session1 != session2 - session1 = client1.transport.get_photo_media._session - session2 = client2.transport.get_photo_media._session - assert session1 != session2 - session1 = client1.transport.get_place._session - session2 = client2.transport.get_place._session - assert session1 != session2 - session1 = client1.transport.autocomplete_places._session - session2 = client2.transport.autocomplete_places._session - assert session1 != session2 -def test_places_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.PlacesGrpcTransport( - 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_places_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.PlacesGrpcAsyncIOTransport( - 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.PlacesGrpcTransport, transports.PlacesGrpcAsyncIOTransport]) -def test_places_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.PlacesGrpcTransport, transports.PlacesGrpcAsyncIOTransport]) -def test_places_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_photo_path(): - place = "squid" - photo = "clam" - expected = "places/{place}/photos/{photo}".format(place=place, photo=photo, ) - actual = PlacesClient.photo_path(place, photo) - assert expected == actual - - -def test_parse_photo_path(): - expected = { - "place": "whelk", - "photo": "octopus", - } - path = PlacesClient.photo_path(**expected) - - # Check that the path construction is reversible. - actual = PlacesClient.parse_photo_path(path) - assert expected == actual - -def test_photo_media_path(): - place_id = "oyster" - photo_reference = "nudibranch" - expected = "places/{place_id}/photos/{photo_reference}/media".format(place_id=place_id, photo_reference=photo_reference, ) - actual = PlacesClient.photo_media_path(place_id, photo_reference) - assert expected == actual - - -def test_parse_photo_media_path(): - expected = { - "place_id": "cuttlefish", - "photo_reference": "mussel", - } - path = PlacesClient.photo_media_path(**expected) - - # Check that the path construction is reversible. - actual = PlacesClient.parse_photo_media_path(path) - assert expected == actual - -def test_place_path(): - place_id = "winkle" - expected = "places/{place_id}".format(place_id=place_id, ) - actual = PlacesClient.place_path(place_id) - assert expected == actual - - -def test_parse_place_path(): - expected = { - "place_id": "nautilus", - } - path = PlacesClient.place_path(**expected) - - # Check that the path construction is reversible. - actual = PlacesClient.parse_place_path(path) - assert expected == actual - -def test_review_path(): - place = "scallop" - review = "abalone" - expected = "places/{place}/reviews/{review}".format(place=place, review=review, ) - actual = PlacesClient.review_path(place, review) - assert expected == actual - - -def test_parse_review_path(): - expected = { - "place": "squid", - "review": "clam", - } - path = PlacesClient.review_path(**expected) - - # Check that the path construction is reversible. - actual = PlacesClient.parse_review_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = PlacesClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = PlacesClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = PlacesClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = PlacesClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = PlacesClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = PlacesClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = PlacesClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = PlacesClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = PlacesClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = PlacesClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = PlacesClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = PlacesClient.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 = PlacesClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = PlacesClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = PlacesClient.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.PlacesTransport, '_prep_wrapped_messages') as prep: - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.PlacesTransport, '_prep_wrapped_messages') as prep: - transport_class = PlacesClient.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 = PlacesClient( - 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 = PlacesAsyncClient( - 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 = PlacesClient( - 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 = PlacesClient( - 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", [ - (PlacesClient, transports.PlacesGrpcTransport), - (PlacesAsyncClient, transports.PlacesGrpcAsyncIOTransport), -]) -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-maps-routeoptimization/v1/.coveragerc b/owl-bot-staging/google-maps-routeoptimization/v1/.coveragerc deleted file mode 100644 index aa5ba4d9b1f4..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/maps/routeoptimization/__init__.py - google/maps/routeoptimization/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-maps-routeoptimization/v1/.flake8 b/owl-bot-staging/google-maps-routeoptimization/v1/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/MANIFEST.in b/owl-bot-staging/google-maps-routeoptimization/v1/MANIFEST.in deleted file mode 100644 index f7956876a038..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/maps/routeoptimization *.py -recursive-include google/maps/routeoptimization_v1 *.py diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/README.rst b/owl-bot-staging/google-maps-routeoptimization/v1/README.rst deleted file mode 100644 index 5873f7a73b0e..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Maps Routeoptimization 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 Maps Routeoptimization 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 diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/docs/_static/custom.css b/owl-bot-staging/google-maps-routeoptimization/v1/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/docs/_static/custom.css +++ /dev/null @@ -1,3 +0,0 @@ -dl.field-list > dt { - min-width: 100px -} diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/docs/conf.py b/owl-bot-staging/google-maps-routeoptimization/v1/docs/conf.py deleted file mode 100644 index 0e46cb236e24..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-maps-routeoptimization 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("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# 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.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -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-maps-routeoptimization" -copyright = u"2023, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# 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 = 'en' - -# 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"] - -# 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 Maps Client Libraries for Python", - "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-maps-routeoptimization-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-maps-routeoptimization.tex", - u"google-maps-routeoptimization 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-maps-routeoptimization", - u"Google Maps Routeoptimization 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-maps-routeoptimization", - u"google-maps-routeoptimization Documentation", - author, - "google-maps-routeoptimization", - "GAPIC library for Google Maps Routeoptimization API", - "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": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", 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-maps-routeoptimization/v1/docs/index.rst b/owl-bot-staging/google-maps-routeoptimization/v1/docs/index.rst deleted file mode 100644 index 382cf6284865..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - routeoptimization_v1/services_ - routeoptimization_v1/types_ diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/docs/routeoptimization_v1/route_optimization.rst b/owl-bot-staging/google-maps-routeoptimization/v1/docs/routeoptimization_v1/route_optimization.rst deleted file mode 100644 index 17445dae6122..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/docs/routeoptimization_v1/route_optimization.rst +++ /dev/null @@ -1,6 +0,0 @@ -RouteOptimization ------------------------------------ - -.. automodule:: google.maps.routeoptimization_v1.services.route_optimization - :members: - :inherited-members: diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/docs/routeoptimization_v1/services_.rst b/owl-bot-staging/google-maps-routeoptimization/v1/docs/routeoptimization_v1/services_.rst deleted file mode 100644 index 818250f8aa4b..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/docs/routeoptimization_v1/services_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Maps Routeoptimization v1 API -================================================= -.. toctree:: - :maxdepth: 2 - - route_optimization diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/docs/routeoptimization_v1/types_.rst b/owl-bot-staging/google-maps-routeoptimization/v1/docs/routeoptimization_v1/types_.rst deleted file mode 100644 index 44fe4e6164f4..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/docs/routeoptimization_v1/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Maps Routeoptimization v1 API -============================================== - -.. automodule:: google.maps.routeoptimization_v1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization/__init__.py b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization/__init__.py deleted file mode 100644 index 589f845e0fb1..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization/__init__.py +++ /dev/null @@ -1,81 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.routeoptimization import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.maps.routeoptimization_v1.services.route_optimization.client import RouteOptimizationClient -from google.maps.routeoptimization_v1.services.route_optimization.async_client import RouteOptimizationAsyncClient - -from google.maps.routeoptimization_v1.types.route_optimization_service import AggregatedMetrics -from google.maps.routeoptimization_v1.types.route_optimization_service import BatchOptimizeToursMetadata -from google.maps.routeoptimization_v1.types.route_optimization_service import BatchOptimizeToursRequest -from google.maps.routeoptimization_v1.types.route_optimization_service import BatchOptimizeToursResponse -from google.maps.routeoptimization_v1.types.route_optimization_service import BreakRule -from google.maps.routeoptimization_v1.types.route_optimization_service import DistanceLimit -from google.maps.routeoptimization_v1.types.route_optimization_service import GcsDestination -from google.maps.routeoptimization_v1.types.route_optimization_service import GcsSource -from google.maps.routeoptimization_v1.types.route_optimization_service import InjectedSolutionConstraint -from google.maps.routeoptimization_v1.types.route_optimization_service import InputConfig -from google.maps.routeoptimization_v1.types.route_optimization_service import Location -from google.maps.routeoptimization_v1.types.route_optimization_service import OptimizeToursRequest -from google.maps.routeoptimization_v1.types.route_optimization_service import OptimizeToursResponse -from google.maps.routeoptimization_v1.types.route_optimization_service import OptimizeToursValidationError -from google.maps.routeoptimization_v1.types.route_optimization_service import OutputConfig -from google.maps.routeoptimization_v1.types.route_optimization_service import RouteModifiers -from google.maps.routeoptimization_v1.types.route_optimization_service import Shipment -from google.maps.routeoptimization_v1.types.route_optimization_service import ShipmentModel -from google.maps.routeoptimization_v1.types.route_optimization_service import ShipmentRoute -from google.maps.routeoptimization_v1.types.route_optimization_service import ShipmentTypeIncompatibility -from google.maps.routeoptimization_v1.types.route_optimization_service import ShipmentTypeRequirement -from google.maps.routeoptimization_v1.types.route_optimization_service import SkippedShipment -from google.maps.routeoptimization_v1.types.route_optimization_service import TimeWindow -from google.maps.routeoptimization_v1.types.route_optimization_service import TransitionAttributes -from google.maps.routeoptimization_v1.types.route_optimization_service import Vehicle -from google.maps.routeoptimization_v1.types.route_optimization_service import Waypoint -from google.maps.routeoptimization_v1.types.route_optimization_service import DataFormat - -__all__ = ('RouteOptimizationClient', - 'RouteOptimizationAsyncClient', - 'AggregatedMetrics', - 'BatchOptimizeToursMetadata', - 'BatchOptimizeToursRequest', - 'BatchOptimizeToursResponse', - 'BreakRule', - 'DistanceLimit', - 'GcsDestination', - 'GcsSource', - 'InjectedSolutionConstraint', - 'InputConfig', - 'Location', - 'OptimizeToursRequest', - 'OptimizeToursResponse', - 'OptimizeToursValidationError', - 'OutputConfig', - 'RouteModifiers', - 'Shipment', - 'ShipmentModel', - 'ShipmentRoute', - 'ShipmentTypeIncompatibility', - 'ShipmentTypeRequirement', - 'SkippedShipment', - 'TimeWindow', - 'TransitionAttributes', - 'Vehicle', - 'Waypoint', - 'DataFormat', -) diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization/gapic_version.py b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-maps-routeoptimization/v1/google/maps/routeoptimization/py.typed b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization/py.typed deleted file mode 100644 index 9471c714bbf3..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-maps-routeoptimization package uses inline types. diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/__init__.py b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/__init__.py deleted file mode 100644 index 0ab14fee353e..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/__init__.py +++ /dev/null @@ -1,82 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.routeoptimization_v1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.route_optimization import RouteOptimizationClient -from .services.route_optimization import RouteOptimizationAsyncClient - -from .types.route_optimization_service import AggregatedMetrics -from .types.route_optimization_service import BatchOptimizeToursMetadata -from .types.route_optimization_service import BatchOptimizeToursRequest -from .types.route_optimization_service import BatchOptimizeToursResponse -from .types.route_optimization_service import BreakRule -from .types.route_optimization_service import DistanceLimit -from .types.route_optimization_service import GcsDestination -from .types.route_optimization_service import GcsSource -from .types.route_optimization_service import InjectedSolutionConstraint -from .types.route_optimization_service import InputConfig -from .types.route_optimization_service import Location -from .types.route_optimization_service import OptimizeToursRequest -from .types.route_optimization_service import OptimizeToursResponse -from .types.route_optimization_service import OptimizeToursValidationError -from .types.route_optimization_service import OutputConfig -from .types.route_optimization_service import RouteModifiers -from .types.route_optimization_service import Shipment -from .types.route_optimization_service import ShipmentModel -from .types.route_optimization_service import ShipmentRoute -from .types.route_optimization_service import ShipmentTypeIncompatibility -from .types.route_optimization_service import ShipmentTypeRequirement -from .types.route_optimization_service import SkippedShipment -from .types.route_optimization_service import TimeWindow -from .types.route_optimization_service import TransitionAttributes -from .types.route_optimization_service import Vehicle -from .types.route_optimization_service import Waypoint -from .types.route_optimization_service import DataFormat - -__all__ = ( - 'RouteOptimizationAsyncClient', -'AggregatedMetrics', -'BatchOptimizeToursMetadata', -'BatchOptimizeToursRequest', -'BatchOptimizeToursResponse', -'BreakRule', -'DataFormat', -'DistanceLimit', -'GcsDestination', -'GcsSource', -'InjectedSolutionConstraint', -'InputConfig', -'Location', -'OptimizeToursRequest', -'OptimizeToursResponse', -'OptimizeToursValidationError', -'OutputConfig', -'RouteModifiers', -'RouteOptimizationClient', -'Shipment', -'ShipmentModel', -'ShipmentRoute', -'ShipmentTypeIncompatibility', -'ShipmentTypeRequirement', -'SkippedShipment', -'TimeWindow', -'TransitionAttributes', -'Vehicle', -'Waypoint', -) diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/gapic_metadata.json b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/gapic_metadata.json deleted file mode 100644 index 386551edc86c..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/gapic_metadata.json +++ /dev/null @@ -1,58 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.maps.routeoptimization_v1", - "protoPackage": "google.maps.routeoptimization.v1", - "schema": "1.0", - "services": { - "RouteOptimization": { - "clients": { - "grpc": { - "libraryClient": "RouteOptimizationClient", - "rpcs": { - "BatchOptimizeTours": { - "methods": [ - "batch_optimize_tours" - ] - }, - "OptimizeTours": { - "methods": [ - "optimize_tours" - ] - } - } - }, - "grpc-async": { - "libraryClient": "RouteOptimizationAsyncClient", - "rpcs": { - "BatchOptimizeTours": { - "methods": [ - "batch_optimize_tours" - ] - }, - "OptimizeTours": { - "methods": [ - "optimize_tours" - ] - } - } - }, - "rest": { - "libraryClient": "RouteOptimizationClient", - "rpcs": { - "BatchOptimizeTours": { - "methods": [ - "batch_optimize_tours" - ] - }, - "OptimizeTours": { - "methods": [ - "optimize_tours" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/gapic_version.py b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-maps-routeoptimization/v1/google/maps/routeoptimization_v1/py.typed b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/py.typed deleted file mode 100644 index 9471c714bbf3..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-maps-routeoptimization package uses inline types. diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/__init__.py b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/__init__.py b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/__init__.py deleted file mode 100644 index 6f2dd114cb2d..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 RouteOptimizationClient -from .async_client import RouteOptimizationAsyncClient - -__all__ = ( - 'RouteOptimizationClient', - 'RouteOptimizationAsyncClient', -) diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/async_client.py b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/async_client.py deleted file mode 100644 index ef9c48e09537..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/async_client.py +++ /dev/null @@ -1,576 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.routeoptimization_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 - - -try: - OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.maps.routeoptimization_v1.types import route_optimization_service -from .transports.base import RouteOptimizationTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import RouteOptimizationGrpcAsyncIOTransport -from .client import RouteOptimizationClient - -try: - from google.api_core import client_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 RouteOptimizationAsyncClient: - """A service for optimizing vehicle tours. - - Validity of certain types of fields: - - - ``google.protobuf.Timestamp`` - - - Times are in Unix time: seconds since - 1970-01-01T00:00:00+00:00. - - seconds must be in [0, 253402300799], i.e. in - [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. - - nanos must be unset or set to 0. - - - ``google.protobuf.Duration`` - - - seconds must be in [0, 253402300799], i.e. in - [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. - - nanos must be unset or set to 0. - - - ``google.type.LatLng`` - - - latitude must be in [-90.0, 90.0]. - - longitude must be in [-180.0, 180.0]. - - at least one of latitude and longitude must be non-zero. - """ - - _client: RouteOptimizationClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = RouteOptimizationClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = RouteOptimizationClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = RouteOptimizationClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = RouteOptimizationClient._DEFAULT_UNIVERSE - - common_billing_account_path = staticmethod(RouteOptimizationClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(RouteOptimizationClient.parse_common_billing_account_path) - common_folder_path = staticmethod(RouteOptimizationClient.common_folder_path) - parse_common_folder_path = staticmethod(RouteOptimizationClient.parse_common_folder_path) - common_organization_path = staticmethod(RouteOptimizationClient.common_organization_path) - parse_common_organization_path = staticmethod(RouteOptimizationClient.parse_common_organization_path) - common_project_path = staticmethod(RouteOptimizationClient.common_project_path) - parse_common_project_path = staticmethod(RouteOptimizationClient.parse_common_project_path) - common_location_path = staticmethod(RouteOptimizationClient.common_location_path) - parse_common_location_path = staticmethod(RouteOptimizationClient.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: - RouteOptimizationAsyncClient: The constructed client. - """ - return RouteOptimizationClient.from_service_account_info.__func__(RouteOptimizationAsyncClient, 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: - RouteOptimizationAsyncClient: The constructed client. - """ - return RouteOptimizationClient.from_service_account_file.__func__(RouteOptimizationAsyncClient, 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 RouteOptimizationClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> RouteOptimizationTransport: - """Returns the transport used by the client instance. - - Returns: - RouteOptimizationTransport: 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 = RouteOptimizationClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, RouteOptimizationTransport, Callable[..., RouteOptimizationTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the route optimization 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,RouteOptimizationTransport,Callable[..., RouteOptimizationTransport]]]): - 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 RouteOptimizationTransport 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 = RouteOptimizationClient( - 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.maps.routeoptimization_v1.RouteOptimizationAsyncClient`.", - extra = { - "serviceName": "google.maps.routeoptimization.v1.RouteOptimization", - "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.maps.routeoptimization.v1.RouteOptimization", - "credentialsType": None, - } - ) - - async def optimize_tours(self, - request: Optional[Union[route_optimization_service.OptimizeToursRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> route_optimization_service.OptimizeToursResponse: - r"""Sends an ``OptimizeToursRequest`` containing a ``ShipmentModel`` - and returns an ``OptimizeToursResponse`` containing - ``ShipmentRoute``\ s, which are a set of routes to be performed - by vehicles minimizing the overall cost. - - A ``ShipmentModel`` model consists mainly of ``Shipment``\ s - that need to be carried out and ``Vehicle``\ s that can be used - to transport the ``Shipment``\ s. The ``ShipmentRoute``\ s - assign ``Shipment``\ s to ``Vehicle``\ s. More specifically, - they assign a series of ``Visit``\ s to each vehicle, where a - ``Visit`` corresponds to a ``VisitRequest``, which is a pickup - or delivery for a ``Shipment``. - - The goal is to provide an assignment of ``ShipmentRoute``\ s to - ``Vehicle``\ s that minimizes the total cost where cost has many - components defined in the ``ShipmentModel``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import routeoptimization_v1 - - async def sample_optimize_tours(): - # Create a client - client = routeoptimization_v1.RouteOptimizationAsyncClient() - - # Initialize request argument(s) - request = routeoptimization_v1.OptimizeToursRequest( - parent="parent_value", - ) - - # Make the request - response = await client.optimize_tours(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.routeoptimization_v1.types.OptimizeToursRequest, dict]]): - The request object. Request to be given to a tour - optimization solver which defines the - shipment model to solve as well as - optimization parameters. - 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.maps.routeoptimization_v1.types.OptimizeToursResponse: - Response after solving a tour - optimization problem containing the - routes followed by each vehicle, the - shipments which have been skipped and - the overall cost of the solution. - - """ - # 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, route_optimization_service.OptimizeToursRequest): - request = route_optimization_service.OptimizeToursRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.optimize_tours] - - # Certain 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 batch_optimize_tours(self, - request: Optional[Union[route_optimization_service.BatchOptimizeToursRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Optimizes vehicle tours for one or more ``OptimizeToursRequest`` - messages as a batch. - - This method is a Long Running Operation (LRO). The inputs for - optimization (``OptimizeToursRequest`` messages) and outputs - (``OptimizeToursResponse`` messages) are read from and written - to Cloud Storage in user-specified format. Like the - ``OptimizeTours`` method, each ``OptimizeToursRequest`` contains - a ``ShipmentModel`` and returns an ``OptimizeToursResponse`` - containing ``ShipmentRoute`` fields, which are a set of routes - to be performed by vehicles minimizing the overall cost. - - The user can poll ``operations.get`` to check the status of the - LRO: - - If the LRO ``done`` field is false, then at least one request is - still being processed. Other requests may have completed - successfully and their results are available in Cloud Storage. - - If the LRO's ``done`` field is true, then all requests have been - processed. Any successfully processed requests will have their - results available in Cloud Storage. Any requests that failed - will not have their results available in Cloud Storage. If the - LRO's ``error`` field is set, then it contains the error from - one of the failed requests. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import routeoptimization_v1 - - async def sample_batch_optimize_tours(): - # Create a client - client = routeoptimization_v1.RouteOptimizationAsyncClient() - - # Initialize request argument(s) - model_configs = routeoptimization_v1.AsyncModelConfig() - model_configs.input_config.gcs_source.uri = "uri_value" - model_configs.input_config.data_format = "PROTO_TEXT" - model_configs.output_config.gcs_destination.uri = "uri_value" - model_configs.output_config.data_format = "PROTO_TEXT" - - request = routeoptimization_v1.BatchOptimizeToursRequest( - parent="parent_value", - model_configs=model_configs, - ) - - # Make the request - operation = client.batch_optimize_tours(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.routeoptimization_v1.types.BatchOptimizeToursRequest, dict]]): - The request object. Request to batch optimize tours as an asynchronous - operation. Each input file should contain one - ``OptimizeToursRequest``, and each output file will - contain one ``OptimizeToursResponse``. The request - contains information to read/write and parse the files. - All the input and output files should be under the same - project. - 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.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.maps.routeoptimization_v1.types.BatchOptimizeToursResponse` Response to a BatchOptimizeToursRequest. This is returned in - the Long Running Operation after the operation is - complete. - - """ - # 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, route_optimization_service.BatchOptimizeToursRequest): - request = route_optimization_service.BatchOptimizeToursRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.batch_optimize_tours] - - # Certain 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, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - route_optimization_service.BatchOptimizeToursResponse, - metadata_type=route_optimization_service.BatchOptimizeToursMetadata, - ) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.get_operation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # 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) -> "RouteOptimizationAsyncClient": - 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__) - - -__all__ = ( - "RouteOptimizationAsyncClient", -) diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/client.py b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/client.py deleted file mode 100644 index cc69d1cd24de..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/client.py +++ /dev/null @@ -1,905 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -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.maps.routeoptimization_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 - -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.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.maps.routeoptimization_v1.types import route_optimization_service -from .transports.base import RouteOptimizationTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import RouteOptimizationGrpcTransport -from .transports.grpc_asyncio import RouteOptimizationGrpcAsyncIOTransport -from .transports.rest import RouteOptimizationRestTransport - - -class RouteOptimizationClientMeta(type): - """Metaclass for the RouteOptimization 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[RouteOptimizationTransport]] - _transport_registry["grpc"] = RouteOptimizationGrpcTransport - _transport_registry["grpc_asyncio"] = RouteOptimizationGrpcAsyncIOTransport - _transport_registry["rest"] = RouteOptimizationRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[RouteOptimizationTransport]: - """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 RouteOptimizationClient(metaclass=RouteOptimizationClientMeta): - """A service for optimizing vehicle tours. - - Validity of certain types of fields: - - - ``google.protobuf.Timestamp`` - - - Times are in Unix time: seconds since - 1970-01-01T00:00:00+00:00. - - seconds must be in [0, 253402300799], i.e. in - [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. - - nanos must be unset or set to 0. - - - ``google.protobuf.Duration`` - - - seconds must be in [0, 253402300799], i.e. in - [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. - - nanos must be unset or set to 0. - - - ``google.type.LatLng`` - - - latitude must be in [-90.0, 90.0]. - - longitude must be in [-180.0, 180.0]. - - at least one of latitude and longitude must be non-zero. - """ - - @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 = "routeoptimization.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "routeoptimization.{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: - RouteOptimizationClient: 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: - RouteOptimizationClient: 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) -> RouteOptimizationTransport: - """Returns the transport used by the client instance. - - Returns: - RouteOptimizationTransport: The transport used by the client - instance. - """ - return self._transport - - @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 = RouteOptimizationClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = RouteOptimizationClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = RouteOptimizationClient._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 = RouteOptimizationClient._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 - - @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, RouteOptimizationTransport, Callable[..., RouteOptimizationTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the route optimization 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,RouteOptimizationTransport,Callable[..., RouteOptimizationTransport]]]): - 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 RouteOptimizationTransport 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 = RouteOptimizationClient._read_environment_variables() - self._client_cert_source = RouteOptimizationClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = RouteOptimizationClient._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, RouteOptimizationTransport) - if transport_provided: - # transport is a RouteOptimizationTransport 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(RouteOptimizationTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - RouteOptimizationClient._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[RouteOptimizationTransport], Callable[..., RouteOptimizationTransport]] = ( - RouteOptimizationClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., RouteOptimizationTransport], 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.maps.routeoptimization_v1.RouteOptimizationClient`.", - extra = { - "serviceName": "google.maps.routeoptimization.v1.RouteOptimization", - "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.maps.routeoptimization.v1.RouteOptimization", - "credentialsType": None, - } - ) - - def optimize_tours(self, - request: Optional[Union[route_optimization_service.OptimizeToursRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> route_optimization_service.OptimizeToursResponse: - r"""Sends an ``OptimizeToursRequest`` containing a ``ShipmentModel`` - and returns an ``OptimizeToursResponse`` containing - ``ShipmentRoute``\ s, which are a set of routes to be performed - by vehicles minimizing the overall cost. - - A ``ShipmentModel`` model consists mainly of ``Shipment``\ s - that need to be carried out and ``Vehicle``\ s that can be used - to transport the ``Shipment``\ s. The ``ShipmentRoute``\ s - assign ``Shipment``\ s to ``Vehicle``\ s. More specifically, - they assign a series of ``Visit``\ s to each vehicle, where a - ``Visit`` corresponds to a ``VisitRequest``, which is a pickup - or delivery for a ``Shipment``. - - The goal is to provide an assignment of ``ShipmentRoute``\ s to - ``Vehicle``\ s that minimizes the total cost where cost has many - components defined in the ``ShipmentModel``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import routeoptimization_v1 - - def sample_optimize_tours(): - # Create a client - client = routeoptimization_v1.RouteOptimizationClient() - - # Initialize request argument(s) - request = routeoptimization_v1.OptimizeToursRequest( - parent="parent_value", - ) - - # Make the request - response = client.optimize_tours(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.routeoptimization_v1.types.OptimizeToursRequest, dict]): - The request object. Request to be given to a tour - optimization solver which defines the - shipment model to solve as well as - optimization parameters. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.maps.routeoptimization_v1.types.OptimizeToursResponse: - Response after solving a tour - optimization problem containing the - routes followed by each vehicle, the - shipments which have been skipped and - the overall cost of the solution. - - """ - # 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, route_optimization_service.OptimizeToursRequest): - request = route_optimization_service.OptimizeToursRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.optimize_tours] - - # Certain 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 batch_optimize_tours(self, - request: Optional[Union[route_optimization_service.BatchOptimizeToursRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Optimizes vehicle tours for one or more ``OptimizeToursRequest`` - messages as a batch. - - This method is a Long Running Operation (LRO). The inputs for - optimization (``OptimizeToursRequest`` messages) and outputs - (``OptimizeToursResponse`` messages) are read from and written - to Cloud Storage in user-specified format. Like the - ``OptimizeTours`` method, each ``OptimizeToursRequest`` contains - a ``ShipmentModel`` and returns an ``OptimizeToursResponse`` - containing ``ShipmentRoute`` fields, which are a set of routes - to be performed by vehicles minimizing the overall cost. - - The user can poll ``operations.get`` to check the status of the - LRO: - - If the LRO ``done`` field is false, then at least one request is - still being processed. Other requests may have completed - successfully and their results are available in Cloud Storage. - - If the LRO's ``done`` field is true, then all requests have been - processed. Any successfully processed requests will have their - results available in Cloud Storage. Any requests that failed - will not have their results available in Cloud Storage. If the - LRO's ``error`` field is set, then it contains the error from - one of the failed requests. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import routeoptimization_v1 - - def sample_batch_optimize_tours(): - # Create a client - client = routeoptimization_v1.RouteOptimizationClient() - - # Initialize request argument(s) - model_configs = routeoptimization_v1.AsyncModelConfig() - model_configs.input_config.gcs_source.uri = "uri_value" - model_configs.input_config.data_format = "PROTO_TEXT" - model_configs.output_config.gcs_destination.uri = "uri_value" - model_configs.output_config.data_format = "PROTO_TEXT" - - request = routeoptimization_v1.BatchOptimizeToursRequest( - parent="parent_value", - model_configs=model_configs, - ) - - # Make the request - operation = client.batch_optimize_tours(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.maps.routeoptimization_v1.types.BatchOptimizeToursRequest, dict]): - The request object. Request to batch optimize tours as an asynchronous - operation. Each input file should contain one - ``OptimizeToursRequest``, and each output file will - contain one ``OptimizeToursResponse``. The request - contains information to read/write and parse the files. - All the input and output files should be under the same - project. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.maps.routeoptimization_v1.types.BatchOptimizeToursResponse` Response to a BatchOptimizeToursRequest. This is returned in - the Long Running Operation after the operation is - complete. - - """ - # 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, route_optimization_service.BatchOptimizeToursRequest): - request = route_optimization_service.BatchOptimizeToursRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.batch_optimize_tours] - - # Certain 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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - route_optimization_service.BatchOptimizeToursResponse, - metadata_type=route_optimization_service.BatchOptimizeToursMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "RouteOptimizationClient": - 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() - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_operation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # 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 - - - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "RouteOptimizationClient", -) diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/README.rst b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/README.rst deleted file mode 100644 index 777c90bfd2dd..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`RouteOptimizationTransport` is the ABC for all transports. -- public child `RouteOptimizationGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `RouteOptimizationGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseRouteOptimizationRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `RouteOptimizationRestTransport` 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-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/__init__.py b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/__init__.py deleted file mode 100644 index c8b6f8c69432..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 RouteOptimizationTransport -from .grpc import RouteOptimizationGrpcTransport -from .grpc_asyncio import RouteOptimizationGrpcAsyncIOTransport -from .rest import RouteOptimizationRestTransport -from .rest import RouteOptimizationRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[RouteOptimizationTransport]] -_transport_registry['grpc'] = RouteOptimizationGrpcTransport -_transport_registry['grpc_asyncio'] = RouteOptimizationGrpcAsyncIOTransport -_transport_registry['rest'] = RouteOptimizationRestTransport - -__all__ = ( - 'RouteOptimizationTransport', - 'RouteOptimizationGrpcTransport', - 'RouteOptimizationGrpcAsyncIOTransport', - 'RouteOptimizationRestTransport', - 'RouteOptimizationRestInterceptor', -) diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/base.py b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/base.py deleted file mode 100644 index 2ff60f79e53d..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/base.py +++ /dev/null @@ -1,198 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.routeoptimization_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.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.longrunning import operations_pb2 # type: ignore -from google.maps.routeoptimization_v1.types import route_optimization_service - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class RouteOptimizationTransport(abc.ABC): - """Abstract transport class for RouteOptimization.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'routeoptimization.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: 'routeoptimization.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to 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.optimize_tours: gapic_v1.method.wrap_method( - self.optimize_tours, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=3600.0, - ), - default_timeout=3600.0, - client_info=client_info, - ), - self.batch_optimize_tours: gapic_v1.method.wrap_method( - self.batch_optimize_tours, - default_timeout=None, - client_info=client_info, - ), - self.get_operation: gapic_v1.method.wrap_method( - self.get_operation, - 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 operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def optimize_tours(self) -> Callable[ - [route_optimization_service.OptimizeToursRequest], - Union[ - route_optimization_service.OptimizeToursResponse, - Awaitable[route_optimization_service.OptimizeToursResponse] - ]]: - raise NotImplementedError() - - @property - def batch_optimize_tours(self) -> Callable[ - [route_optimization_service.BatchOptimizeToursRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'RouteOptimizationTransport', -) diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/grpc.py b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/grpc.py deleted file mode 100644 index 28739646e9bf..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/grpc.py +++ /dev/null @@ -1,471 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.protobuf.json_format import MessageToJson -import google.protobuf.message - -import grpc # type: ignore -import proto # type: ignore - -from google.longrunning import operations_pb2 # type: ignore -from google.maps.routeoptimization_v1.types import route_optimization_service -from .base import RouteOptimizationTransport, 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.maps.routeoptimization.v1.RouteOptimization", - "rpcName": 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.maps.routeoptimization.v1.RouteOptimization", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class RouteOptimizationGrpcTransport(RouteOptimizationTransport): - """gRPC backend transport for RouteOptimization. - - A service for optimizing vehicle tours. - - Validity of certain types of fields: - - - ``google.protobuf.Timestamp`` - - - Times are in Unix time: seconds since - 1970-01-01T00:00:00+00:00. - - seconds must be in [0, 253402300799], i.e. in - [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. - - nanos must be unset or set to 0. - - - ``google.protobuf.Duration`` - - - seconds must be in [0, 253402300799], i.e. in - [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. - - nanos must be unset or set to 0. - - - ``google.type.LatLng`` - - - latitude must be in [-90.0, 90.0]. - - longitude must be in [-180.0, 180.0]. - - at least one of latitude and longitude must be non-zero. - - This 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 = 'routeoptimization.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: 'routeoptimization.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to 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] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - 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 = 'routeoptimization.googleapis.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 operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self._logged_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def optimize_tours(self) -> Callable[ - [route_optimization_service.OptimizeToursRequest], - route_optimization_service.OptimizeToursResponse]: - r"""Return a callable for the optimize tours method over gRPC. - - Sends an ``OptimizeToursRequest`` containing a ``ShipmentModel`` - and returns an ``OptimizeToursResponse`` containing - ``ShipmentRoute``\ s, which are a set of routes to be performed - by vehicles minimizing the overall cost. - - A ``ShipmentModel`` model consists mainly of ``Shipment``\ s - that need to be carried out and ``Vehicle``\ s that can be used - to transport the ``Shipment``\ s. The ``ShipmentRoute``\ s - assign ``Shipment``\ s to ``Vehicle``\ s. More specifically, - they assign a series of ``Visit``\ s to each vehicle, where a - ``Visit`` corresponds to a ``VisitRequest``, which is a pickup - or delivery for a ``Shipment``. - - The goal is to provide an assignment of ``ShipmentRoute``\ s to - ``Vehicle``\ s that minimizes the total cost where cost has many - components defined in the ``ShipmentModel``. - - Returns: - Callable[[~.OptimizeToursRequest], - ~.OptimizeToursResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'optimize_tours' not in self._stubs: - self._stubs['optimize_tours'] = self._logged_channel.unary_unary( - '/google.maps.routeoptimization.v1.RouteOptimization/OptimizeTours', - request_serializer=route_optimization_service.OptimizeToursRequest.serialize, - response_deserializer=route_optimization_service.OptimizeToursResponse.deserialize, - ) - return self._stubs['optimize_tours'] - - @property - def batch_optimize_tours(self) -> Callable[ - [route_optimization_service.BatchOptimizeToursRequest], - operations_pb2.Operation]: - r"""Return a callable for the batch optimize tours method over gRPC. - - Optimizes vehicle tours for one or more ``OptimizeToursRequest`` - messages as a batch. - - This method is a Long Running Operation (LRO). The inputs for - optimization (``OptimizeToursRequest`` messages) and outputs - (``OptimizeToursResponse`` messages) are read from and written - to Cloud Storage in user-specified format. Like the - ``OptimizeTours`` method, each ``OptimizeToursRequest`` contains - a ``ShipmentModel`` and returns an ``OptimizeToursResponse`` - containing ``ShipmentRoute`` fields, which are a set of routes - to be performed by vehicles minimizing the overall cost. - - The user can poll ``operations.get`` to check the status of the - LRO: - - If the LRO ``done`` field is false, then at least one request is - still being processed. Other requests may have completed - successfully and their results are available in Cloud Storage. - - If the LRO's ``done`` field is true, then all requests have been - processed. Any successfully processed requests will have their - results available in Cloud Storage. Any requests that failed - will not have their results available in Cloud Storage. If the - LRO's ``error`` field is set, then it contains the error from - one of the failed requests. - - Returns: - Callable[[~.BatchOptimizeToursRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_optimize_tours' not in self._stubs: - self._stubs['batch_optimize_tours'] = self._logged_channel.unary_unary( - '/google.maps.routeoptimization.v1.RouteOptimization/BatchOptimizeTours', - request_serializer=route_optimization_service.BatchOptimizeToursRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['batch_optimize_tours'] - - def close(self): - self._logged_channel.close() - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'RouteOptimizationGrpcTransport', -) diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/grpc_asyncio.py b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/grpc_asyncio.py deleted file mode 100644 index ae4a0e4f207d..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/grpc_asyncio.py +++ /dev/null @@ -1,510 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.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.longrunning import operations_pb2 # type: ignore -from google.maps.routeoptimization_v1.types import route_optimization_service -from .base import RouteOptimizationTransport, DEFAULT_CLIENT_INFO -from .grpc import RouteOptimizationGrpcTransport - -try: - from google.api_core import client_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.maps.routeoptimization.v1.RouteOptimization", - "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.maps.routeoptimization.v1.RouteOptimization", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class RouteOptimizationGrpcAsyncIOTransport(RouteOptimizationTransport): - """gRPC AsyncIO backend transport for RouteOptimization. - - A service for optimizing vehicle tours. - - Validity of certain types of fields: - - - ``google.protobuf.Timestamp`` - - - Times are in Unix time: seconds since - 1970-01-01T00:00:00+00:00. - - seconds must be in [0, 253402300799], i.e. in - [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. - - nanos must be unset or set to 0. - - - ``google.protobuf.Duration`` - - - seconds must be in [0, 253402300799], i.e. in - [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. - - nanos must be unset or set to 0. - - - ``google.type.LatLng`` - - - latitude must be in [-90.0, 90.0]. - - longitude must be in [-180.0, 180.0]. - - at least one of latitude and longitude must be non-zero. - - This 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 = 'routeoptimization.googleapis.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 = 'routeoptimization.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: 'routeoptimization.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to 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] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - 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 operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self._logged_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def optimize_tours(self) -> Callable[ - [route_optimization_service.OptimizeToursRequest], - Awaitable[route_optimization_service.OptimizeToursResponse]]: - r"""Return a callable for the optimize tours method over gRPC. - - Sends an ``OptimizeToursRequest`` containing a ``ShipmentModel`` - and returns an ``OptimizeToursResponse`` containing - ``ShipmentRoute``\ s, which are a set of routes to be performed - by vehicles minimizing the overall cost. - - A ``ShipmentModel`` model consists mainly of ``Shipment``\ s - that need to be carried out and ``Vehicle``\ s that can be used - to transport the ``Shipment``\ s. The ``ShipmentRoute``\ s - assign ``Shipment``\ s to ``Vehicle``\ s. More specifically, - they assign a series of ``Visit``\ s to each vehicle, where a - ``Visit`` corresponds to a ``VisitRequest``, which is a pickup - or delivery for a ``Shipment``. - - The goal is to provide an assignment of ``ShipmentRoute``\ s to - ``Vehicle``\ s that minimizes the total cost where cost has many - components defined in the ``ShipmentModel``. - - Returns: - Callable[[~.OptimizeToursRequest], - Awaitable[~.OptimizeToursResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'optimize_tours' not in self._stubs: - self._stubs['optimize_tours'] = self._logged_channel.unary_unary( - '/google.maps.routeoptimization.v1.RouteOptimization/OptimizeTours', - request_serializer=route_optimization_service.OptimizeToursRequest.serialize, - response_deserializer=route_optimization_service.OptimizeToursResponse.deserialize, - ) - return self._stubs['optimize_tours'] - - @property - def batch_optimize_tours(self) -> Callable[ - [route_optimization_service.BatchOptimizeToursRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the batch optimize tours method over gRPC. - - Optimizes vehicle tours for one or more ``OptimizeToursRequest`` - messages as a batch. - - This method is a Long Running Operation (LRO). The inputs for - optimization (``OptimizeToursRequest`` messages) and outputs - (``OptimizeToursResponse`` messages) are read from and written - to Cloud Storage in user-specified format. Like the - ``OptimizeTours`` method, each ``OptimizeToursRequest`` contains - a ``ShipmentModel`` and returns an ``OptimizeToursResponse`` - containing ``ShipmentRoute`` fields, which are a set of routes - to be performed by vehicles minimizing the overall cost. - - The user can poll ``operations.get`` to check the status of the - LRO: - - If the LRO ``done`` field is false, then at least one request is - still being processed. Other requests may have completed - successfully and their results are available in Cloud Storage. - - If the LRO's ``done`` field is true, then all requests have been - processed. Any successfully processed requests will have their - results available in Cloud Storage. Any requests that failed - will not have their results available in Cloud Storage. If the - LRO's ``error`` field is set, then it contains the error from - one of the failed requests. - - Returns: - Callable[[~.BatchOptimizeToursRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_optimize_tours' not in self._stubs: - self._stubs['batch_optimize_tours'] = self._logged_channel.unary_unary( - '/google.maps.routeoptimization.v1.RouteOptimization/BatchOptimizeTours', - request_serializer=route_optimization_service.BatchOptimizeToursRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['batch_optimize_tours'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.optimize_tours: self._wrap_method( - self.optimize_tours, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=3600.0, - ), - default_timeout=3600.0, - client_info=client_info, - ), - self.batch_optimize_tours: self._wrap_method( - self.batch_optimize_tours, - default_timeout=None, - client_info=client_info, - ), - self.get_operation: self._wrap_method( - self.get_operation, - 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" - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - -__all__ = ( - 'RouteOptimizationGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/rest.py b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/rest.py deleted file mode 100644 index 40fc33e37335..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/rest.py +++ /dev/null @@ -1,692 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -from google.protobuf import json_format -from google.api_core import operations_v1 - -from requests import __version__ as requests_version -import dataclasses -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - - -from google.maps.routeoptimization_v1.types import route_optimization_service -from google.longrunning import operations_pb2 # type: ignore - - -from .rest_base import _BaseRouteOptimizationRestTransport -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}", -) - - -class RouteOptimizationRestInterceptor: - """Interceptor for RouteOptimization. - - 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 RouteOptimizationRestTransport. - - .. code-block:: python - class MyCustomRouteOptimizationInterceptor(RouteOptimizationRestInterceptor): - def pre_batch_optimize_tours(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_batch_optimize_tours(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_optimize_tours(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_optimize_tours(self, response): - logging.log(f"Received response: {response}") - return response - - transport = RouteOptimizationRestTransport(interceptor=MyCustomRouteOptimizationInterceptor()) - client = RouteOptimizationClient(transport=transport) - - - """ - def pre_batch_optimize_tours(self, request: route_optimization_service.BatchOptimizeToursRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[route_optimization_service.BatchOptimizeToursRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for batch_optimize_tours - - Override in a subclass to manipulate the request or metadata - before they are sent to the RouteOptimization server. - """ - return request, metadata - - def post_batch_optimize_tours(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for batch_optimize_tours - - Override in a subclass to manipulate the response - after it is returned by the RouteOptimization server but before - it is returned to user code. - """ - return response - - def pre_optimize_tours(self, request: route_optimization_service.OptimizeToursRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[route_optimization_service.OptimizeToursRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for optimize_tours - - Override in a subclass to manipulate the request or metadata - before they are sent to the RouteOptimization server. - """ - return request, metadata - - def post_optimize_tours(self, response: route_optimization_service.OptimizeToursResponse) -> route_optimization_service.OptimizeToursResponse: - """Post-rpc interceptor for optimize_tours - - Override in a subclass to manipulate the response - after it is returned by the RouteOptimization server but before - it is returned to user code. - """ - return response - - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the RouteOptimization server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the RouteOptimization server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class RouteOptimizationRestStub: - _session: AuthorizedSession - _host: str - _interceptor: RouteOptimizationRestInterceptor - - -class RouteOptimizationRestTransport(_BaseRouteOptimizationRestTransport): - """REST backend synchronous transport for RouteOptimization. - - A service for optimizing vehicle tours. - - Validity of certain types of fields: - - - ``google.protobuf.Timestamp`` - - - Times are in Unix time: seconds since - 1970-01-01T00:00:00+00:00. - - seconds must be in [0, 253402300799], i.e. in - [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. - - nanos must be unset or set to 0. - - - ``google.protobuf.Duration`` - - - seconds must be in [0, 253402300799], i.e. in - [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. - - nanos must be unset or set to 0. - - - ``google.type.LatLng`` - - - latitude must be in [-90.0, 90.0]. - - longitude must be in [-180.0, 180.0]. - - at least one of latitude and longitude must be non-zero. - - This 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 = 'routeoptimization.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[RouteOptimizationRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'routeoptimization.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to 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) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or RouteOptimizationRestInterceptor() - self._prep_wrapped_messages(client_info) - - @property - def operations_client(self) -> operations_v1.AbstractOperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Only create a new client if we do not already have one. - if self._operations_client is None: - http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ], - } - - rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _BatchOptimizeTours(_BaseRouteOptimizationRestTransport._BaseBatchOptimizeTours, RouteOptimizationRestStub): - def __hash__(self): - return hash("RouteOptimizationRestTransport.BatchOptimizeTours") - - @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: route_optimization_service.BatchOptimizeToursRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the batch optimize tours method over HTTP. - - Args: - request (~.route_optimization_service.BatchOptimizeToursRequest): - The request object. Request to batch optimize tours as an asynchronous - operation. Each input file should contain one - ``OptimizeToursRequest``, and each output file will - contain one ``OptimizeToursResponse``. The request - contains information to read/write and parse the files. - All the input and output files should be under the same - project. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseRouteOptimizationRestTransport._BaseBatchOptimizeTours._get_http_options() - - request, metadata = self._interceptor.pre_batch_optimize_tours(request, metadata) - transcoded_request = _BaseRouteOptimizationRestTransport._BaseBatchOptimizeTours._get_transcoded_request(http_options, request) - - body = _BaseRouteOptimizationRestTransport._BaseBatchOptimizeTours._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseRouteOptimizationRestTransport._BaseBatchOptimizeTours._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(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.maps.routeoptimization_v1.RouteOptimizationClient.BatchOptimizeTours", - extra = { - "serviceName": "google.maps.routeoptimization.v1.RouteOptimization", - "rpcName": "BatchOptimizeTours", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = RouteOptimizationRestTransport._BatchOptimizeTours._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 = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_batch_optimize_tours(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.maps.routeoptimization_v1.RouteOptimizationClient.batch_optimize_tours", - extra = { - "serviceName": "google.maps.routeoptimization.v1.RouteOptimization", - "rpcName": "BatchOptimizeTours", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _OptimizeTours(_BaseRouteOptimizationRestTransport._BaseOptimizeTours, RouteOptimizationRestStub): - def __hash__(self): - return hash("RouteOptimizationRestTransport.OptimizeTours") - - @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: route_optimization_service.OptimizeToursRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> route_optimization_service.OptimizeToursResponse: - r"""Call the optimize tours method over HTTP. - - Args: - request (~.route_optimization_service.OptimizeToursRequest): - The request object. Request to be given to a tour - optimization solver which defines the - shipment model to solve as well as - optimization parameters. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.route_optimization_service.OptimizeToursResponse: - Response after solving a tour - optimization problem containing the - routes followed by each vehicle, the - shipments which have been skipped and - the overall cost of the solution. - - """ - - http_options = _BaseRouteOptimizationRestTransport._BaseOptimizeTours._get_http_options() - - request, metadata = self._interceptor.pre_optimize_tours(request, metadata) - transcoded_request = _BaseRouteOptimizationRestTransport._BaseOptimizeTours._get_transcoded_request(http_options, request) - - body = _BaseRouteOptimizationRestTransport._BaseOptimizeTours._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseRouteOptimizationRestTransport._BaseOptimizeTours._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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.maps.routeoptimization_v1.RouteOptimizationClient.OptimizeTours", - extra = { - "serviceName": "google.maps.routeoptimization.v1.RouteOptimization", - "rpcName": "OptimizeTours", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = RouteOptimizationRestTransport._OptimizeTours._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 = route_optimization_service.OptimizeToursResponse() - pb_resp = route_optimization_service.OptimizeToursResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_optimize_tours(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = route_optimization_service.OptimizeToursResponse.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.maps.routeoptimization_v1.RouteOptimizationClient.optimize_tours", - extra = { - "serviceName": "google.maps.routeoptimization.v1.RouteOptimization", - "rpcName": "OptimizeTours", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def batch_optimize_tours(self) -> Callable[ - [route_optimization_service.BatchOptimizeToursRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._BatchOptimizeTours(self._session, self._host, self._interceptor) # type: ignore - - @property - def optimize_tours(self) -> Callable[ - [route_optimization_service.OptimizeToursRequest], - route_optimization_service.OptimizeToursResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._OptimizeTours(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(_BaseRouteOptimizationRestTransport._BaseGetOperation, RouteOptimizationRestStub): - def __hash__(self): - return hash("RouteOptimizationRestTransport.GetOperation") - - @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: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options = _BaseRouteOptimizationRestTransport._BaseGetOperation._get_http_options() - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - transcoded_request = _BaseRouteOptimizationRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseRouteOptimizationRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.maps.routeoptimization_v1.RouteOptimizationClient.GetOperation", - extra = { - "serviceName": "google.maps.routeoptimization.v1.RouteOptimization", - "rpcName": "GetOperation", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = RouteOptimizationRestTransport._GetOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = operations_pb2.Operation() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_get_operation(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.maps.routeoptimization_v1.RouteOptimizationAsyncClient.GetOperation", - extra = { - "serviceName": "google.maps.routeoptimization.v1.RouteOptimization", - "rpcName": "GetOperation", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'RouteOptimizationRestTransport', -) diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/rest_base.py b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/rest_base.py deleted file mode 100644 index 849347da5750..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/rest_base.py +++ /dev/null @@ -1,221 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 RouteOptimizationTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.maps.routeoptimization_v1.types import route_optimization_service -from google.longrunning import operations_pb2 # type: ignore - - -class _BaseRouteOptimizationRestTransport(RouteOptimizationTransport): - """Base REST backend transport for RouteOptimization. - - 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 = 'routeoptimization.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: 'routeoptimization.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 _BaseBatchOptimizeTours: - 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': '/v1/{parent=projects/*/locations/*}:batchOptimizeTours', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{parent=projects/*}:batchOptimizeTours', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = route_optimization_service.BatchOptimizeToursRequest.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(_BaseRouteOptimizationRestTransport._BaseBatchOptimizeTours._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseOptimizeTours: - 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': '/v1/{parent=projects/*/locations/*}:optimizeTours', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{parent=projects/*}:optimizeTours', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = route_optimization_service.OptimizeToursRequest.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(_BaseRouteOptimizationRestTransport._BaseOptimizeTours._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetOperation: - 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': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - -__all__=( - '_BaseRouteOptimizationRestTransport', -) diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/types/__init__.py b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/types/__init__.py deleted file mode 100644 index a2de944fa5be..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/types/__init__.py +++ /dev/null @@ -1,74 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .route_optimization_service import ( - AggregatedMetrics, - BatchOptimizeToursMetadata, - BatchOptimizeToursRequest, - BatchOptimizeToursResponse, - BreakRule, - DistanceLimit, - GcsDestination, - GcsSource, - InjectedSolutionConstraint, - InputConfig, - Location, - OptimizeToursRequest, - OptimizeToursResponse, - OptimizeToursValidationError, - OutputConfig, - RouteModifiers, - Shipment, - ShipmentModel, - ShipmentRoute, - ShipmentTypeIncompatibility, - ShipmentTypeRequirement, - SkippedShipment, - TimeWindow, - TransitionAttributes, - Vehicle, - Waypoint, - DataFormat, -) - -__all__ = ( - 'AggregatedMetrics', - 'BatchOptimizeToursMetadata', - 'BatchOptimizeToursRequest', - 'BatchOptimizeToursResponse', - 'BreakRule', - 'DistanceLimit', - 'GcsDestination', - 'GcsSource', - 'InjectedSolutionConstraint', - 'InputConfig', - 'Location', - 'OptimizeToursRequest', - 'OptimizeToursResponse', - 'OptimizeToursValidationError', - 'OutputConfig', - 'RouteModifiers', - 'Shipment', - 'ShipmentModel', - 'ShipmentRoute', - 'ShipmentTypeIncompatibility', - 'ShipmentTypeRequirement', - 'SkippedShipment', - 'TimeWindow', - 'TransitionAttributes', - 'Vehicle', - 'Waypoint', - 'DataFormat', -) diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/types/route_optimization_service.py b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/types/route_optimization_service.py deleted file mode 100644 index f361d0359c2a..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/types/route_optimization_service.py +++ /dev/null @@ -1,3776 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.type import latlng_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routeoptimization.v1', - manifest={ - 'DataFormat', - 'BatchOptimizeToursRequest', - 'BatchOptimizeToursResponse', - 'BatchOptimizeToursMetadata', - 'OptimizeToursRequest', - 'OptimizeToursResponse', - 'ShipmentModel', - 'Shipment', - 'ShipmentTypeIncompatibility', - 'ShipmentTypeRequirement', - 'RouteModifiers', - 'Vehicle', - 'TimeWindow', - 'DistanceLimit', - 'TransitionAttributes', - 'Waypoint', - 'Location', - 'BreakRule', - 'ShipmentRoute', - 'SkippedShipment', - 'AggregatedMetrics', - 'InjectedSolutionConstraint', - 'OptimizeToursValidationError', - 'InputConfig', - 'OutputConfig', - 'GcsSource', - 'GcsDestination', - }, -) - - -class DataFormat(proto.Enum): - r"""Data formats for input and output files. - - Values: - DATA_FORMAT_UNSPECIFIED (0): - Invalid value, format must not be - UNSPECIFIED. - JSON (1): - JavaScript Object Notation. - PROTO_TEXT (2): - Protocol Buffers text format. See - https://protobuf.dev/reference/protobuf/textformat-spec/ - """ - DATA_FORMAT_UNSPECIFIED = 0 - JSON = 1 - PROTO_TEXT = 2 - - -class BatchOptimizeToursRequest(proto.Message): - r"""Request to batch optimize tours as an asynchronous operation. Each - input file should contain one ``OptimizeToursRequest``, and each - output file will contain one ``OptimizeToursResponse``. The request - contains information to read/write and parse the files. All the - input and output files should be under the same project. - - Attributes: - parent (str): - Required. Target project and location to make a call. - - Format: - - - ``projects/{project-id}`` - - ``projects/{project-id}/locations/{location-id}`` - - If no location is specified, a region will be chosen - automatically. - model_configs (MutableSequence[google.maps.routeoptimization_v1.types.BatchOptimizeToursRequest.AsyncModelConfig]): - Required. Input/Output information each - purchase model, such as file paths and data - formats. - """ - - class AsyncModelConfig(proto.Message): - r"""Information for solving one optimization model - asynchronously. - - Attributes: - display_name (str): - Optional. User defined model name, can be - used as alias by users to keep track of models. - input_config (google.maps.routeoptimization_v1.types.InputConfig): - Required. Information about the input model. - output_config (google.maps.routeoptimization_v1.types.OutputConfig): - Required. The desired output location - information. - """ - - display_name: str = proto.Field( - proto.STRING, - number=1, - ) - input_config: 'InputConfig' = proto.Field( - proto.MESSAGE, - number=2, - message='InputConfig', - ) - output_config: 'OutputConfig' = proto.Field( - proto.MESSAGE, - number=3, - message='OutputConfig', - ) - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - model_configs: MutableSequence[AsyncModelConfig] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=AsyncModelConfig, - ) - - -class BatchOptimizeToursResponse(proto.Message): - r"""Response to a ``BatchOptimizeToursRequest``. This is returned in the - Long Running Operation after the operation is complete. - - """ - - -class BatchOptimizeToursMetadata(proto.Message): - r"""Operation metadata for ``BatchOptimizeToursRequest`` calls. - """ - - -class OptimizeToursRequest(proto.Message): - r"""Request to be given to a tour optimization solver which - defines the shipment model to solve as well as optimization - parameters. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - parent (str): - Required. Target project or location to make a call. - - Format: - - - ``projects/{project-id}`` - - ``projects/{project-id}/locations/{location-id}`` - - If no location is specified, a region will be chosen - automatically. - timeout (google.protobuf.duration_pb2.Duration): - If this timeout is set, the server returns a - response before the timeout period has elapsed - or the server deadline for synchronous requests - is reached, whichever is sooner. - - For asynchronous requests, the server will - generate a solution (if possible) before the - timeout has elapsed. - model (google.maps.routeoptimization_v1.types.ShipmentModel): - Shipment model to solve. - solving_mode (google.maps.routeoptimization_v1.types.OptimizeToursRequest.SolvingMode): - By default, the solving mode is ``DEFAULT_SOLVE`` (0). - search_mode (google.maps.routeoptimization_v1.types.OptimizeToursRequest.SearchMode): - Search mode used to solve the request. - injected_first_solution_routes (MutableSequence[google.maps.routeoptimization_v1.types.ShipmentRoute]): - Guide the optimization algorithm in finding a first solution - that is similar to a previous solution. - - The model is constrained when the first solution is built. - Any shipments not performed on a route are implicitly - skipped in the first solution, but they may be performed in - successive solutions. - - The solution must satisfy some basic validity assumptions: - - - for all routes, ``vehicle_index`` must be in range and - not be duplicated. - - for all visits, ``shipment_index`` and - ``visit_request_index`` must be in range. - - a shipment may only be referenced on one route. - - the pickup of a pickup-delivery shipment must be - performed before the delivery. - - no more than one pickup alternative or delivery - alternative of a shipment may be performed. - - for all routes, times are increasing (i.e., - ``vehicle_start_time <= visits[0].start_time <= visits[1].start_time ... <= vehicle_end_time``). - - a shipment may only be performed on a vehicle that is - allowed. A vehicle is allowed if - [Shipment.allowed_vehicle_indices][google.maps.routeoptimization.v1.Shipment.allowed_vehicle_indices] - is empty or its ``vehicle_index`` is included in - [Shipment.allowed_vehicle_indices][google.maps.routeoptimization.v1.Shipment.allowed_vehicle_indices]. - - If the injected solution is not feasible, a validation error - is not necessarily returned and an error indicating - infeasibility may be returned instead. - injected_solution_constraint (google.maps.routeoptimization_v1.types.InjectedSolutionConstraint): - Constrain the optimization algorithm to find - a final solution that is similar to a previous - solution. For example, this may be used to - freeze portions of routes which have already - been completed or which are to be completed but - must not be modified. - - If the injected solution is not feasible, a - validation error is not necessarily returned and - an error indicating infeasibility may be - returned instead. - refresh_details_routes (MutableSequence[google.maps.routeoptimization_v1.types.ShipmentRoute]): - If non-empty, the given routes will be refreshed, without - modifying their underlying sequence of visits or travel - times: only other details will be updated. This does not - solve the model. - - As of 2020/11, this only populates the polylines of - non-empty routes and requires that ``populate_polylines`` is - true. - - The ``route_polyline`` fields of the passed-in routes may be - inconsistent with route ``transitions``. - - This field must not be used together with - ``injected_first_solution_routes`` or - ``injected_solution_constraint``. - - ``Shipment.ignore`` and ``Vehicle.ignore`` have no effect on - the behavior. Polylines are still populated between all - visits in all non-empty routes regardless of whether the - related shipments or vehicles are ignored. - interpret_injected_solutions_using_labels (bool): - If true: - - - uses - [ShipmentRoute.vehicle_label][google.maps.routeoptimization.v1.ShipmentRoute.vehicle_label] - instead of ``vehicle_index`` to match routes in an - injected solution with vehicles in the request; reuses - the mapping of original - [ShipmentRoute.vehicle_index][google.maps.routeoptimization.v1.ShipmentRoute.vehicle_index] - to new - [ShipmentRoute.vehicle_index][google.maps.routeoptimization.v1.ShipmentRoute.vehicle_index] - to update - [ConstraintRelaxation.vehicle_indices][google.maps.routeoptimization.v1.InjectedSolutionConstraint.ConstraintRelaxation.vehicle_indices] - if non-empty, but the mapping must be unambiguous (i.e., - multiple ``ShipmentRoute``\ s must not share the same - original ``vehicle_index``). - - uses - [ShipmentRoute.Visit.shipment_label][google.maps.routeoptimization.v1.ShipmentRoute.Visit.shipment_label] - instead of ``shipment_index`` to match visits in an - injected solution with shipments in the request; - - uses - [SkippedShipment.label][google.maps.routeoptimization.v1.SkippedShipment.label] - instead of - [SkippedShipment.index][google.maps.routeoptimization.v1.SkippedShipment.index] - to match skipped shipments in the injected solution with - request shipments. - - This interpretation applies to the - ``injected_first_solution_routes``, - ``injected_solution_constraint``, and - ``refresh_details_routes`` fields. It can be used when - shipment or vehicle indices in the request have changed - since the solution was created, perhaps because shipments or - vehicles have been removed from or added to the request. - - If true, labels in the following categories must appear at - most once in their category: - - - [Vehicle.label][google.maps.routeoptimization.v1.Vehicle.label] - in the request; - - [Shipment.label][google.maps.routeoptimization.v1.Shipment.label] - in the request; - - [ShipmentRoute.vehicle_label][google.maps.routeoptimization.v1.ShipmentRoute.vehicle_label] - in the injected solution; - - [SkippedShipment.label][google.maps.routeoptimization.v1.SkippedShipment.label] - and - [ShipmentRoute.Visit.shipment_label][google.maps.routeoptimization.v1.ShipmentRoute.Visit.shipment_label] - in the injected solution (except pickup/delivery visit - pairs, whose ``shipment_label`` must appear twice). - - If a ``vehicle_label`` in the injected solution does not - correspond to a request vehicle, the corresponding route is - removed from the solution along with its visits. If a - ``shipment_label`` in the injected solution does not - correspond to a request shipment, the corresponding visit is - removed from the solution. If a - [SkippedShipment.label][google.maps.routeoptimization.v1.SkippedShipment.label] - in the injected solution does not correspond to a request - shipment, the ``SkippedShipment`` is removed from the - solution. - - Removing route visits or entire routes from an injected - solution may have an effect on the implied constraints, - which may lead to change in solution, validation errors, or - infeasibility. - - NOTE: The caller must ensure that each - [Vehicle.label][google.maps.routeoptimization.v1.Vehicle.label] - (resp. - [Shipment.label][google.maps.routeoptimization.v1.Shipment.label]) - uniquely identifies a vehicle (resp. shipment) entity used - across the two relevant requests: the past request that - produced the ``OptimizeToursResponse`` used in the injected - solution and the current request that includes the injected - solution. The uniqueness checks described above are not - enough to guarantee this requirement. - consider_road_traffic (bool): - Consider traffic estimation in calculating ``ShipmentRoute`` - fields - [Transition.travel_duration][google.maps.routeoptimization.v1.ShipmentRoute.Transition.travel_duration], - [Visit.start_time][google.maps.routeoptimization.v1.ShipmentRoute.Visit.start_time], - and ``vehicle_end_time``; in setting the - [ShipmentRoute.has_traffic_infeasibilities][google.maps.routeoptimization.v1.ShipmentRoute.has_traffic_infeasibilities] - field, and in calculating the - [OptimizeToursResponse.total_cost][google.maps.routeoptimization.v1.OptimizeToursResponse.total_cost] - field. - populate_polylines (bool): - If true, polylines will be populated in response - ``ShipmentRoute``\ s. - populate_transition_polylines (bool): - If true, polylines and route tokens will be populated in - response - [ShipmentRoute.transitions][google.maps.routeoptimization.v1.ShipmentRoute.transitions]. - allow_large_deadline_despite_interruption_risk (bool): - If this is set, then the request can have a - deadline (see https://grpc.io/blog/deadlines) of - up to 60 minutes. Otherwise, the maximum - deadline is only 30 minutes. Note that - long-lived requests have a significantly larger - (but still small) risk of interruption. - use_geodesic_distances (bool): - If true, travel distances will be computed using geodesic - distances instead of Google Maps distances, and travel times - will be computed using geodesic distances with a speed - defined by ``geodesic_meters_per_second``. - geodesic_meters_per_second (float): - When ``use_geodesic_distances`` is true, this field must be - set and defines the speed applied to compute travel times. - Its value must be at least 1.0 meters/seconds. - - This field is a member of `oneof`_ ``_geodesic_meters_per_second``. - max_validation_errors (int): - Truncates the number of validation errors returned. These - errors are typically attached to an INVALID_ARGUMENT error - payload as a BadRequest error detail - (https://cloud.google.com/apis/design/errors#error_details), - unless solving_mode=VALIDATE_ONLY: see the - [OptimizeToursResponse.validation_errors][google.maps.routeoptimization.v1.OptimizeToursResponse.validation_errors] - field. This defaults to 100 and is capped at 10,000. - - This field is a member of `oneof`_ ``_max_validation_errors``. - label (str): - Label that may be used to identify this request, reported - back in the - [OptimizeToursResponse.request_label][google.maps.routeoptimization.v1.OptimizeToursResponse.request_label]. - """ - class SolvingMode(proto.Enum): - r"""Defines how the solver should handle the request. In all modes but - ``VALIDATE_ONLY``, if the request is invalid, you will receive an - ``INVALID_REQUEST`` error. See - [max_validation_errors][google.maps.routeoptimization.v1.OptimizeToursRequest.max_validation_errors] - to cap the number of errors returned. - - Values: - DEFAULT_SOLVE (0): - Solve the model. Warnings may be issued in - [OptimizeToursResponse.validation_errors][google.cloud.optimization.v1.OptimizeToursResponse.validation_errors]. - VALIDATE_ONLY (1): - Only validates the model without solving it: populates as - many - [OptimizeToursResponse.validation_errors][google.maps.routeoptimization.v1.OptimizeToursResponse.validation_errors] - as possible. - DETECT_SOME_INFEASIBLE_SHIPMENTS (2): - Only populates - [OptimizeToursResponse.validation_errors][google.maps.routeoptimization.v1.OptimizeToursResponse.validation_errors] - or - [OptimizeToursResponse.skipped_shipments][google.maps.routeoptimization.v1.OptimizeToursResponse.skipped_shipments], - and doesn't actually solve the rest of the request - (``status`` and ``routes`` are unset in the response). If - infeasibilities in ``injected_solution_constraint`` routes - are detected they are populated in the - [OptimizeToursResponse.validation_errors][google.maps.routeoptimization.v1.OptimizeToursResponse.validation_errors] - field and - [OptimizeToursResponse.skipped_shipments][google.maps.routeoptimization.v1.OptimizeToursResponse.skipped_shipments] - is left empty. - - *IMPORTANT*: not all infeasible shipments are returned here, - but only the ones that are detected as infeasible during - preprocessing. - """ - DEFAULT_SOLVE = 0 - VALIDATE_ONLY = 1 - DETECT_SOME_INFEASIBLE_SHIPMENTS = 2 - - class SearchMode(proto.Enum): - r"""Mode defining the behavior of the search, trading off latency - versus solution quality. In all modes, the global request - deadline is enforced. - - Values: - SEARCH_MODE_UNSPECIFIED (0): - Unspecified search mode, equivalent to ``RETURN_FAST``. - RETURN_FAST (1): - Stop the search after finding the first good - solution. - CONSUME_ALL_AVAILABLE_TIME (2): - Spend all the available time to search for - better solutions. - """ - SEARCH_MODE_UNSPECIFIED = 0 - RETURN_FAST = 1 - CONSUME_ALL_AVAILABLE_TIME = 2 - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - timeout: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - model: 'ShipmentModel' = proto.Field( - proto.MESSAGE, - number=3, - message='ShipmentModel', - ) - solving_mode: SolvingMode = proto.Field( - proto.ENUM, - number=4, - enum=SolvingMode, - ) - search_mode: SearchMode = proto.Field( - proto.ENUM, - number=6, - enum=SearchMode, - ) - injected_first_solution_routes: MutableSequence['ShipmentRoute'] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message='ShipmentRoute', - ) - injected_solution_constraint: 'InjectedSolutionConstraint' = proto.Field( - proto.MESSAGE, - number=8, - message='InjectedSolutionConstraint', - ) - refresh_details_routes: MutableSequence['ShipmentRoute'] = proto.RepeatedField( - proto.MESSAGE, - number=9, - message='ShipmentRoute', - ) - interpret_injected_solutions_using_labels: bool = proto.Field( - proto.BOOL, - number=10, - ) - consider_road_traffic: bool = proto.Field( - proto.BOOL, - number=11, - ) - populate_polylines: bool = proto.Field( - proto.BOOL, - number=12, - ) - populate_transition_polylines: bool = proto.Field( - proto.BOOL, - number=13, - ) - allow_large_deadline_despite_interruption_risk: bool = proto.Field( - proto.BOOL, - number=14, - ) - use_geodesic_distances: bool = proto.Field( - proto.BOOL, - number=15, - ) - geodesic_meters_per_second: float = proto.Field( - proto.DOUBLE, - number=16, - optional=True, - ) - max_validation_errors: int = proto.Field( - proto.INT32, - number=5, - optional=True, - ) - label: str = proto.Field( - proto.STRING, - number=17, - ) - - -class OptimizeToursResponse(proto.Message): - r"""Response after solving a tour optimization problem containing - the routes followed by each vehicle, the shipments which have - been skipped and the overall cost of the solution. - - Attributes: - routes (MutableSequence[google.maps.routeoptimization_v1.types.ShipmentRoute]): - Routes computed for each vehicle; the i-th - route corresponds to the i-th vehicle in the - model. - request_label (str): - Copy of the - [OptimizeToursRequest.label][google.maps.routeoptimization.v1.OptimizeToursRequest.label], - if a label was specified in the request. - skipped_shipments (MutableSequence[google.maps.routeoptimization_v1.types.SkippedShipment]): - The list of all shipments skipped. - validation_errors (MutableSequence[google.maps.routeoptimization_v1.types.OptimizeToursValidationError]): - List of all the validation errors that we were able to - detect independently. See the "MULTIPLE ERRORS" explanation - for the - [OptimizeToursValidationError][google.maps.routeoptimization.v1.OptimizeToursValidationError] - message. Instead of errors, this will include warnings in - the case ``solving_mode`` is ``DEFAULT_SOLVE``. - metrics (google.maps.routeoptimization_v1.types.OptimizeToursResponse.Metrics): - Duration, distance and usage metrics for this - solution. - """ - - class Metrics(proto.Message): - r"""Overall metrics, aggregated over all routes. - - Attributes: - aggregated_route_metrics (google.maps.routeoptimization_v1.types.AggregatedMetrics): - Aggregated over the routes. Each metric is the sum (or max, - for loads) over all - [ShipmentRoute.metrics][google.maps.routeoptimization.v1.ShipmentRoute.metrics] - fields of the same name. - skipped_mandatory_shipment_count (int): - Number of mandatory shipments skipped. - used_vehicle_count (int): - Number of vehicles used. Note: if a vehicle route is empty - and - [Vehicle.used_if_route_is_empty][google.maps.routeoptimization.v1.Vehicle.used_if_route_is_empty] - is true, the vehicle is considered used. - earliest_vehicle_start_time (google.protobuf.timestamp_pb2.Timestamp): - The earliest start time for a used vehicle, computed as the - minimum over all used vehicles of - [ShipmentRoute.vehicle_start_time][google.maps.routeoptimization.v1.ShipmentRoute.vehicle_start_time]. - latest_vehicle_end_time (google.protobuf.timestamp_pb2.Timestamp): - The latest end time for a used vehicle, computed as the - maximum over all used vehicles of - [ShipmentRoute.vehicle_end_time][google.maps.routeoptimization.v1.ShipmentRoute.vehicle_end_time]. - costs (MutableMapping[str, float]): - Cost of the solution, broken down by cost-related request - fields. The keys are proto paths, relative to the input - OptimizeToursRequest, e.g. "model.shipments.pickups.cost", - and the values are the total cost generated by the - corresponding cost field, aggregated over the whole - solution. In other words, - costs["model.shipments.pickups.cost"] is the sum of all - pickup costs over the solution. All costs defined in the - model are reported in detail here with the exception of - costs related to TransitionAttributes that are only reported - in an aggregated way as of 2022/01. - total_cost (float): - Total cost of the solution. The sum of all - values in the costs map. - """ - - aggregated_route_metrics: 'AggregatedMetrics' = proto.Field( - proto.MESSAGE, - number=1, - message='AggregatedMetrics', - ) - skipped_mandatory_shipment_count: int = proto.Field( - proto.INT32, - number=2, - ) - used_vehicle_count: int = proto.Field( - proto.INT32, - number=3, - ) - earliest_vehicle_start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - latest_vehicle_end_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - costs: MutableMapping[str, float] = proto.MapField( - proto.STRING, - proto.DOUBLE, - number=10, - ) - total_cost: float = proto.Field( - proto.DOUBLE, - number=6, - ) - - routes: MutableSequence['ShipmentRoute'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ShipmentRoute', - ) - request_label: str = proto.Field( - proto.STRING, - number=3, - ) - skipped_shipments: MutableSequence['SkippedShipment'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='SkippedShipment', - ) - validation_errors: MutableSequence['OptimizeToursValidationError'] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message='OptimizeToursValidationError', - ) - metrics: Metrics = proto.Field( - proto.MESSAGE, - number=6, - message=Metrics, - ) - - -class ShipmentModel(proto.Message): - r"""A shipment model contains a set of shipments which must be performed - by a set of vehicles, while minimizing the overall cost, which is - the sum of: - - - the cost of routing the vehicles (sum of cost per total time, - cost per travel time, and fixed cost over all vehicles). - - the unperformed shipment penalties. - - the cost of the global duration of the shipments - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - shipments (MutableSequence[google.maps.routeoptimization_v1.types.Shipment]): - Set of shipments which must be performed in - the model. - vehicles (MutableSequence[google.maps.routeoptimization_v1.types.Vehicle]): - Set of vehicles which can be used to perform - visits. - max_active_vehicles (int): - Constrains the maximum number of active - vehicles. A vehicle is active if its route - performs at least one shipment. This can be used - to limit the number of routes in the case where - there are fewer drivers than vehicles and that - the fleet of vehicles is heterogeneous. The - optimization will then select the best subset of - vehicles to use. Must be strictly positive. - - This field is a member of `oneof`_ ``_max_active_vehicles``. - global_start_time (google.protobuf.timestamp_pb2.Timestamp): - Global start and end time of the model: no times outside of - this range can be considered valid. - - The model's time span must be less than a year, i.e. the - ``global_end_time`` and the ``global_start_time`` must be - within 31536000 seconds of each other. - - When using ``cost_per_*hour`` fields, you might want to set - this window to a smaller interval to increase performance - (eg. if you model a single day, you should set the global - time limits to that day). If unset, 00:00:00 UTC, January 1, - 1970 (i.e. seconds: 0, nanos: 0) is used as default. - global_end_time (google.protobuf.timestamp_pb2.Timestamp): - If unset, 00:00:00 UTC, January 1, 1971 (i.e. - seconds: 31536000, nanos: 0) is used as default. - global_duration_cost_per_hour (float): - The "global duration" of the overall plan is the difference - between the earliest effective start time and the latest - effective end time of all vehicles. Users can assign a cost - per hour to that quantity to try and optimize for earliest - job completion, for example. This cost must be in the same - unit as - [Shipment.penalty_cost][google.maps.routeoptimization.v1.Shipment.penalty_cost]. - duration_distance_matrices (MutableSequence[google.maps.routeoptimization_v1.types.ShipmentModel.DurationDistanceMatrix]): - Specifies duration and distance matrices used in the model. - If this field is empty, Google Maps or geodesic distances - will be used instead, depending on the value of the - ``use_geodesic_distances`` field. If it is not empty, - ``use_geodesic_distances`` cannot be true and neither - ``duration_distance_matrix_src_tags`` nor - ``duration_distance_matrix_dst_tags`` can be empty. - - Usage examples: - - - There are two locations: locA and locB. - - 1 vehicle starting its route at locA and ending it at - locA. - - 1 pickup visit request at locB. - - :: - - model { - vehicles { start_tags: "locA" end_tags: "locA" } - shipments { pickups { tags: "locB" } } - duration_distance_matrix_src_tags: "locA" - duration_distance_matrix_src_tags: "locB" - duration_distance_matrix_dst_tags: "locA" - duration_distance_matrix_dst_tags: "locB" - duration_distance_matrices { - rows { # from: locA - durations { seconds: 0 } meters: 0 # to: locA - durations { seconds: 100 } meters: 1000 # to: locB - } - rows { # from: locB - durations { seconds: 102 } meters: 990 # to: locA - durations { seconds: 0 } meters: 0 # to: locB - } - } - } - - - There are three locations: locA, locB and locC. - - 1 vehicle starting its route at locA and ending it at - locB, using matrix "fast". - - 1 vehicle starting its route at locB and ending it at - locB, using matrix "slow". - - 1 vehicle starting its route at locB and ending it at - locB, using matrix "fast". - - 1 pickup visit request at locC. - - :: - - model { - vehicles { start_tags: "locA" end_tags: "locB" start_tags: "fast" } - vehicles { start_tags: "locB" end_tags: "locB" start_tags: "slow" } - vehicles { start_tags: "locB" end_tags: "locB" start_tags: "fast" } - shipments { pickups { tags: "locC" } } - duration_distance_matrix_src_tags: "locA" - duration_distance_matrix_src_tags: "locB" - duration_distance_matrix_src_tags: "locC" - duration_distance_matrix_dst_tags: "locB" - duration_distance_matrix_dst_tags: "locC" - duration_distance_matrices { - vehicle_start_tag: "fast" - rows { # from: locA - durations { seconds: 1000 } meters: 2000 # to: locB - durations { seconds: 600 } meters: 1000 # to: locC - } - rows { # from: locB - durations { seconds: 0 } meters: 0 # to: locB - durations { seconds: 700 } meters: 1200 # to: locC - } - rows { # from: locC - durations { seconds: 702 } meters: 1190 # to: locB - durations { seconds: 0 } meters: 0 # to: locC - } - } - duration_distance_matrices { - vehicle_start_tag: "slow" - rows { # from: locA - durations { seconds: 1800 } meters: 2001 # to: locB - durations { seconds: 900 } meters: 1002 # to: locC - } - rows { # from: locB - durations { seconds: 0 } meters: 0 # to: locB - durations { seconds: 1000 } meters: 1202 # to: locC - } - rows { # from: locC - durations { seconds: 1001 } meters: 1195 # to: locB - durations { seconds: 0 } meters: 0 # to: locC - } - } - } - duration_distance_matrix_src_tags (MutableSequence[str]): - Tags defining the sources of the duration and distance - matrices; ``duration_distance_matrices(i).rows(j)`` defines - durations and distances from visits with tag - ``duration_distance_matrix_src_tags(j)`` to other visits in - matrix i. - - Tags correspond to - [VisitRequest.tags][google.maps.routeoptimization.v1.Shipment.VisitRequest.tags] - or - [Vehicle.start_tags][google.maps.routeoptimization.v1.Vehicle.start_tags]. - A given ``VisitRequest`` or ``Vehicle`` must match exactly - one tag in this field. Note that a ``Vehicle``'s source, - destination and matrix tags may be the same; similarly a - ``VisitRequest``'s source and destination tags may be the - same. All tags must be different and cannot be empty - strings. If this field is not empty, then - ``duration_distance_matrices`` must not be empty. - duration_distance_matrix_dst_tags (MutableSequence[str]): - Tags defining the destinations of the duration and distance - matrices; - ``duration_distance_matrices(i).rows(j).durations(k)`` - (resp. ``duration_distance_matrices(i).rows(j).meters(k))`` - defines the duration (resp. the distance) of the travel from - visits with tag ``duration_distance_matrix_src_tags(j)`` to - visits with tag ``duration_distance_matrix_dst_tags(k)`` in - matrix i. - - Tags correspond to - [VisitRequest.tags][google.maps.routeoptimization.v1.Shipment.VisitRequest.tags] - or - [Vehicle.start_tags][google.maps.routeoptimization.v1.Vehicle.start_tags]. - A given ``VisitRequest`` or ``Vehicle`` must match exactly - one tag in this field. Note that a ``Vehicle``'s source, - destination and matrix tags may be the same; similarly a - ``VisitRequest``'s source and destination tags may be the - same. All tags must be different and cannot be empty - strings. If this field is not empty, then - ``duration_distance_matrices`` must not be empty. - transition_attributes (MutableSequence[google.maps.routeoptimization_v1.types.TransitionAttributes]): - Transition attributes added to the model. - shipment_type_incompatibilities (MutableSequence[google.maps.routeoptimization_v1.types.ShipmentTypeIncompatibility]): - Sets of incompatible shipment_types (see - ``ShipmentTypeIncompatibility``). - shipment_type_requirements (MutableSequence[google.maps.routeoptimization_v1.types.ShipmentTypeRequirement]): - Sets of ``shipment_type`` requirements (see - ``ShipmentTypeRequirement``). - precedence_rules (MutableSequence[google.maps.routeoptimization_v1.types.ShipmentModel.PrecedenceRule]): - Set of precedence rules which must be - enforced in the model. - """ - - class DurationDistanceMatrix(proto.Message): - r"""Specifies a duration and distance matrix from visit and - vehicle start locations to visit and vehicle end locations. - - Attributes: - rows (MutableSequence[google.maps.routeoptimization_v1.types.ShipmentModel.DurationDistanceMatrix.Row]): - Specifies the rows of the duration and distance matrix. It - must have as many elements as - [ShipmentModel.duration_distance_matrix_src_tags][google.maps.routeoptimization.v1.ShipmentModel.duration_distance_matrix_src_tags]. - vehicle_start_tag (str): - Tag defining to which vehicles this duration and distance - matrix applies. If empty, this applies to all vehicles, and - there can only be a single matrix. - - Each vehicle start must match exactly one matrix, i.e. - exactly one of their ``start_tags`` field must match the - ``vehicle_start_tag`` of a matrix (and of that matrix only). - - All matrices must have a different ``vehicle_start_tag``. - """ - - class Row(proto.Message): - r"""Specifies a row of the duration and distance matrix. - - Attributes: - durations (MutableSequence[google.protobuf.duration_pb2.Duration]): - Duration values for a given row. It must have as many - elements as - [ShipmentModel.duration_distance_matrix_dst_tags][google.maps.routeoptimization.v1.ShipmentModel.duration_distance_matrix_dst_tags]. - meters (MutableSequence[float]): - Distance values for a given row. If no costs or constraints - refer to distances in the model, this can be left empty; - otherwise it must have as many elements as ``durations``. - """ - - durations: MutableSequence[duration_pb2.Duration] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - meters: MutableSequence[float] = proto.RepeatedField( - proto.DOUBLE, - number=2, - ) - - rows: MutableSequence['ShipmentModel.DurationDistanceMatrix.Row'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ShipmentModel.DurationDistanceMatrix.Row', - ) - vehicle_start_tag: str = proto.Field( - proto.STRING, - number=2, - ) - - class PrecedenceRule(proto.Message): - r"""A precedence rule between two events (each event is the pickup or - the delivery of a shipment): the "second" event has to start at - least ``offset_duration`` after "first" has started. - - Several precedences can refer to the same (or related) events, e.g., - "pickup of B happens after delivery of A" and "pickup of C happens - after pickup of B". - - Furthermore, precedences only apply when both shipments are - performed and are otherwise ignored. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - first_index (int): - Shipment index of the "first" event. This - field must be specified. - - This field is a member of `oneof`_ ``_first_index``. - first_is_delivery (bool): - Indicates if the "first" event is a delivery. - second_index (int): - Shipment index of the "second" event. This - field must be specified. - - This field is a member of `oneof`_ ``_second_index``. - second_is_delivery (bool): - Indicates if the "second" event is a - delivery. - offset_duration (google.protobuf.duration_pb2.Duration): - The offset between the "first" and "second" - event. It can be negative. - """ - - first_index: int = proto.Field( - proto.INT32, - number=1, - optional=True, - ) - first_is_delivery: bool = proto.Field( - proto.BOOL, - number=3, - ) - second_index: int = proto.Field( - proto.INT32, - number=2, - optional=True, - ) - second_is_delivery: bool = proto.Field( - proto.BOOL, - number=4, - ) - offset_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=5, - message=duration_pb2.Duration, - ) - - shipments: MutableSequence['Shipment'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Shipment', - ) - vehicles: MutableSequence['Vehicle'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Vehicle', - ) - max_active_vehicles: int = proto.Field( - proto.INT32, - number=4, - optional=True, - ) - global_start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - global_end_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - global_duration_cost_per_hour: float = proto.Field( - proto.DOUBLE, - number=7, - ) - duration_distance_matrices: MutableSequence[DurationDistanceMatrix] = proto.RepeatedField( - proto.MESSAGE, - number=8, - message=DurationDistanceMatrix, - ) - duration_distance_matrix_src_tags: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=9, - ) - duration_distance_matrix_dst_tags: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=10, - ) - transition_attributes: MutableSequence['TransitionAttributes'] = proto.RepeatedField( - proto.MESSAGE, - number=11, - message='TransitionAttributes', - ) - shipment_type_incompatibilities: MutableSequence['ShipmentTypeIncompatibility'] = proto.RepeatedField( - proto.MESSAGE, - number=12, - message='ShipmentTypeIncompatibility', - ) - shipment_type_requirements: MutableSequence['ShipmentTypeRequirement'] = proto.RepeatedField( - proto.MESSAGE, - number=13, - message='ShipmentTypeRequirement', - ) - precedence_rules: MutableSequence[PrecedenceRule] = proto.RepeatedField( - proto.MESSAGE, - number=14, - message=PrecedenceRule, - ) - - -class Shipment(proto.Message): - r"""The shipment of a single item, from one of its pickups to one - of its deliveries. For the shipment to be considered as - performed, a unique vehicle must visit one of its pickup - locations (and decrease its spare capacities accordingly), then - visit one of its delivery locations later on (and therefore - re-increase its spare capacities accordingly). - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - display_name (str): - The user-defined display name of the - shipment. It can be up to 63 characters long and - may use UTF-8 characters. - pickups (MutableSequence[google.maps.routeoptimization_v1.types.Shipment.VisitRequest]): - Set of pickup alternatives associated to the - shipment. If not specified, the vehicle only - needs to visit a location corresponding to the - deliveries. - deliveries (MutableSequence[google.maps.routeoptimization_v1.types.Shipment.VisitRequest]): - Set of delivery alternatives associated to - the shipment. If not specified, the vehicle only - needs to visit a location corresponding to the - pickups. - load_demands (MutableMapping[str, google.maps.routeoptimization_v1.types.Shipment.Load]): - Load demands of the shipment (for example weight, volume, - number of pallets etc). The keys in the map should be - identifiers describing the type of the corresponding load, - ideally also including the units. For example: "weight_kg", - "volume_gallons", "pallet_count", etc. If a given key does - not appear in the map, the corresponding load is considered - as null. - penalty_cost (float): - If the shipment is not completed, this penalty is added to - the overall cost of the routes. A shipment is considered - completed if one of its pickup and delivery alternatives is - visited. The cost may be expressed in the same unit used for - all other cost-related fields in the model and must be - positive. - - *IMPORTANT*: If this penalty is not specified, it is - considered infinite, i.e. the shipment must be completed. - - This field is a member of `oneof`_ ``_penalty_cost``. - allowed_vehicle_indices (MutableSequence[int]): - The set of vehicles that may perform this shipment. If - empty, all vehicles may perform it. Vehicles are given by - their index in the ``ShipmentModel``'s ``vehicles`` list. - costs_per_vehicle (MutableSequence[float]): - Specifies the cost that is incurred when this shipment is - delivered by each vehicle. If specified, it must have - EITHER: - - - the same number of elements as - ``costs_per_vehicle_indices``. ``costs_per_vehicle[i]`` - corresponds to vehicle ``costs_per_vehicle_indices[i]`` - of the model. - - the same number of elements as there are vehicles in the - model. The i-th element corresponds to vehicle #i of the - model. - - These costs must be in the same unit as ``penalty_cost`` and - must not be negative. Leave this field empty, if there are - no such costs. - costs_per_vehicle_indices (MutableSequence[int]): - Indices of the vehicles to which ``costs_per_vehicle`` - applies. If non-empty, it must have the same number of - elements as ``costs_per_vehicle``. A vehicle index may not - be specified more than once. If a vehicle is excluded from - ``costs_per_vehicle_indices``, its cost is zero. - pickup_to_delivery_relative_detour_limit (float): - Specifies the maximum relative detour time compared to the - shortest path from pickup to delivery. If specified, it must - be nonnegative, and the shipment must contain at least a - pickup and a delivery. - - For example, let t be the shortest time taken to go from the - selected pickup alternative directly to the selected - delivery alternative. Then setting - ``pickup_to_delivery_relative_detour_limit`` enforces: - - :: - - start_time(delivery) - start_time(pickup) <= - std::ceil(t * (1.0 + pickup_to_delivery_relative_detour_limit)) - - If both relative and absolute limits are specified on the - same shipment, the more constraining limit is used for each - possible pickup/delivery pair. As of 2017/10, detours are - only supported when travel durations do not depend on - vehicles. - - This field is a member of `oneof`_ ``_pickup_to_delivery_relative_detour_limit``. - pickup_to_delivery_absolute_detour_limit (google.protobuf.duration_pb2.Duration): - Specifies the maximum absolute detour time compared to the - shortest path from pickup to delivery. If specified, it must - be nonnegative, and the shipment must contain at least a - pickup and a delivery. - - For example, let t be the shortest time taken to go from the - selected pickup alternative directly to the selected - delivery alternative. Then setting - ``pickup_to_delivery_absolute_detour_limit`` enforces: - - :: - - start_time(delivery) - start_time(pickup) <= - t + pickup_to_delivery_absolute_detour_limit - - If both relative and absolute limits are specified on the - same shipment, the more constraining limit is used for each - possible pickup/delivery pair. As of 2017/10, detours are - only supported when travel durations do not depend on - vehicles. - pickup_to_delivery_time_limit (google.protobuf.duration_pb2.Duration): - Specifies the maximum duration from start of - pickup to start of delivery of a shipment. If - specified, it must be nonnegative, and the - shipment must contain at least a pickup and a - delivery. This does not depend on which - alternatives are selected for pickup and - delivery, nor on vehicle speed. This can be - specified alongside maximum detour constraints: - the solution will respect both specifications. - shipment_type (str): - Non-empty string specifying a "type" for this shipment. This - feature can be used to define incompatibilities or - requirements between ``shipment_types`` (see - ``shipment_type_incompatibilities`` and - ``shipment_type_requirements`` in ``ShipmentModel``). - - Differs from ``visit_types`` which is specified for a single - visit: All pickup/deliveries belonging to the same shipment - share the same ``shipment_type``. - label (str): - Specifies a label for this shipment. This label is reported - in the response in the ``shipment_label`` of the - corresponding - [ShipmentRoute.Visit][google.maps.routeoptimization.v1.ShipmentRoute.Visit]. - ignore (bool): - If true, skip this shipment, but don't apply a - ``penalty_cost``. - - Ignoring a shipment results in a validation error when there - are any ``shipment_type_requirements`` in the model. - - Ignoring a shipment that is performed in - ``injected_first_solution_routes`` or - ``injected_solution_constraint`` is permitted; the solver - removes the related pickup/delivery visits from the - performing route. ``precedence_rules`` that reference - ignored shipments will also be ignored. - """ - - class VisitRequest(proto.Message): - r"""Request for a visit which can be done by a vehicle: it has a - geo-location (or two, see below), opening and closing times - represented by time windows, and a service duration time (time - spent by the vehicle once it has arrived to pickup or drop off - goods). - - Attributes: - arrival_location (google.type.latlng_pb2.LatLng): - The geo-location where the vehicle arrives when performing - this ``VisitRequest``. If the shipment model has duration - distance matrices, ``arrival_location`` must not be - specified. - arrival_waypoint (google.maps.routeoptimization_v1.types.Waypoint): - The waypoint where the vehicle arrives when performing this - ``VisitRequest``. If the shipment model has duration - distance matrices, ``arrival_waypoint`` must not be - specified. - departure_location (google.type.latlng_pb2.LatLng): - The geo-location where the vehicle departs after completing - this ``VisitRequest``. Can be omitted if it is the same as - ``arrival_location``. If the shipment model has duration - distance matrices, ``departure_location`` must not be - specified. - departure_waypoint (google.maps.routeoptimization_v1.types.Waypoint): - The waypoint where the vehicle departs after completing this - ``VisitRequest``. Can be omitted if it is the same as - ``arrival_waypoint``. If the shipment model has duration - distance matrices, ``departure_waypoint`` must not be - specified. - tags (MutableSequence[str]): - Specifies tags attached to the visit request. - Empty or duplicate strings are not allowed. - time_windows (MutableSequence[google.maps.routeoptimization_v1.types.TimeWindow]): - Time windows which constrain the arrival time at a visit. - Note that a vehicle may depart outside of the arrival time - window, i.e. arrival time + duration do not need to be - inside a time window. This can result in waiting time if the - vehicle arrives before - [TimeWindow.start_time][google.maps.routeoptimization.v1.TimeWindow.start_time]. - - The absence of ``TimeWindow`` means that the vehicle can - perform this visit at any time. - - Time windows must be disjoint, i.e. no time window must - overlap with or be adjacent to another, and they must be in - increasing order. - - ``cost_per_hour_after_soft_end_time`` and ``soft_end_time`` - can only be set if there is a single time window. - duration (google.protobuf.duration_pb2.Duration): - Duration of the visit, i.e. time spent by the vehicle - between arrival and departure (to be added to the possible - waiting time; see ``time_windows``). - cost (float): - Cost to service this visit request on a vehicle route. This - can be used to pay different costs for each alternative - pickup or delivery of a shipment. This cost must be in the - same unit as ``Shipment.penalty_cost`` and must not be - negative. - load_demands (MutableMapping[str, google.maps.routeoptimization_v1.types.Shipment.Load]): - Load demands of this visit request. This is just like - [Shipment.load_demands][google.maps.routeoptimization.v1.Shipment.load_demands] - field, except that it only applies to this - [VisitRequest][google.maps.routeoptimization.v1.Shipment.VisitRequest] - instead of the whole - [Shipment][google.maps.routeoptimization.v1.Shipment]. The - demands listed here are added to the demands listed in - [Shipment.load_demands][google.maps.routeoptimization.v1.Shipment.load_demands]. - visit_types (MutableSequence[str]): - Specifies the types of the visit. This may be used to - allocate additional time required for a vehicle to complete - this visit (see - [Vehicle.extra_visit_duration_for_visit_type][google.maps.routeoptimization.v1.Vehicle.extra_visit_duration_for_visit_type]). - - A type can only appear once. - label (str): - Specifies a label for this ``VisitRequest``. This label is - reported in the response as ``visit_label`` in the - corresponding - [ShipmentRoute.Visit][google.maps.routeoptimization.v1.ShipmentRoute.Visit]. - """ - - arrival_location: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=1, - message=latlng_pb2.LatLng, - ) - arrival_waypoint: 'Waypoint' = proto.Field( - proto.MESSAGE, - number=2, - message='Waypoint', - ) - departure_location: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=3, - message=latlng_pb2.LatLng, - ) - departure_waypoint: 'Waypoint' = proto.Field( - proto.MESSAGE, - number=4, - message='Waypoint', - ) - tags: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - time_windows: MutableSequence['TimeWindow'] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message='TimeWindow', - ) - duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=7, - message=duration_pb2.Duration, - ) - cost: float = proto.Field( - proto.DOUBLE, - number=8, - ) - load_demands: MutableMapping[str, 'Shipment.Load'] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=12, - message='Shipment.Load', - ) - visit_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=10, - ) - label: str = proto.Field( - proto.STRING, - number=11, - ) - - class Load(proto.Message): - r"""When performing a visit, a predefined amount may be added to the - vehicle load if it's a pickup, or subtracted if it's a delivery. - This message defines such amount. See - [load_demands][google.maps.routeoptimization.v1.Shipment.load_demands]. - - Attributes: - amount (int): - The amount by which the load of the vehicle - performing the corresponding visit will vary. - Since it is an integer, users are advised to - choose an appropriate unit to avoid loss of - precision. Must be ≥ 0. - """ - - amount: int = proto.Field( - proto.INT64, - number=2, - ) - - display_name: str = proto.Field( - proto.STRING, - number=16, - ) - pickups: MutableSequence[VisitRequest] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=VisitRequest, - ) - deliveries: MutableSequence[VisitRequest] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=VisitRequest, - ) - load_demands: MutableMapping[str, Load] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=14, - message=Load, - ) - penalty_cost: float = proto.Field( - proto.DOUBLE, - number=4, - optional=True, - ) - allowed_vehicle_indices: MutableSequence[int] = proto.RepeatedField( - proto.INT32, - number=5, - ) - costs_per_vehicle: MutableSequence[float] = proto.RepeatedField( - proto.DOUBLE, - number=6, - ) - costs_per_vehicle_indices: MutableSequence[int] = proto.RepeatedField( - proto.INT32, - number=7, - ) - pickup_to_delivery_relative_detour_limit: float = proto.Field( - proto.DOUBLE, - number=8, - optional=True, - ) - pickup_to_delivery_absolute_detour_limit: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=9, - message=duration_pb2.Duration, - ) - pickup_to_delivery_time_limit: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=10, - message=duration_pb2.Duration, - ) - shipment_type: str = proto.Field( - proto.STRING, - number=11, - ) - label: str = proto.Field( - proto.STRING, - number=12, - ) - ignore: bool = proto.Field( - proto.BOOL, - number=13, - ) - - -class ShipmentTypeIncompatibility(proto.Message): - r"""Specifies incompatibilties between shipments depending on their - shipment_type. The appearance of incompatible shipments on the same - route is restricted based on the incompatibility mode. - - Attributes: - types (MutableSequence[str]): - List of incompatible types. Two shipments having different - ``shipment_types`` among those listed are "incompatible". - incompatibility_mode (google.maps.routeoptimization_v1.types.ShipmentTypeIncompatibility.IncompatibilityMode): - Mode applied to the incompatibility. - """ - class IncompatibilityMode(proto.Enum): - r"""Modes defining how the appearance of incompatible shipments - are restricted on the same route. - - Values: - INCOMPATIBILITY_MODE_UNSPECIFIED (0): - Unspecified incompatibility mode. This value - should never be used. - NOT_PERFORMED_BY_SAME_VEHICLE (1): - In this mode, two shipments with incompatible - types can never share the same vehicle. - NOT_IN_SAME_VEHICLE_SIMULTANEOUSLY (2): - For two shipments with incompatible types with the - ``NOT_IN_SAME_VEHICLE_SIMULTANEOUSLY`` incompatibility mode: - - - If both are pickups only (no deliveries) or deliveries - only (no pickups), they cannot share the same vehicle at - all. - - If one of the shipments has a delivery and the other a - pickup, the two shipments can share the same vehicle iff - the former shipment is delivered before the latter is - picked up. - """ - INCOMPATIBILITY_MODE_UNSPECIFIED = 0 - NOT_PERFORMED_BY_SAME_VEHICLE = 1 - NOT_IN_SAME_VEHICLE_SIMULTANEOUSLY = 2 - - types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - incompatibility_mode: IncompatibilityMode = proto.Field( - proto.ENUM, - number=2, - enum=IncompatibilityMode, - ) - - -class ShipmentTypeRequirement(proto.Message): - r"""Specifies requirements between shipments based on their - shipment_type. The specifics of the requirement are defined by the - requirement mode. - - Attributes: - required_shipment_type_alternatives (MutableSequence[str]): - List of alternative shipment types required by the - ``dependent_shipment_types``. - dependent_shipment_types (MutableSequence[str]): - All shipments with a type in the - ``dependent_shipment_types`` field require at least one - shipment of type ``required_shipment_type_alternatives`` to - be visited on the same route. - - NOTE: Chains of requirements such that a ``shipment_type`` - depends on itself are not allowed. - requirement_mode (google.maps.routeoptimization_v1.types.ShipmentTypeRequirement.RequirementMode): - Mode applied to the requirement. - """ - class RequirementMode(proto.Enum): - r"""Modes defining the appearance of dependent shipments on a - route. - - Values: - REQUIREMENT_MODE_UNSPECIFIED (0): - Unspecified requirement mode. This value - should never be used. - PERFORMED_BY_SAME_VEHICLE (1): - In this mode, all "dependent" shipments must - share the same vehicle as at least one of their - "required" shipments. - IN_SAME_VEHICLE_AT_PICKUP_TIME (2): - With the ``IN_SAME_VEHICLE_AT_PICKUP_TIME`` mode, all - "dependent" shipments need to have at least one "required" - shipment on their vehicle at the time of their pickup. - - A "dependent" shipment pickup must therefore have either: - - - A delivery-only "required" shipment delivered on the - route after, or - - A "required" shipment picked up on the route before it, - and if the "required" shipment has a delivery, this - delivery must be performed after the "dependent" - shipment's pickup. - IN_SAME_VEHICLE_AT_DELIVERY_TIME (3): - Same as before, except the "dependent" shipments need to - have a "required" shipment on their vehicle at the time of - their *delivery*. - """ - REQUIREMENT_MODE_UNSPECIFIED = 0 - PERFORMED_BY_SAME_VEHICLE = 1 - IN_SAME_VEHICLE_AT_PICKUP_TIME = 2 - IN_SAME_VEHICLE_AT_DELIVERY_TIME = 3 - - required_shipment_type_alternatives: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - dependent_shipment_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - requirement_mode: RequirementMode = proto.Field( - proto.ENUM, - number=3, - enum=RequirementMode, - ) - - -class RouteModifiers(proto.Message): - r"""Encapsulates a set of optional conditions to satisfy when - calculating vehicle routes. This is similar to ``RouteModifiers`` in - the Google Maps Platform Routes Preferred API; see: - https://developers.google.com/maps/documentation/routes/reference/rest/v2/RouteModifiers. - - Attributes: - avoid_tolls (bool): - Specifies whether to avoid toll roads where - reasonable. Preference will be given to routes - not containing toll roads. Applies only to - motorized travel modes. - avoid_highways (bool): - Specifies whether to avoid highways where - reasonable. Preference will be given to routes - not containing highways. Applies only to - motorized travel modes. - avoid_ferries (bool): - Specifies whether to avoid ferries where - reasonable. Preference will be given to routes - not containing travel by ferries. Applies only - to motorized travel modes. - avoid_indoor (bool): - Optional. Specifies whether to avoid navigating indoors - where reasonable. Preference will be given to routes not - containing indoor navigation. Applies only to the - ``WALKING`` travel mode. - """ - - avoid_tolls: bool = proto.Field( - proto.BOOL, - number=2, - ) - avoid_highways: bool = proto.Field( - proto.BOOL, - number=3, - ) - avoid_ferries: bool = proto.Field( - proto.BOOL, - number=4, - ) - avoid_indoor: bool = proto.Field( - proto.BOOL, - number=5, - ) - - -class Vehicle(proto.Message): - r"""Models a vehicle in a shipment problem. Solving a shipment problem - will build a route starting from ``start_location`` and ending at - ``end_location`` for this vehicle. A route is a sequence of visits - (see ``ShipmentRoute``). - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - display_name (str): - The user-defined display name of the vehicle. - It can be up to 63 characters long and may use - UTF-8 characters. - travel_mode (google.maps.routeoptimization_v1.types.Vehicle.TravelMode): - The travel mode which affects the roads usable by the - vehicle and its speed. See also - ``travel_duration_multiple``. - route_modifiers (google.maps.routeoptimization_v1.types.RouteModifiers): - A set of conditions to satisfy that affect - the way routes are calculated for the given - vehicle. - start_location (google.type.latlng_pb2.LatLng): - Geographic location where the vehicle starts before picking - up any shipments. If not specified, the vehicle starts at - its first pickup. If the shipment model has duration and - distance matrices, ``start_location`` must not be specified. - start_waypoint (google.maps.routeoptimization_v1.types.Waypoint): - Waypoint representing a geographic location where the - vehicle starts before picking up any shipments. If neither - ``start_waypoint`` nor ``start_location`` is specified, the - vehicle starts at its first pickup. If the shipment model - has duration and distance matrices, ``start_waypoint`` must - not be specified. - end_location (google.type.latlng_pb2.LatLng): - Geographic location where the vehicle ends after it has - completed its last ``VisitRequest``. If not specified the - vehicle's ``ShipmentRoute`` ends immediately when it - completes its last ``VisitRequest``. If the shipment model - has duration and distance matrices, ``end_location`` must - not be specified. - end_waypoint (google.maps.routeoptimization_v1.types.Waypoint): - Waypoint representing a geographic location where the - vehicle ends after it has completed its last - ``VisitRequest``. If neither ``end_waypoint`` nor - ``end_location`` is specified, the vehicle's - ``ShipmentRoute`` ends immediately when it completes its - last ``VisitRequest``. If the shipment model has duration - and distance matrices, ``end_waypoint`` must not be - specified. - start_tags (MutableSequence[str]): - Specifies tags attached to the start of the - vehicle's route. - Empty or duplicate strings are not allowed. - end_tags (MutableSequence[str]): - Specifies tags attached to the end of the - vehicle's route. - Empty or duplicate strings are not allowed. - start_time_windows (MutableSequence[google.maps.routeoptimization_v1.types.TimeWindow]): - Time windows during which the vehicle may depart its start - location. They must be within the global time limits (see - [ShipmentModel.global_*][google.maps.routeoptimization.v1.ShipmentModel.global_start_time] - fields). If unspecified, there is no limitation besides - those global time limits. - - Time windows belonging to the same repeated field must be - disjoint, i.e. no time window can overlap with or be - adjacent to another, and they must be in chronological - order. - - ``cost_per_hour_after_soft_end_time`` and ``soft_end_time`` - can only be set if there is a single time window. - end_time_windows (MutableSequence[google.maps.routeoptimization_v1.types.TimeWindow]): - Time windows during which the vehicle may arrive at its end - location. They must be within the global time limits (see - [ShipmentModel.global_*][google.maps.routeoptimization.v1.ShipmentModel.global_start_time] - fields). If unspecified, there is no limitation besides - those global time limits. - - Time windows belonging to the same repeated field must be - disjoint, i.e. no time window can overlap with or be - adjacent to another, and they must be in chronological - order. - - ``cost_per_hour_after_soft_end_time`` and ``soft_end_time`` - can only be set if there is a single time window. - travel_duration_multiple (float): - Specifies a multiplicative factor that can be used to - increase or decrease travel times of this vehicle. For - example, setting this to 2.0 means that this vehicle is - slower and has travel times that are twice what they are for - standard vehicles. This multiple does not affect visit - durations. It does affect cost if ``cost_per_hour`` or - ``cost_per_traveled_hour`` are specified. This must be in - the range [0.001, 1000.0]. If unset, the vehicle is - standard, and this multiple is considered 1.0. - - WARNING: Travel times will be rounded to the nearest second - after this multiple is applied but before performing any - numerical operations, thus, a small multiple may result in a - loss of precision. - - See also ``extra_visit_duration_for_visit_type`` below. - - This field is a member of `oneof`_ ``_travel_duration_multiple``. - unloading_policy (google.maps.routeoptimization_v1.types.Vehicle.UnloadingPolicy): - Unloading policy enforced on the vehicle. - load_limits (MutableMapping[str, google.maps.routeoptimization_v1.types.Vehicle.LoadLimit]): - Capacities of the vehicle (weight, volume, # of pallets for - example). The keys in the map are the identifiers of the - type of load, consistent with the keys of the - [Shipment.load_demands][google.maps.routeoptimization.v1.Shipment.load_demands] - field. If a given key is absent from this map, the - corresponding capacity is considered to be limitless. - cost_per_hour (float): - Vehicle costs: all costs add up and must be in the same unit - as - [Shipment.penalty_cost][google.maps.routeoptimization.v1.Shipment.penalty_cost]. - - Cost per hour of the vehicle route. This cost is applied to - the total time taken by the route, and includes travel time, - waiting time, and visit time. Using ``cost_per_hour`` - instead of just ``cost_per_traveled_hour`` may result in - additional latency. - cost_per_traveled_hour (float): - Cost per traveled hour of the vehicle route. This cost is - applied only to travel time taken by the route (i.e., that - reported in - [ShipmentRoute.transitions][google.maps.routeoptimization.v1.ShipmentRoute.transitions]), - and excludes waiting time and visit time. - cost_per_kilometer (float): - Cost per kilometer of the vehicle route. This cost is - applied to the distance reported in the - [ShipmentRoute.transitions][google.maps.routeoptimization.v1.ShipmentRoute.transitions] - and does not apply to any distance implicitly traveled from - the ``arrival_location`` to the ``departure_location`` of a - single ``VisitRequest``. - fixed_cost (float): - Fixed cost applied if this vehicle is used to - handle a shipment. - used_if_route_is_empty (bool): - This field only applies to vehicles when their route does - not serve any shipments. It indicates if the vehicle should - be considered as used or not in this case. - - If true, the vehicle goes from its start to its end location - even if it doesn't serve any shipments, and time and - distance costs resulting from its start --> end travel are - taken into account. - - Otherwise, it doesn't travel from its start to its end - location, and no ``break_rule`` or delay (from - ``TransitionAttributes``) are scheduled for this vehicle. In - this case, the vehicle's ``ShipmentRoute`` doesn't contain - any information except for the vehicle index and label. - route_duration_limit (google.maps.routeoptimization_v1.types.Vehicle.DurationLimit): - Limit applied to the total duration of the vehicle's route. - In a given ``OptimizeToursResponse``, the route duration of - a vehicle is the difference between its ``vehicle_end_time`` - and ``vehicle_start_time``. - travel_duration_limit (google.maps.routeoptimization_v1.types.Vehicle.DurationLimit): - Limit applied to the travel duration of the vehicle's route. - In a given ``OptimizeToursResponse``, the route travel - duration is the sum of all its - [transitions.travel_duration][google.maps.routeoptimization.v1.ShipmentRoute.Transition.travel_duration]. - route_distance_limit (google.maps.routeoptimization_v1.types.DistanceLimit): - Limit applied to the total distance of the vehicle's route. - In a given ``OptimizeToursResponse``, the route distance is - the sum of all its - [transitions.travel_distance_meters][google.maps.routeoptimization.v1.ShipmentRoute.Transition.travel_distance_meters]. - extra_visit_duration_for_visit_type (MutableMapping[str, google.protobuf.duration_pb2.Duration]): - Specifies a map from visit_types strings to durations. The - duration is time in addition to - [VisitRequest.duration][google.maps.routeoptimization.v1.Shipment.VisitRequest.duration] - to be taken at visits with the specified ``visit_types``. - This extra visit duration adds cost if ``cost_per_hour`` is - specified. Keys (i.e. ``visit_types``) cannot be empty - strings. - - If a visit request has multiple types, a duration will be - added for each type in the map. - break_rule (google.maps.routeoptimization_v1.types.BreakRule): - Describes the break schedule to be enforced - on this vehicle. If empty, no breaks will be - scheduled for this vehicle. - label (str): - Specifies a label for this vehicle. This label is reported - in the response as the ``vehicle_label`` of the - corresponding - [ShipmentRoute][google.maps.routeoptimization.v1.ShipmentRoute]. - ignore (bool): - If true, ``used_if_route_is_empty`` must be false, and this - vehicle will remain unused. - - If a shipment is performed by an ignored vehicle in - ``injected_first_solution_routes``, it is skipped in the - first solution but is free to be performed in the response. - - If a shipment is performed by an ignored vehicle in - ``injected_solution_constraint`` and any related - pickup/delivery is constrained to remain on the vehicle - (i.e., not relaxed to level ``RELAX_ALL_AFTER_THRESHOLD``), - it is skipped in the response. If a shipment has a non-empty - ``allowed_vehicle_indices`` field and all of the allowed - vehicles are ignored, it is skipped in the response. - """ - class TravelMode(proto.Enum): - r"""Travel modes which can be used by vehicles. - - These should be a subset of the Google Maps Platform Routes - Preferred API travel modes, see: - https://developers.google.com/maps/documentation/routes_preferred/reference/rest/Shared.Types/RouteTravelMode. - - Values: - TRAVEL_MODE_UNSPECIFIED (0): - Unspecified travel mode, equivalent to ``DRIVING``. - DRIVING (1): - Travel mode corresponding to driving - directions (car, ...). - WALKING (2): - Travel mode corresponding to walking - directions. - """ - TRAVEL_MODE_UNSPECIFIED = 0 - DRIVING = 1 - WALKING = 2 - - class UnloadingPolicy(proto.Enum): - r"""Policy on how a vehicle can be unloaded. Applies only to shipments - having both a pickup and a delivery. - - Other shipments are free to occur anywhere on the route independent - of ``unloading_policy``. - - Values: - UNLOADING_POLICY_UNSPECIFIED (0): - Unspecified unloading policy; deliveries must - just occur after their corresponding pickups. - LAST_IN_FIRST_OUT (1): - Deliveries must occur in reverse order of - pickups - FIRST_IN_FIRST_OUT (2): - Deliveries must occur in the same order as - pickups - """ - UNLOADING_POLICY_UNSPECIFIED = 0 - LAST_IN_FIRST_OUT = 1 - FIRST_IN_FIRST_OUT = 2 - - class LoadLimit(proto.Message): - r"""Defines a load limit applying to a vehicle, e.g. "this truck may - only carry up to 3500 kg". See - [load_limits][google.maps.routeoptimization.v1.Vehicle.load_limits]. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - max_load (int): - The maximum acceptable amount of load. - - This field is a member of `oneof`_ ``_max_load``. - soft_max_load (int): - A soft limit of the load. See - [cost_per_unit_above_soft_max][google.maps.routeoptimization.v1.Vehicle.LoadLimit.cost_per_unit_above_soft_max]. - cost_per_unit_above_soft_max (float): - If the load ever exceeds - [soft_max_load][google.maps.routeoptimization.v1.Vehicle.LoadLimit.soft_max_load] - along this vehicle's route, the following cost penalty - applies (only once per vehicle): (load - - [soft_max_load][google.maps.routeoptimization.v1.Vehicle.LoadLimit.soft_max_load]) - - - [cost_per_unit_above_soft_max][google.maps.routeoptimization.v1.Vehicle.LoadLimit.cost_per_unit_above_soft_max]. - All costs add up and must be in the same unit as - [Shipment.penalty_cost][google.maps.routeoptimization.v1.Shipment.penalty_cost]. - start_load_interval (google.maps.routeoptimization_v1.types.Vehicle.LoadLimit.Interval): - The acceptable load interval of the vehicle - at the start of the route. - end_load_interval (google.maps.routeoptimization_v1.types.Vehicle.LoadLimit.Interval): - The acceptable load interval of the vehicle - at the end of the route. - """ - - class Interval(proto.Message): - r"""Interval of acceptable load amounts. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - min_ (int): - A minimum acceptable load. Must be ≥ 0. If they're both - specified, - [min][google.maps.routeoptimization.v1.Vehicle.LoadLimit.Interval.min] - must be ≤ - [max][google.maps.routeoptimization.v1.Vehicle.LoadLimit.Interval.max]. - max_ (int): - A maximum acceptable load. Must be ≥ 0. If unspecified, the - maximum load is unrestricted by this message. If they're - both specified, - [min][google.maps.routeoptimization.v1.Vehicle.LoadLimit.Interval.min] - must be ≤ - [max][google.maps.routeoptimization.v1.Vehicle.LoadLimit.Interval.max]. - - This field is a member of `oneof`_ ``_max``. - """ - - min_: int = proto.Field( - proto.INT64, - number=1, - ) - max_: int = proto.Field( - proto.INT64, - number=2, - optional=True, - ) - - max_load: int = proto.Field( - proto.INT64, - number=1, - optional=True, - ) - soft_max_load: int = proto.Field( - proto.INT64, - number=2, - ) - cost_per_unit_above_soft_max: float = proto.Field( - proto.DOUBLE, - number=3, - ) - start_load_interval: 'Vehicle.LoadLimit.Interval' = proto.Field( - proto.MESSAGE, - number=4, - message='Vehicle.LoadLimit.Interval', - ) - end_load_interval: 'Vehicle.LoadLimit.Interval' = proto.Field( - proto.MESSAGE, - number=5, - message='Vehicle.LoadLimit.Interval', - ) - - class DurationLimit(proto.Message): - r"""A limit defining a maximum duration of the route of a - vehicle. It can be either hard or soft. - - When a soft limit field is defined, both the soft max threshold - and its associated cost must be defined together. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - max_duration (google.protobuf.duration_pb2.Duration): - A hard limit constraining the duration to be at most - max_duration. - soft_max_duration (google.protobuf.duration_pb2.Duration): - A soft limit not enforcing a maximum duration limit, but - when violated makes the route incur a cost. This cost adds - up to other costs defined in the model, with the same unit. - - If defined, ``soft_max_duration`` must be nonnegative. If - max_duration is also defined, ``soft_max_duration`` must be - less than max_duration. - cost_per_hour_after_soft_max (float): - Cost per hour incurred if the ``soft_max_duration`` - threshold is violated. The additional cost is 0 if the - duration is under the threshold, otherwise the cost depends - on the duration as follows: - - :: - - cost_per_hour_after_soft_max * (duration - soft_max_duration) - - The cost must be nonnegative. - - This field is a member of `oneof`_ ``_cost_per_hour_after_soft_max``. - quadratic_soft_max_duration (google.protobuf.duration_pb2.Duration): - A soft limit not enforcing a maximum duration limit, but - when violated makes the route incur a cost, quadratic in the - duration. This cost adds up to other costs defined in the - model, with the same unit. - - If defined, ``quadratic_soft_max_duration`` must be - nonnegative. If ``max_duration`` is also defined, - ``quadratic_soft_max_duration`` must be less than - ``max_duration``, and the difference must be no larger than - one day: - - :: - - `max_duration - quadratic_soft_max_duration <= 86400 seconds` - cost_per_square_hour_after_quadratic_soft_max (float): - Cost per square hour incurred if the - ``quadratic_soft_max_duration`` threshold is violated. - - The additional cost is 0 if the duration is under the - threshold, otherwise the cost depends on the duration as - follows: - - :: - - cost_per_square_hour_after_quadratic_soft_max * - (duration - quadratic_soft_max_duration)^2 - - The cost must be nonnegative. - - This field is a member of `oneof`_ ``_cost_per_square_hour_after_quadratic_soft_max``. - """ - - max_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - soft_max_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - cost_per_hour_after_soft_max: float = proto.Field( - proto.DOUBLE, - number=3, - optional=True, - ) - quadratic_soft_max_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=4, - message=duration_pb2.Duration, - ) - cost_per_square_hour_after_quadratic_soft_max: float = proto.Field( - proto.DOUBLE, - number=5, - optional=True, - ) - - display_name: str = proto.Field( - proto.STRING, - number=32, - ) - travel_mode: TravelMode = proto.Field( - proto.ENUM, - number=1, - enum=TravelMode, - ) - route_modifiers: 'RouteModifiers' = proto.Field( - proto.MESSAGE, - number=2, - message='RouteModifiers', - ) - start_location: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=3, - message=latlng_pb2.LatLng, - ) - start_waypoint: 'Waypoint' = proto.Field( - proto.MESSAGE, - number=4, - message='Waypoint', - ) - end_location: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=5, - message=latlng_pb2.LatLng, - ) - end_waypoint: 'Waypoint' = proto.Field( - proto.MESSAGE, - number=6, - message='Waypoint', - ) - start_tags: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=7, - ) - end_tags: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=8, - ) - start_time_windows: MutableSequence['TimeWindow'] = proto.RepeatedField( - proto.MESSAGE, - number=9, - message='TimeWindow', - ) - end_time_windows: MutableSequence['TimeWindow'] = proto.RepeatedField( - proto.MESSAGE, - number=10, - message='TimeWindow', - ) - travel_duration_multiple: float = proto.Field( - proto.DOUBLE, - number=11, - optional=True, - ) - unloading_policy: UnloadingPolicy = proto.Field( - proto.ENUM, - number=12, - enum=UnloadingPolicy, - ) - load_limits: MutableMapping[str, LoadLimit] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=30, - message=LoadLimit, - ) - cost_per_hour: float = proto.Field( - proto.DOUBLE, - number=16, - ) - cost_per_traveled_hour: float = proto.Field( - proto.DOUBLE, - number=17, - ) - cost_per_kilometer: float = proto.Field( - proto.DOUBLE, - number=18, - ) - fixed_cost: float = proto.Field( - proto.DOUBLE, - number=19, - ) - used_if_route_is_empty: bool = proto.Field( - proto.BOOL, - number=20, - ) - route_duration_limit: DurationLimit = proto.Field( - proto.MESSAGE, - number=21, - message=DurationLimit, - ) - travel_duration_limit: DurationLimit = proto.Field( - proto.MESSAGE, - number=22, - message=DurationLimit, - ) - route_distance_limit: 'DistanceLimit' = proto.Field( - proto.MESSAGE, - number=23, - message='DistanceLimit', - ) - extra_visit_duration_for_visit_type: MutableMapping[str, duration_pb2.Duration] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=24, - message=duration_pb2.Duration, - ) - break_rule: 'BreakRule' = proto.Field( - proto.MESSAGE, - number=25, - message='BreakRule', - ) - label: str = proto.Field( - proto.STRING, - number=27, - ) - ignore: bool = proto.Field( - proto.BOOL, - number=28, - ) - - -class TimeWindow(proto.Message): - r"""Time windows constrain the time of an event, such as the arrival - time at a visit, or the start and end time of a vehicle. - - Hard time window bounds, ``start_time`` and ``end_time``, enforce - the earliest and latest time of the event, such that - ``start_time <= event_time <= end_time``. The soft time window lower - bound, ``soft_start_time``, expresses a preference for the event to - happen at or after ``soft_start_time`` by incurring a cost - proportional to how long before soft_start_time the event occurs. - The soft time window upper bound, ``soft_end_time``, expresses a - preference for the event to happen at or before ``soft_end_time`` by - incurring a cost proportional to how long after ``soft_end_time`` - the event occurs. ``start_time``, ``end_time``, ``soft_start_time`` - and ``soft_end_time`` should be within the global time limits (see - [ShipmentModel.global_start_time][google.maps.routeoptimization.v1.ShipmentModel.global_start_time] - and - [ShipmentModel.global_end_time][google.maps.routeoptimization.v1.ShipmentModel.global_end_time]) - and should respect: - - :: - - 0 <= `start_time` <= `end_time` and - 0 <= `start_time` <= `soft_start_time` and - 0 <= `soft_end_time` <= `end_time`. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - start_time (google.protobuf.timestamp_pb2.Timestamp): - The hard time window start time. If unspecified it will be - set to ``ShipmentModel.global_start_time``. - end_time (google.protobuf.timestamp_pb2.Timestamp): - The hard time window end time. If unspecified it will be set - to ``ShipmentModel.global_end_time``. - soft_start_time (google.protobuf.timestamp_pb2.Timestamp): - The soft start time of the time window. - soft_end_time (google.protobuf.timestamp_pb2.Timestamp): - The soft end time of the time window. - cost_per_hour_before_soft_start_time (float): - A cost per hour added to other costs in the model if the - event occurs before soft_start_time, computed as: - - :: - - max(0, soft_start_time - t.seconds) - * cost_per_hour_before_soft_start_time / 3600, - t being the time of the event. - - This cost must be positive, and the field can only be set if - soft_start_time has been set. - - This field is a member of `oneof`_ ``_cost_per_hour_before_soft_start_time``. - cost_per_hour_after_soft_end_time (float): - A cost per hour added to other costs in the model if the - event occurs after ``soft_end_time``, computed as: - - :: - - max(0, t.seconds - soft_end_time.seconds) - * cost_per_hour_after_soft_end_time / 3600, - t being the time of the event. - - This cost must be positive, and the field can only be set if - ``soft_end_time`` has been set. - - This field is a member of `oneof`_ ``_cost_per_hour_after_soft_end_time``. - """ - - start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - end_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - soft_start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - soft_end_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - cost_per_hour_before_soft_start_time: float = proto.Field( - proto.DOUBLE, - number=5, - optional=True, - ) - cost_per_hour_after_soft_end_time: float = proto.Field( - proto.DOUBLE, - number=6, - optional=True, - ) - - -class DistanceLimit(proto.Message): - r"""A limit defining a maximum distance which can be traveled. It can be - either hard or soft. - - If a soft limit is defined, both ``soft_max_meters`` and - ``cost_per_kilometer_above_soft_max`` must be defined and be - nonnegative. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - max_meters (int): - A hard limit constraining the distance to be at most - max_meters. The limit must be nonnegative. - - This field is a member of `oneof`_ ``_max_meters``. - soft_max_meters (int): - A soft limit not enforcing a maximum distance limit, but - when violated results in a cost which adds up to other costs - defined in the model, with the same unit. - - If defined soft_max_meters must be less than max_meters and - must be nonnegative. - - This field is a member of `oneof`_ ``_soft_max_meters``. - cost_per_kilometer_below_soft_max (float): - Cost per kilometer incurred, increasing up to - ``soft_max_meters``, with formula: - - :: - - min(distance_meters, soft_max_meters) / 1000.0 * - cost_per_kilometer_below_soft_max. - - This cost is not supported in ``route_distance_limit``. - - This field is a member of `oneof`_ ``_cost_per_kilometer_below_soft_max``. - cost_per_kilometer_above_soft_max (float): - Cost per kilometer incurred if distance is above - ``soft_max_meters`` limit. The additional cost is 0 if the - distance is under the limit, otherwise the formula used to - compute the cost is the following: - - :: - - (distance_meters - soft_max_meters) / 1000.0 * - cost_per_kilometer_above_soft_max. - - The cost must be nonnegative. - - This field is a member of `oneof`_ ``_cost_per_kilometer_above_soft_max``. - """ - - max_meters: int = proto.Field( - proto.INT64, - number=1, - optional=True, - ) - soft_max_meters: int = proto.Field( - proto.INT64, - number=2, - optional=True, - ) - cost_per_kilometer_below_soft_max: float = proto.Field( - proto.DOUBLE, - number=4, - optional=True, - ) - cost_per_kilometer_above_soft_max: float = proto.Field( - proto.DOUBLE, - number=3, - optional=True, - ) - - -class TransitionAttributes(proto.Message): - r"""Specifies attributes of transitions between two consecutive visits - on a route. Several ``TransitionAttributes`` may apply to the same - transition: in that case, all extra costs add up and the strictest - constraint or limit applies (following natural "AND" semantics). - - Attributes: - src_tag (str): - Tags defining the set of (src->dst) transitions these - attributes apply to. - - A source visit or vehicle start matches iff its - [VisitRequest.tags][google.maps.routeoptimization.v1.Shipment.VisitRequest.tags] - or - [Vehicle.start_tags][google.maps.routeoptimization.v1.Vehicle.start_tags] - either contains ``src_tag`` or does not contain - ``excluded_src_tag`` (depending on which of these two fields - is non-empty). - excluded_src_tag (str): - See ``src_tag``. Exactly one of ``src_tag`` and - ``excluded_src_tag`` must be non-empty. - dst_tag (str): - A destination visit or vehicle end matches iff its - [VisitRequest.tags][google.maps.routeoptimization.v1.Shipment.VisitRequest.tags] - or - [Vehicle.end_tags][google.maps.routeoptimization.v1.Vehicle.end_tags] - either contains ``dst_tag`` or does not contain - ``excluded_dst_tag`` (depending on which of these two fields - is non-empty). - excluded_dst_tag (str): - See ``dst_tag``. Exactly one of ``dst_tag`` and - ``excluded_dst_tag`` must be non-empty. - cost (float): - Specifies a cost for performing this - transition. This is in the same unit as all - other costs in the model and must not be - negative. It is applied on top of all other - existing costs. - cost_per_kilometer (float): - Specifies a cost per kilometer applied to the distance - traveled while performing this transition. It adds up to any - [Vehicle.cost_per_kilometer][google.maps.routeoptimization.v1.Vehicle.cost_per_kilometer] - specified on vehicles. - distance_limit (google.maps.routeoptimization_v1.types.DistanceLimit): - Specifies a limit on the distance traveled - while performing this transition. - - As of 2021/06, only soft limits are supported. - delay (google.protobuf.duration_pb2.Duration): - Specifies a delay incurred when performing this transition. - - This delay always occurs *after* finishing the source visit - and *before* starting the destination visit. - """ - - src_tag: str = proto.Field( - proto.STRING, - number=1, - ) - excluded_src_tag: str = proto.Field( - proto.STRING, - number=2, - ) - dst_tag: str = proto.Field( - proto.STRING, - number=3, - ) - excluded_dst_tag: str = proto.Field( - proto.STRING, - number=4, - ) - cost: float = proto.Field( - proto.DOUBLE, - number=5, - ) - cost_per_kilometer: float = proto.Field( - proto.DOUBLE, - number=6, - ) - distance_limit: 'DistanceLimit' = proto.Field( - proto.MESSAGE, - number=7, - message='DistanceLimit', - ) - delay: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=8, - message=duration_pb2.Duration, - ) - - -class Waypoint(proto.Message): - r"""Encapsulates a waypoint. Waypoints mark arrival and departure - locations of VisitRequests, and start and end locations of - Vehicles. - - 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 (google.maps.routeoptimization_v1.types.Location): - A point specified using geographic - coordinates, including an optional heading. - - This field is a member of `oneof`_ ``location_type``. - place_id (str): - The POI Place ID associated with the - waypoint. - - This field is a member of `oneof`_ ``location_type``. - side_of_road (bool): - Optional. Indicates that the location of this - waypoint is meant to have a preference for the - vehicle to stop at a particular side of road. - When you set this value, the route will pass - through the location so that the vehicle can - stop at the side of road that the location is - biased towards from the center of the road. This - option doesn't work for the 'WALKING' travel - mode. - """ - - location: 'Location' = proto.Field( - proto.MESSAGE, - number=1, - oneof='location_type', - message='Location', - ) - place_id: str = proto.Field( - proto.STRING, - number=2, - oneof='location_type', - ) - side_of_road: bool = proto.Field( - proto.BOOL, - number=3, - ) - - -class Location(proto.Message): - r"""Encapsulates a location (a geographic point, and an optional - heading). - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - lat_lng (google.type.latlng_pb2.LatLng): - The waypoint's geographic coordinates. - heading (int): - The compass heading associated with the - direction of the flow of traffic. This value is - used to specify the side of the road to use for - pickup and drop-off. Heading values can be from - 0 to 360, where 0 specifies a heading of due - North, 90 specifies a heading of due East, etc. - - This field is a member of `oneof`_ ``_heading``. - """ - - lat_lng: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=1, - message=latlng_pb2.LatLng, - ) - heading: int = proto.Field( - proto.INT32, - number=2, - optional=True, - ) - - -class BreakRule(proto.Message): - r"""Rules to generate time breaks for a vehicle (e.g. lunch breaks). A - break is a contiguous period of time during which the vehicle - remains idle at its current position and cannot perform any visit. A - break may occur: - - - during the travel between two visits (which includes the time - right before or right after a visit, but not in the middle of a - visit), in which case it extends the corresponding transit time - between the visits, - - or before the vehicle start (the vehicle may not start in the - middle of a break), in which case it does not affect the vehicle - start time. - - or after the vehicle end (ditto, with the vehicle end time). - - Attributes: - break_requests (MutableSequence[google.maps.routeoptimization_v1.types.BreakRule.BreakRequest]): - Sequence of breaks. See the ``BreakRequest`` message. - frequency_constraints (MutableSequence[google.maps.routeoptimization_v1.types.BreakRule.FrequencyConstraint]): - Several ``FrequencyConstraint`` may apply. They must all be - satisfied by the ``BreakRequest``\ s of this ``BreakRule``. - See ``FrequencyConstraint``. - """ - - class BreakRequest(proto.Message): - r"""The sequence of breaks (i.e. their number and order) that apply to - each vehicle must be known beforehand. The repeated - ``BreakRequest``\ s define that sequence, in the order in which they - must occur. Their time windows (``earliest_start_time`` / - ``latest_start_time``) may overlap, but they must be compatible with - the order (this is checked). - - Attributes: - earliest_start_time (google.protobuf.timestamp_pb2.Timestamp): - Required. Lower bound (inclusive) on the - start of the break. - latest_start_time (google.protobuf.timestamp_pb2.Timestamp): - Required. Upper bound (inclusive) on the - start of the break. - min_duration (google.protobuf.duration_pb2.Duration): - Required. Minimum duration of the break. Must - be positive. - """ - - earliest_start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - latest_start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - min_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=3, - message=duration_pb2.Duration, - ) - - class FrequencyConstraint(proto.Message): - r"""One may further constrain the frequency and duration of the breaks - specified above, by enforcing a minimum break frequency, such as - "There must be a break of at least 1 hour every 12 hours". Assuming - that this can be interpreted as "Within any sliding time window of - 12h, there must be at least one break of at least one hour", that - example would translate to the following ``FrequencyConstraint``: - - :: - - { - min_break_duration { seconds: 3600 } # 1 hour. - max_inter_break_duration { seconds: 39600 } # 11 hours (12 - 1 = 11). - } - - The timing and duration of the breaks in the solution will respect - all such constraints, in addition to the time windows and minimum - durations already specified in the ``BreakRequest``. - - A ``FrequencyConstraint`` may in practice apply to non-consecutive - breaks. For example, the following schedule honors the "1h every - 12h" example: - - :: - - 04:00 vehicle start - .. performing travel and visits .. - 09:00 1 hour break - 10:00 end of the break - .. performing travel and visits .. - 12:00 20-min lunch break - 12:20 end of the break - .. performing travel and visits .. - 21:00 1 hour break - 22:00 end of the break - .. performing travel and visits .. - 23:59 vehicle end - - Attributes: - min_break_duration (google.protobuf.duration_pb2.Duration): - Required. Minimum break duration for this constraint. - Nonnegative. See description of ``FrequencyConstraint``. - max_inter_break_duration (google.protobuf.duration_pb2.Duration): - Required. Maximum allowed span of any interval of time in - the route that does not include at least partially a break - of ``duration >= min_break_duration``. Must be positive. - """ - - min_break_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - max_inter_break_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - - break_requests: MutableSequence[BreakRequest] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=BreakRequest, - ) - frequency_constraints: MutableSequence[FrequencyConstraint] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=FrequencyConstraint, - ) - - -class ShipmentRoute(proto.Message): - r"""A vehicle's route can be decomposed, along the time axis, like this - (we assume there are n visits): - - :: - - | | | | | T[2], | | | - | Transition | Visit #0 | | | V[2], | | | - | #0 | aka | T[1] | V[1] | ... | V[n-1] | T[n] | - | aka T[0] | V[0] | | | V[n-2],| | | - | | | | | T[n-1] | | | - ^ ^ ^ ^ ^ ^ ^ ^ - vehicle V[0].start V[0].end V[1]. V[1]. V[n]. V[n]. vehicle - start (arrival) (departure) start end start end end - - Note that we make a difference between: - - - "punctual events", such as the vehicle start and end and each - visit's start and end (aka arrival and departure). They happen at - a given second. - - "time intervals", such as the visits themselves, and the - transition between visits. Though time intervals can sometimes - have zero duration, i.e. start and end at the same second, they - often have a positive duration. - - Invariants: - - - If there are n visits, there are n+1 transitions. - - A visit is always surrounded by a transition before it (same - index) and a transition after it (index + 1). - - The vehicle start is always followed by transition #0. - - The vehicle end is always preceded by transition #n. - - Zooming in, here is what happens during a ``Transition`` and a - ``Visit``: - - :: - - ---+-------------------------------------+-----------------------------+--> - | TRANSITION[i] | VISIT[i] | - | | | - | * TRAVEL: the vehicle moves from | PERFORM the visit: | - | VISIT[i-1].departure_location to | | - | VISIT[i].arrival_location, which | * Spend some time: | - | takes a given travel duration | the "visit duration". | - | and distance | | - | | * Load or unload | - | * BREAKS: the driver may have | some quantities from the | - | breaks (e.g. lunch break). | vehicle: the "demand". | - | | | - | * WAIT: the driver/vehicle does | | - | nothing. This can happen for | | - | many reasons, for example when | | - | the vehicle reaches the next | | - | event's destination before the | | - | start of its time window | | - | | | - | * DELAY: *right before* the next | | - | arrival. E.g. the vehicle and/or | | - | driver spends time unloading. | | - | | | - ---+-------------------------------------+-----------------------------+--> - ^ ^ ^ - V[i-1].end V[i].start V[i].end - - Lastly, here is how the TRAVEL, BREAKS, DELAY and WAIT can be - arranged during a transition. - - - They don't overlap. - - The DELAY is unique and *must* be a contiguous period of time - right before the next visit (or vehicle end). Thus, it suffice to - know the delay duration to know its start and end time. - - The BREAKS are contiguous, non-overlapping periods of time. The - response specifies the start time and duration of each break. - - TRAVEL and WAIT are "preemptable": they can be interrupted - several times during this transition. Clients can assume that - travel happens "as soon as possible" and that "wait" fills the - remaining time. - - A (complex) example: - - :: - - TRANSITION[i] - --++-----+-----------------------------------------------------------++--> - || | | | | | | || - || T | B | T | | B | | D || - || r | r | r | W | r | W | e || - || a | e | a | a | e | a | l || - || v | a | v | i | a | i | a || - || e | k | e | t | k | t | y || - || l | | l | | | | || - || | | | | | | || - --++-----------------------------------------------------------------++--> - - Attributes: - vehicle_index (int): - Vehicle performing the route, identified by its index in the - source ``ShipmentModel``. - vehicle_label (str): - Label of the vehicle performing this route, equal to - ``ShipmentModel.vehicles(vehicle_index).label``, if - specified. - vehicle_start_time (google.protobuf.timestamp_pb2.Timestamp): - Time at which the vehicle starts its route. - vehicle_end_time (google.protobuf.timestamp_pb2.Timestamp): - Time at which the vehicle finishes its route. - visits (MutableSequence[google.maps.routeoptimization_v1.types.ShipmentRoute.Visit]): - Ordered sequence of visits representing a route. visits[i] - is the i-th visit in the route. If this field is empty, the - vehicle is considered as unused. - transitions (MutableSequence[google.maps.routeoptimization_v1.types.ShipmentRoute.Transition]): - Ordered list of transitions for the route. - has_traffic_infeasibilities (bool): - When - [OptimizeToursRequest.consider_road_traffic][google.maps.routeoptimization.v1.OptimizeToursRequest.consider_road_traffic], - is set to true, this field indicates that inconsistencies in - route timings are predicted using traffic-based travel - duration estimates. There may be insufficient time to - complete traffic-adjusted travel, delays, and breaks between - visits, before the first visit, or after the last visit, - while still satisfying the visit and vehicle time windows. - For example, - - :: - - start_time(previous_visit) + duration(previous_visit) + - travel_duration(previous_visit, next_visit) > start_time(next_visit) - - Arrival at next_visit will likely happen later than its - current time window due the increased estimate of travel - time ``travel_duration(previous_visit, next_visit)`` due to - traffic. Also, a break may be forced to overlap with a visit - due to an increase in travel time estimates and visit or - break time window restrictions. - route_polyline (google.maps.routeoptimization_v1.types.ShipmentRoute.EncodedPolyline): - The encoded polyline representation of the route. This field - is only populated if - [OptimizeToursRequest.populate_polylines][google.maps.routeoptimization.v1.OptimizeToursRequest.populate_polylines] - is set to true. - breaks (MutableSequence[google.maps.routeoptimization_v1.types.ShipmentRoute.Break]): - Breaks scheduled for the vehicle performing this route. The - ``breaks`` sequence represents time intervals, each starting - at the corresponding ``start_time`` and lasting ``duration`` - seconds. - metrics (google.maps.routeoptimization_v1.types.AggregatedMetrics): - Duration, distance and load metrics for this route. The - fields of - [AggregatedMetrics][google.maps.routeoptimization.v1.AggregatedMetrics] - are summed over all - [ShipmentRoute.transitions][google.maps.routeoptimization.v1.ShipmentRoute.transitions] - or - [ShipmentRoute.visits][google.maps.routeoptimization.v1.ShipmentRoute.visits], - depending on the context. - route_costs (MutableMapping[str, float]): - Cost of the route, broken down by cost-related request - fields. The keys are proto paths, relative to the input - OptimizeToursRequest, e.g. "model.shipments.pickups.cost", - and the values are the total cost generated by the - corresponding cost field, aggregated over the whole route. - In other words, costs["model.shipments.pickups.cost"] is the - sum of all pickup costs over the route. All costs defined in - the model are reported in detail here with the exception of - costs related to TransitionAttributes that are only reported - in an aggregated way as of 2022/01. - route_total_cost (float): - Total cost of the route. The sum of all costs - in the cost map. - """ - - class Visit(proto.Message): - r"""A visit performed during a route. This visit corresponds to a pickup - or a delivery of a ``Shipment``. - - Attributes: - shipment_index (int): - Index of the ``shipments`` field in the source - [ShipmentModel][google.maps.routeoptimization.v1.ShipmentModel]. - is_pickup (bool): - If true the visit corresponds to a pickup of a ``Shipment``. - Otherwise, it corresponds to a delivery. - visit_request_index (int): - Index of ``VisitRequest`` in either the pickup or delivery - field of the ``Shipment`` (see ``is_pickup``). - start_time (google.protobuf.timestamp_pb2.Timestamp): - Time at which the visit starts. Note that the vehicle may - arrive earlier than this at the visit location. Times are - consistent with the ``ShipmentModel``. - load_demands (MutableMapping[str, google.maps.routeoptimization_v1.types.Shipment.Load]): - Total visit load demand as the sum of the shipment and the - visit request ``load_demands``. The values are negative if - the visit is a delivery. Demands are reported for the same - types as the - [Transition.loads][google.maps.routeoptimization.v1.ShipmentRoute.Transition] - (see this field). - detour (google.protobuf.duration_pb2.Duration): - Extra detour time due to the shipments visited on the route - before the visit and to the potential waiting time induced - by time windows. If the visit is a delivery, the detour is - computed from the corresponding pickup visit and is equal - to: - - :: - - start_time(delivery) - start_time(pickup) - - (duration(pickup) + travel duration from the pickup location - to the delivery location). - - Otherwise, it is computed from the vehicle - ``start_location`` and is equal to: - - :: - - start_time - vehicle_start_time - travel duration from - the vehicle's `start_location` to the visit. - shipment_label (str): - Copy of the corresponding ``Shipment.label``, if specified - in the ``Shipment``. - visit_label (str): - Copy of the corresponding - [VisitRequest.label][google.maps.routeoptimization.v1.Shipment.VisitRequest.label], - if specified in the ``VisitRequest``. - """ - - shipment_index: int = proto.Field( - proto.INT32, - number=1, - ) - is_pickup: bool = proto.Field( - proto.BOOL, - number=2, - ) - visit_request_index: int = proto.Field( - proto.INT32, - number=3, - ) - start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - load_demands: MutableMapping[str, 'Shipment.Load'] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=11, - message='Shipment.Load', - ) - detour: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=6, - message=duration_pb2.Duration, - ) - shipment_label: str = proto.Field( - proto.STRING, - number=7, - ) - visit_label: str = proto.Field( - proto.STRING, - number=8, - ) - - class Transition(proto.Message): - r"""Transition between two events on the route. See the description of - [ShipmentRoute][google.maps.routeoptimization.v1.ShipmentRoute]. - - If the vehicle does not have a ``start_location`` and/or - ``end_location``, the corresponding travel metrics are 0. - - Attributes: - travel_duration (google.protobuf.duration_pb2.Duration): - Travel duration during this transition. - travel_distance_meters (float): - Distance traveled during the transition. - traffic_info_unavailable (bool): - When traffic is requested via - [OptimizeToursRequest.consider_road_traffic] - [google.maps.routeoptimization.v1.OptimizeToursRequest.consider_road_traffic], - and the traffic info couldn't be retrieved for a - ``Transition``, this boolean is set to true. This may be - temporary (rare hiccup in the realtime traffic servers) or - permanent (no data for this location). - delay_duration (google.protobuf.duration_pb2.Duration): - Sum of the delay durations applied to this transition. If - any, the delay starts exactly ``delay_duration`` seconds - before the next event (visit or vehicle end). See - [TransitionAttributes.delay][google.maps.routeoptimization.v1.TransitionAttributes.delay]. - break_duration (google.protobuf.duration_pb2.Duration): - Sum of the duration of the breaks occurring during this - transition, if any. Details about each break's start time - and duration are stored in - [ShipmentRoute.breaks][google.maps.routeoptimization.v1.ShipmentRoute.breaks]. - wait_duration (google.protobuf.duration_pb2.Duration): - Time spent waiting during this transition. - Wait duration corresponds to idle time and does - not include break time. Also note that this wait - time may be split into several non-contiguous - intervals. - total_duration (google.protobuf.duration_pb2.Duration): - Total duration of the transition, provided for convenience. - It is equal to: - - - next visit ``start_time`` (or ``vehicle_end_time`` if - this is the last transition) - this transition's - ``start_time``; - - if ``ShipmentRoute.has_traffic_infeasibilities`` is - false, the following additionally holds: \`total_duration - = travel_duration + delay_duration - - - break_duration + wait_duration`. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Start time of this transition. - route_polyline (google.maps.routeoptimization_v1.types.ShipmentRoute.EncodedPolyline): - The encoded polyline representation of the route followed - during the transition. This field is only populated if - [populate_transition_polylines] - [google.maps.routeoptimization.v1.OptimizeToursRequest.populate_transition_polylines] - is set to true. - route_token (str): - Output only. An opaque token that can be passed to - `Navigation - SDK `__ - to reconstruct the route during navigation, and, in the - event of rerouting, honor the original intention when the - route was created. Treat this token as an opaque blob. Don't - compare its value across requests as its value may change - even if the service returns the exact same route. This field - is only populated if [populate_transition_polylines] - [google.maps.routeoptimization.v1.OptimizeToursRequest.populate_transition_polylines] - is set to true. - vehicle_loads (MutableMapping[str, google.maps.routeoptimization_v1.types.ShipmentRoute.VehicleLoad]): - Vehicle loads during this transition, for each type that - either appears in this vehicle's - [Vehicle.load_limits][google.maps.routeoptimization.v1.Vehicle.load_limits], - or that have non-zero - [Shipment.load_demands][google.maps.routeoptimization.v1.Shipment.load_demands] - on some shipment performed on this route. - - The loads during the first transition are the starting loads - of the vehicle route. Then, after each visit, the visit's - ``load_demands`` are either added or subtracted to get the - next transition's loads, depending on whether the visit was - a pickup or a delivery. - """ - - travel_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - travel_distance_meters: float = proto.Field( - proto.DOUBLE, - number=2, - ) - traffic_info_unavailable: bool = proto.Field( - proto.BOOL, - number=3, - ) - delay_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=4, - message=duration_pb2.Duration, - ) - break_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=5, - message=duration_pb2.Duration, - ) - wait_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=6, - message=duration_pb2.Duration, - ) - total_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=7, - message=duration_pb2.Duration, - ) - start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=8, - message=timestamp_pb2.Timestamp, - ) - route_polyline: 'ShipmentRoute.EncodedPolyline' = proto.Field( - proto.MESSAGE, - number=9, - message='ShipmentRoute.EncodedPolyline', - ) - route_token: str = proto.Field( - proto.STRING, - number=12, - ) - vehicle_loads: MutableMapping[str, 'ShipmentRoute.VehicleLoad'] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=11, - message='ShipmentRoute.VehicleLoad', - ) - - class VehicleLoad(proto.Message): - r"""Reports the actual load of the vehicle at some point along the - route, for a given type (see - [Transition.vehicle_loads][google.maps.routeoptimization.v1.ShipmentRoute.Transition.vehicle_loads]). - - Attributes: - amount (int): - The amount of load on the vehicle, for the given type. The - unit of load is usually indicated by the type. See - [Transition.vehicle_loads][google.maps.routeoptimization.v1.ShipmentRoute.Transition.vehicle_loads]. - """ - - amount: int = proto.Field( - proto.INT64, - number=1, - ) - - class EncodedPolyline(proto.Message): - r"""The encoded representation of a polyline. More information on - polyline encoding can be found here: - - https://developers.google.com/maps/documentation/utilities/polylinealgorithm - https://developers.google.com/maps/documentation/javascript/reference/geometry#encoding. - - Attributes: - points (str): - String representing encoded points of the - polyline. - """ - - points: str = proto.Field( - proto.STRING, - number=1, - ) - - class Break(proto.Message): - r"""Data representing the execution of a break. - - Attributes: - start_time (google.protobuf.timestamp_pb2.Timestamp): - Start time of a break. - duration (google.protobuf.duration_pb2.Duration): - Duration of a break. - """ - - start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - - vehicle_index: int = proto.Field( - proto.INT32, - number=1, - ) - vehicle_label: str = proto.Field( - proto.STRING, - number=2, - ) - vehicle_start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - vehicle_end_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - visits: MutableSequence[Visit] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message=Visit, - ) - transitions: MutableSequence[Transition] = proto.RepeatedField( - proto.MESSAGE, - number=8, - message=Transition, - ) - has_traffic_infeasibilities: bool = proto.Field( - proto.BOOL, - number=9, - ) - route_polyline: EncodedPolyline = proto.Field( - proto.MESSAGE, - number=10, - message=EncodedPolyline, - ) - breaks: MutableSequence[Break] = proto.RepeatedField( - proto.MESSAGE, - number=11, - message=Break, - ) - metrics: 'AggregatedMetrics' = proto.Field( - proto.MESSAGE, - number=12, - message='AggregatedMetrics', - ) - route_costs: MutableMapping[str, float] = proto.MapField( - proto.STRING, - proto.DOUBLE, - number=17, - ) - route_total_cost: float = proto.Field( - proto.DOUBLE, - number=18, - ) - - -class SkippedShipment(proto.Message): - r"""Specifies details of unperformed shipments in a solution. For - trivial cases and/or if we are able to identify the cause for - skipping, we report the reason here. - - Attributes: - index (int): - The index corresponds to the index of the shipment in the - source ``ShipmentModel``. - label (str): - Copy of the corresponding - [Shipment.label][google.maps.routeoptimization.v1.Shipment.label], - if specified in the ``Shipment``. - reasons (MutableSequence[google.maps.routeoptimization_v1.types.SkippedShipment.Reason]): - A list of reasons that explain why the shipment was skipped. - See comment above ``Reason``. If we are unable to understand - why a shipment was skipped, reasons will not be set. - """ - - class Reason(proto.Message): - r"""If we can explain why the shipment was skipped, reasons will be - listed here. If the reason is not the same for all vehicles, - ``reason`` will have more than 1 element. A skipped shipment cannot - have duplicate reasons, i.e. where all fields are the same except - for ``example_vehicle_index``. Example: - - :: - - reasons { - code: DEMAND_EXCEEDS_VEHICLE_CAPACITY - example_vehicle_index: 1 - example_exceeded_capacity_type: "Apples" - } - reasons { - code: DEMAND_EXCEEDS_VEHICLE_CAPACITY - example_vehicle_index: 3 - example_exceeded_capacity_type: "Pears" - } - reasons { - code: CANNOT_BE_PERFORMED_WITHIN_VEHICLE_DISTANCE_LIMIT - example_vehicle_index: 1 - } - - The skipped shipment is incompatible with all vehicles. The reasons - may be different for all vehicles but at least one vehicle's - "Apples" capacity would be exceeded (including vehicle 1), at least - one vehicle's "Pears" capacity would be exceeded (including vehicle - 3) and at least one vehicle's distance limit would be exceeded - (including vehicle 1). - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - code (google.maps.routeoptimization_v1.types.SkippedShipment.Reason.Code): - Refer to the comments of Code. - example_vehicle_index (int): - If the reason is related to a - shipment-vehicle incompatibility, this field - provides the index of one relevant vehicle. - - This field is a member of `oneof`_ ``_example_vehicle_index``. - example_exceeded_capacity_type (str): - If the reason code is ``DEMAND_EXCEEDS_VEHICLE_CAPACITY``, - documents one capacity type that is exceeded. - """ - class Code(proto.Enum): - r"""Code identifying the reason type. The order here is - meaningless. In particular, it gives no indication of whether a - given reason will appear before another in the solution, if both - apply. - - Values: - CODE_UNSPECIFIED (0): - This should never be used. - NO_VEHICLE (1): - There is no vehicle in the model making all - shipments infeasible. - DEMAND_EXCEEDS_VEHICLE_CAPACITY (2): - The demand of the shipment exceeds a vehicle's capacity for - some capacity types, one of which is - ``example_exceeded_capacity_type``. - CANNOT_BE_PERFORMED_WITHIN_VEHICLE_DISTANCE_LIMIT (3): - The minimum distance necessary to perform this shipment, - i.e. from the vehicle's ``start_location`` to the shipment's - pickup and/or delivery locations and to the vehicle's end - location exceeds the vehicle's ``route_distance_limit``. - - Note that for this computation we use the geodesic - distances. - CANNOT_BE_PERFORMED_WITHIN_VEHICLE_DURATION_LIMIT (4): - The minimum time necessary to perform this shipment, - including travel time, wait time and service time exceeds - the vehicle's ``route_duration_limit``. - - Note: travel time is computed in the best-case scenario, - namely as geodesic distance x 36 m/s (roughly 130 km/hour). - CANNOT_BE_PERFORMED_WITHIN_VEHICLE_TRAVEL_DURATION_LIMIT (5): - Same as above but we only compare minimum travel time and - the vehicle's ``travel_duration_limit``. - CANNOT_BE_PERFORMED_WITHIN_VEHICLE_TIME_WINDOWS (6): - The vehicle cannot perform this shipment in the best-case - scenario (see - ``CANNOT_BE_PERFORMED_WITHIN_VEHICLE_DURATION_LIMIT`` for - time computation) if it starts at its earliest start time: - the total time would make the vehicle end after its latest - end time. - VEHICLE_NOT_ALLOWED (7): - The ``allowed_vehicle_indices`` field of the shipment is not - empty and this vehicle does not belong to it. - """ - CODE_UNSPECIFIED = 0 - NO_VEHICLE = 1 - DEMAND_EXCEEDS_VEHICLE_CAPACITY = 2 - CANNOT_BE_PERFORMED_WITHIN_VEHICLE_DISTANCE_LIMIT = 3 - CANNOT_BE_PERFORMED_WITHIN_VEHICLE_DURATION_LIMIT = 4 - CANNOT_BE_PERFORMED_WITHIN_VEHICLE_TRAVEL_DURATION_LIMIT = 5 - CANNOT_BE_PERFORMED_WITHIN_VEHICLE_TIME_WINDOWS = 6 - VEHICLE_NOT_ALLOWED = 7 - - code: 'SkippedShipment.Reason.Code' = proto.Field( - proto.ENUM, - number=1, - enum='SkippedShipment.Reason.Code', - ) - example_vehicle_index: int = proto.Field( - proto.INT32, - number=2, - optional=True, - ) - example_exceeded_capacity_type: str = proto.Field( - proto.STRING, - number=3, - ) - - index: int = proto.Field( - proto.INT32, - number=1, - ) - label: str = proto.Field( - proto.STRING, - number=2, - ) - reasons: MutableSequence[Reason] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=Reason, - ) - - -class AggregatedMetrics(proto.Message): - r"""Aggregated metrics for - [ShipmentRoute][google.maps.routeoptimization.v1.ShipmentRoute] - (resp. for - [OptimizeToursResponse][google.maps.routeoptimization.v1.OptimizeToursResponse] - over all - [Transition][google.maps.routeoptimization.v1.ShipmentRoute.Transition] - and/or [Visit][google.maps.routeoptimization.v1.ShipmentRoute.Visit] - (resp. over all - [ShipmentRoute][google.maps.routeoptimization.v1.ShipmentRoute]) - elements. - - Attributes: - performed_shipment_count (int): - Number of shipments performed. Note that a - pickup and delivery pair only counts once. - travel_duration (google.protobuf.duration_pb2.Duration): - Total travel duration for a route or a - solution. - wait_duration (google.protobuf.duration_pb2.Duration): - Total wait duration for a route or a - solution. - delay_duration (google.protobuf.duration_pb2.Duration): - Total delay duration for a route or a - solution. - break_duration (google.protobuf.duration_pb2.Duration): - Total break duration for a route or a - solution. - visit_duration (google.protobuf.duration_pb2.Duration): - Total visit duration for a route or a - solution. - total_duration (google.protobuf.duration_pb2.Duration): - The total duration should be equal to the sum of all - durations above. For routes, it also corresponds to: - - :: - - [ShipmentRoute.vehicle_end_time][google.maps.routeoptimization.v1.ShipmentRoute.vehicle_end_time] - - - [ShipmentRoute.vehicle_start_time][google.maps.routeoptimization.v1.ShipmentRoute.vehicle_start_time] - travel_distance_meters (float): - Total travel distance for a route or a - solution. - max_loads (MutableMapping[str, google.maps.routeoptimization_v1.types.ShipmentRoute.VehicleLoad]): - Maximum load achieved over the entire route (resp. - solution), for each of the quantities on this route (resp. - solution), computed as the maximum over all - [Transition.vehicle_loads][google.maps.routeoptimization.v1.ShipmentRoute.Transition.vehicle_loads] - (resp. - [ShipmentRoute.metrics.max_loads][google.maps.routeoptimization.v1.AggregatedMetrics.max_loads]. - """ - - performed_shipment_count: int = proto.Field( - proto.INT32, - number=1, - ) - travel_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - wait_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=3, - message=duration_pb2.Duration, - ) - delay_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=4, - message=duration_pb2.Duration, - ) - break_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=5, - message=duration_pb2.Duration, - ) - visit_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=6, - message=duration_pb2.Duration, - ) - total_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=7, - message=duration_pb2.Duration, - ) - travel_distance_meters: float = proto.Field( - proto.DOUBLE, - number=8, - ) - max_loads: MutableMapping[str, 'ShipmentRoute.VehicleLoad'] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=9, - message='ShipmentRoute.VehicleLoad', - ) - - -class InjectedSolutionConstraint(proto.Message): - r"""Solution injected in the request including information about - which visits must be constrained and how they must be - constrained. - - Attributes: - routes (MutableSequence[google.maps.routeoptimization_v1.types.ShipmentRoute]): - Routes of the solution to inject. Some routes may be omitted - from the original solution. The routes and skipped shipments - must satisfy the basic validity assumptions listed for - ``injected_first_solution_routes``. - skipped_shipments (MutableSequence[google.maps.routeoptimization_v1.types.SkippedShipment]): - Skipped shipments of the solution to inject. Some may be - omitted from the original solution. See the ``routes`` - field. - constraint_relaxations (MutableSequence[google.maps.routeoptimization_v1.types.InjectedSolutionConstraint.ConstraintRelaxation]): - For zero or more groups of vehicles, - specifies when and how much to relax - constraints. If this field is empty, all - non-empty vehicle routes are fully constrained. - """ - - class ConstraintRelaxation(proto.Message): - r"""For a group of vehicles, specifies at what threshold(s) constraints - on visits will be relaxed and to which level. Shipments listed in - the ``skipped_shipment`` field are constrained to be skipped; i.e., - they cannot be performed. - - Attributes: - relaxations (MutableSequence[google.maps.routeoptimization_v1.types.InjectedSolutionConstraint.ConstraintRelaxation.Relaxation]): - All the visit constraint relaxations that will apply to - visits on routes with vehicles in ``vehicle_indices``. - vehicle_indices (MutableSequence[int]): - Specifies the vehicle indices to which the visit constraint - ``relaxations`` apply. If empty, this is considered the - default and the ``relaxations`` apply to all vehicles that - are not specified in other ``constraint_relaxations``. There - can be at most one default, i.e., at most one constraint - relaxation field is allowed empty ``vehicle_indices``. A - vehicle index can only be listed once, even within several - ``constraint_relaxations``. - - A vehicle index is mapped the same as - [ShipmentRoute.vehicle_index][google.maps.routeoptimization.v1.ShipmentRoute.vehicle_index], - if ``interpret_injected_solutions_using_labels`` is true - (see ``fields`` comment). - """ - - class Relaxation(proto.Message): - r"""If ``relaxations`` is empty, the start time and sequence of all - visits on ``routes`` are fully constrained and no new visits may be - inserted or added to those routes. Also, a vehicle's start and end - time in ``routes`` is fully constrained, unless the vehicle is empty - (i.e., has no visits and has ``used_if_route_is_empty`` set to false - in the model). - - ``relaxations(i).level`` specifies the constraint relaxation level - applied to a visit #j that satisfies: - - - ``route.visits(j).start_time >= relaxations(i).threshold_time`` - AND - - ``j + 1 >= relaxations(i).threshold_visit_count`` - - Similarly, the vehicle start is relaxed to ``relaxations(i).level`` - if it satisfies: - - - ``vehicle_start_time >= relaxations(i).threshold_time`` AND - - ``relaxations(i).threshold_visit_count == 0`` and the vehicle end - is relaxed to ``relaxations(i).level`` if it satisfies: - - ``vehicle_end_time >= relaxations(i).threshold_time`` AND - - ``route.visits_size() + 1 >= relaxations(i).threshold_visit_count`` - - To apply a relaxation level if a visit meets the - ``threshold_visit_count`` OR the ``threshold_time`` add two - ``relaxations`` with the same ``level``: one with only - ``threshold_visit_count`` set and the other with only - ``threshold_time`` set. If a visit satisfies the conditions of - multiple ``relaxations``, the most relaxed level applies. As a - result, from the vehicle start through the route visits in order to - the vehicle end, the relaxation level becomes more relaxed: i.e., - the relaxation level is non-decreasing as the route progresses. - - The timing and sequence of route visits that do not satisfy the - threshold conditions of any ``relaxations`` are fully constrained - and no visits may be inserted into these sequences. Also, if a - vehicle start or end does not satisfy the conditions of any - relaxation the time is fixed, unless the vehicle is empty. - - Attributes: - level (google.maps.routeoptimization_v1.types.InjectedSolutionConstraint.ConstraintRelaxation.Relaxation.Level): - The constraint relaxation level that applies when the - conditions at or after ``threshold_time`` AND at least - ``threshold_visit_count`` are satisfied. - threshold_time (google.protobuf.timestamp_pb2.Timestamp): - The time at or after which the relaxation ``level`` may be - applied. - threshold_visit_count (int): - The number of visits at or after which the relaxation - ``level`` may be applied. If ``threshold_visit_count`` is 0 - (or unset), the ``level`` may be applied directly at the - vehicle start. - - If it is ``route.visits_size() + 1``, the ``level`` may only - be applied to the vehicle end. If it is more than - ``route.visits_size() + 1``, ``level`` is not applied at all - for that route. - """ - class Level(proto.Enum): - r"""Expresses the different constraint relaxation levels, which - are applied for a visit and those that follow when it satisfies - the threshold conditions. - - The enumeration below is in order of increasing relaxation. - - Values: - LEVEL_UNSPECIFIED (0): - Implicit default relaxation level: no constraints are - relaxed, i.e., all visits are fully constrained. - - This value must not be explicitly used in ``level``. - RELAX_VISIT_TIMES_AFTER_THRESHOLD (1): - Visit start times and vehicle start/end times - will be relaxed, but each visit remains bound to - the same vehicle and the visit sequence must be - observed: no visit can be inserted between them - or before them. - RELAX_VISIT_TIMES_AND_SEQUENCE_AFTER_THRESHOLD (2): - Same as ``RELAX_VISIT_TIMES_AFTER_THRESHOLD``, but the visit - sequence is also relaxed: visits can only be performed by - this vehicle, but can potentially become unperformed. - RELAX_ALL_AFTER_THRESHOLD (3): - Same as ``RELAX_VISIT_TIMES_AND_SEQUENCE_AFTER_THRESHOLD``, - but the vehicle is also relaxed: visits are completely free - at or after the threshold time and can potentially become - unperformed. - """ - LEVEL_UNSPECIFIED = 0 - RELAX_VISIT_TIMES_AFTER_THRESHOLD = 1 - RELAX_VISIT_TIMES_AND_SEQUENCE_AFTER_THRESHOLD = 2 - RELAX_ALL_AFTER_THRESHOLD = 3 - - level: 'InjectedSolutionConstraint.ConstraintRelaxation.Relaxation.Level' = proto.Field( - proto.ENUM, - number=1, - enum='InjectedSolutionConstraint.ConstraintRelaxation.Relaxation.Level', - ) - threshold_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - threshold_visit_count: int = proto.Field( - proto.INT32, - number=3, - ) - - relaxations: MutableSequence['InjectedSolutionConstraint.ConstraintRelaxation.Relaxation'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='InjectedSolutionConstraint.ConstraintRelaxation.Relaxation', - ) - vehicle_indices: MutableSequence[int] = proto.RepeatedField( - proto.INT32, - number=2, - ) - - routes: MutableSequence['ShipmentRoute'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ShipmentRoute', - ) - skipped_shipments: MutableSequence['SkippedShipment'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='SkippedShipment', - ) - constraint_relaxations: MutableSequence[ConstraintRelaxation] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=ConstraintRelaxation, - ) - - -class OptimizeToursValidationError(proto.Message): - r"""Describes an error or warning encountered when validating an - ``OptimizeToursRequest``. - - Attributes: - code (int): - A validation error is defined by the pair (``code``, - ``display_name``) which are always present. - - The fields following this section provide more context about - the error. - - *MULTIPLE ERRORS*: When there are multiple errors, the - validation process tries to output several of them. Much - like a compiler, this is an imperfect process. Some - validation errors will be "fatal", meaning that they stop - the entire validation process. This is the case for - ``display_name="UNSPECIFIED"`` errors, among others. Some - errors may cause the validation process to skip other - errors. - - *STABILITY*: ``code`` and ``display_name`` should be very - stable. But new codes and display names may appear over - time, which may cause a given (invalid) request to yield a - different (``code``, ``display_name``) pair because the new - error hid the old one. For example, see "MULTIPLE ERRORS". - display_name (str): - The error display name. - fields (MutableSequence[google.maps.routeoptimization_v1.types.OptimizeToursValidationError.FieldReference]): - An error context may involve 0, 1 (most of the time) or more - fields. For example, referring to vehicle #4 and shipment - #2's first pickup can be done as follows: - - :: - - fields { name: "vehicles" index: 4} - fields { name: "shipments" index: 2 sub_field {name: "pickups" index: 0} } - - Note, however, that the cardinality of ``fields`` should not - change for a given error code. - error_message (str): - Human-readable string describing the error. There is a 1:1 - mapping between ``code`` and ``error_message`` (when code != - "UNSPECIFIED"). - - *STABILITY*: Not stable: the error message associated to a - given ``code`` may change (hopefully to clarify it) over - time. Please rely on the ``display_name`` and ``code`` - instead. - offending_values (str): - May contain the value(s) of the field(s). - This is not always available. You should - absolutely not rely on it and use it only for - manual model debugging. - """ - - class FieldReference(proto.Message): - r"""Specifies a context for the validation error. A ``FieldReference`` - always refers to a given field in this file and follows the same - hierarchical structure. For example, we may specify element #2 of - ``start_time_windows`` of vehicle #5 using: - - :: - - name: "vehicles" index: 5 sub_field { name: "end_time_windows" index: 2 } - - We however omit top-level entities such as ``OptimizeToursRequest`` - or ``ShipmentModel`` to avoid crowding the message. - - 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: - name (str): - Name of the field, e.g., "vehicles". - index (int): - Index of the field if repeated. - - This field is a member of `oneof`_ ``index_or_key``. - key (str): - Key if the field is a map. - - This field is a member of `oneof`_ ``index_or_key``. - sub_field (google.maps.routeoptimization_v1.types.OptimizeToursValidationError.FieldReference): - Recursively nested sub-field, if needed. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - index: int = proto.Field( - proto.INT32, - number=2, - oneof='index_or_key', - ) - key: str = proto.Field( - proto.STRING, - number=4, - oneof='index_or_key', - ) - sub_field: 'OptimizeToursValidationError.FieldReference' = proto.Field( - proto.MESSAGE, - number=3, - message='OptimizeToursValidationError.FieldReference', - ) - - code: int = proto.Field( - proto.INT32, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - fields: MutableSequence[FieldReference] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=FieldReference, - ) - error_message: str = proto.Field( - proto.STRING, - number=4, - ) - offending_values: str = proto.Field( - proto.STRING, - number=5, - ) - - -class InputConfig(proto.Message): - r"""Specify an input for - [BatchOptimizeTours][google.maps.routeoptimization.v1.RouteOptimizationService.BatchOptimizeTours]. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gcs_source (google.maps.routeoptimization_v1.types.GcsSource): - A Google Cloud Storage location. This must be - a single object (file). - - This field is a member of `oneof`_ ``source``. - data_format (google.maps.routeoptimization_v1.types.DataFormat): - Required. The input data format. - """ - - gcs_source: 'GcsSource' = proto.Field( - proto.MESSAGE, - number=1, - oneof='source', - message='GcsSource', - ) - data_format: 'DataFormat' = proto.Field( - proto.ENUM, - number=2, - enum='DataFormat', - ) - - -class OutputConfig(proto.Message): - r"""Specify a destination for - [BatchOptimizeTours][google.maps.routeoptimization.v1.RouteOptimizationService.BatchOptimizeTours] - results. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gcs_destination (google.maps.routeoptimization_v1.types.GcsDestination): - The Google Cloud Storage location to write - the output to. - - This field is a member of `oneof`_ ``destination``. - data_format (google.maps.routeoptimization_v1.types.DataFormat): - Required. The output data format. - """ - - gcs_destination: 'GcsDestination' = proto.Field( - proto.MESSAGE, - number=1, - oneof='destination', - message='GcsDestination', - ) - data_format: 'DataFormat' = proto.Field( - proto.ENUM, - number=2, - enum='DataFormat', - ) - - -class GcsSource(proto.Message): - r"""The Google Cloud Storage location where the input file will - be read from. - - Attributes: - uri (str): - Required. URI of a Google Cloud Storage object with the - format ``gs://bucket/path/to/object``. - """ - - uri: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GcsDestination(proto.Message): - r"""The Google Cloud Storage location where the output file(s) - will be written to. - - Attributes: - uri (str): - Required. Google Cloud Storage URI. - """ - - uri: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/mypy.ini b/owl-bot-staging/google-maps-routeoptimization/v1/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/noxfile.py b/owl-bot-staging/google-maps-routeoptimization/v1/noxfile.py deleted file mode 100644 index 4d8faceb4ca0..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/noxfile.py +++ /dev/null @@ -1,280 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", - "3.12", - "3.13", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = 'google-maps-routeoptimization' - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.13" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "prerelease_deps", -] - -@nox.session(python=ALL_PYTHON) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def unit(session, protobuf_implementation): - """Run the unit test suite.""" - - 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+") - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") - - # 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") - - session.run( - 'py.test', - '--quiet', - '--cov=google/maps/routeoptimization_v1/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - -@nox.session(python=ALL_PYTHON[-1]) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def prerelease_deps(session, protobuf_implementation): - """Run the unit test suite against pre-release versions of dependencies.""" - - 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 test environment dependencies - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - - # Install the package without dependencies - session.install('-e', '.', '--no-deps') - - # We test the minimum dependency versions using the minimum Python - # version so the lowest python runtime that we test has a corresponding constraints - # file, located at `testing/constraints--.txt`, which contains all of the - # 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 - ) - ] - - session.install(*constraints_deps) - - prerel_deps = [ - "googleapis-common-protos", - "google-api-core", - "google-auth", - # Exclude grpcio!=1.67.0rc1 which does not support python 3.13 - "grpcio!=1.67.0rc1", - "grpcio-status", - "protobuf", - "proto-plus", - ] - - for dep in prerel_deps: - session.install("--pre", "--no-deps", "--upgrade", dep) - - # Remaining dependencies - other_deps = [ - "requests", - ] - session.install(*other_deps) - - # Print out prerelease package versions - - session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") - session.run("python", "-c", "import google.auth; print(google.auth.__version__)") - session.run("python", "-c", "import grpc; print(grpc.__version__)") - session.run( - "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" - ) - session.run( - "python", "-c", "import proto; print(proto.__version__)" - ) - - session.run( - 'py.test', - '--quiet', - '--cov=google/maps/routeoptimization_v1/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - - -@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=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 docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==7.0.1", "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=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", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/samples/generated_samples/routeoptimization_v1_generated_route_optimization_batch_optimize_tours_async.py b/owl-bot-staging/google-maps-routeoptimization/v1/samples/generated_samples/routeoptimization_v1_generated_route_optimization_batch_optimize_tours_async.py deleted file mode 100644 index 6086f976fcca..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/samples/generated_samples/routeoptimization_v1_generated_route_optimization_batch_optimize_tours_async.py +++ /dev/null @@ -1,63 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchOptimizeTours -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-routeoptimization - - -# [START routeoptimization_v1_generated_RouteOptimization_BatchOptimizeTours_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.maps import routeoptimization_v1 - - -async def sample_batch_optimize_tours(): - # Create a client - client = routeoptimization_v1.RouteOptimizationAsyncClient() - - # Initialize request argument(s) - model_configs = routeoptimization_v1.AsyncModelConfig() - model_configs.input_config.gcs_source.uri = "uri_value" - model_configs.input_config.data_format = "PROTO_TEXT" - model_configs.output_config.gcs_destination.uri = "uri_value" - model_configs.output_config.data_format = "PROTO_TEXT" - - request = routeoptimization_v1.BatchOptimizeToursRequest( - parent="parent_value", - model_configs=model_configs, - ) - - # Make the request - operation = client.batch_optimize_tours(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END routeoptimization_v1_generated_RouteOptimization_BatchOptimizeTours_async] diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/samples/generated_samples/routeoptimization_v1_generated_route_optimization_batch_optimize_tours_sync.py b/owl-bot-staging/google-maps-routeoptimization/v1/samples/generated_samples/routeoptimization_v1_generated_route_optimization_batch_optimize_tours_sync.py deleted file mode 100644 index 77ae2122ea29..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/samples/generated_samples/routeoptimization_v1_generated_route_optimization_batch_optimize_tours_sync.py +++ /dev/null @@ -1,63 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchOptimizeTours -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-routeoptimization - - -# [START routeoptimization_v1_generated_RouteOptimization_BatchOptimizeTours_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.maps import routeoptimization_v1 - - -def sample_batch_optimize_tours(): - # Create a client - client = routeoptimization_v1.RouteOptimizationClient() - - # Initialize request argument(s) - model_configs = routeoptimization_v1.AsyncModelConfig() - model_configs.input_config.gcs_source.uri = "uri_value" - model_configs.input_config.data_format = "PROTO_TEXT" - model_configs.output_config.gcs_destination.uri = "uri_value" - model_configs.output_config.data_format = "PROTO_TEXT" - - request = routeoptimization_v1.BatchOptimizeToursRequest( - parent="parent_value", - model_configs=model_configs, - ) - - # Make the request - operation = client.batch_optimize_tours(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END routeoptimization_v1_generated_RouteOptimization_BatchOptimizeTours_sync] diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/samples/generated_samples/routeoptimization_v1_generated_route_optimization_optimize_tours_async.py b/owl-bot-staging/google-maps-routeoptimization/v1/samples/generated_samples/routeoptimization_v1_generated_route_optimization_optimize_tours_async.py deleted file mode 100644 index e27f39d51f1e..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/samples/generated_samples/routeoptimization_v1_generated_route_optimization_optimize_tours_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for OptimizeTours -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-routeoptimization - - -# [START routeoptimization_v1_generated_RouteOptimization_OptimizeTours_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.maps import routeoptimization_v1 - - -async def sample_optimize_tours(): - # Create a client - client = routeoptimization_v1.RouteOptimizationAsyncClient() - - # Initialize request argument(s) - request = routeoptimization_v1.OptimizeToursRequest( - parent="parent_value", - ) - - # Make the request - response = await client.optimize_tours(request=request) - - # Handle the response - print(response) - -# [END routeoptimization_v1_generated_RouteOptimization_OptimizeTours_async] diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/samples/generated_samples/routeoptimization_v1_generated_route_optimization_optimize_tours_sync.py b/owl-bot-staging/google-maps-routeoptimization/v1/samples/generated_samples/routeoptimization_v1_generated_route_optimization_optimize_tours_sync.py deleted file mode 100644 index dd85447bf985..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/samples/generated_samples/routeoptimization_v1_generated_route_optimization_optimize_tours_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for OptimizeTours -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-routeoptimization - - -# [START routeoptimization_v1_generated_RouteOptimization_OptimizeTours_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.maps import routeoptimization_v1 - - -def sample_optimize_tours(): - # Create a client - client = routeoptimization_v1.RouteOptimizationClient() - - # Initialize request argument(s) - request = routeoptimization_v1.OptimizeToursRequest( - parent="parent_value", - ) - - # Make the request - response = client.optimize_tours(request=request) - - # Handle the response - print(response) - -# [END routeoptimization_v1_generated_RouteOptimization_OptimizeTours_sync] diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/samples/generated_samples/snippet_metadata_google.maps.routeoptimization.v1.json b/owl-bot-staging/google-maps-routeoptimization/v1/samples/generated_samples/snippet_metadata_google.maps.routeoptimization.v1.json deleted file mode 100644 index fcfcf65d2f4f..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/samples/generated_samples/snippet_metadata_google.maps.routeoptimization.v1.json +++ /dev/null @@ -1,321 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.maps.routeoptimization.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "google-maps-routeoptimization", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.routeoptimization_v1.RouteOptimizationAsyncClient", - "shortName": "RouteOptimizationAsyncClient" - }, - "fullName": "google.maps.routeoptimization_v1.RouteOptimizationAsyncClient.batch_optimize_tours", - "method": { - "fullName": "google.maps.routeoptimization.v1.RouteOptimization.BatchOptimizeTours", - "service": { - "fullName": "google.maps.routeoptimization.v1.RouteOptimization", - "shortName": "RouteOptimization" - }, - "shortName": "BatchOptimizeTours" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.routeoptimization_v1.types.BatchOptimizeToursRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "batch_optimize_tours" - }, - "description": "Sample for BatchOptimizeTours", - "file": "routeoptimization_v1_generated_route_optimization_batch_optimize_tours_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "routeoptimization_v1_generated_RouteOptimization_BatchOptimizeTours_async", - "segments": [ - { - "end": 62, - "start": 27, - "type": "FULL" - }, - { - "end": 62, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 52, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 59, - "start": 53, - "type": "REQUEST_EXECUTION" - }, - { - "end": 63, - "start": 60, - "type": "RESPONSE_HANDLING" - } - ], - "title": "routeoptimization_v1_generated_route_optimization_batch_optimize_tours_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.routeoptimization_v1.RouteOptimizationClient", - "shortName": "RouteOptimizationClient" - }, - "fullName": "google.maps.routeoptimization_v1.RouteOptimizationClient.batch_optimize_tours", - "method": { - "fullName": "google.maps.routeoptimization.v1.RouteOptimization.BatchOptimizeTours", - "service": { - "fullName": "google.maps.routeoptimization.v1.RouteOptimization", - "shortName": "RouteOptimization" - }, - "shortName": "BatchOptimizeTours" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.routeoptimization_v1.types.BatchOptimizeToursRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "batch_optimize_tours" - }, - "description": "Sample for BatchOptimizeTours", - "file": "routeoptimization_v1_generated_route_optimization_batch_optimize_tours_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "routeoptimization_v1_generated_RouteOptimization_BatchOptimizeTours_sync", - "segments": [ - { - "end": 62, - "start": 27, - "type": "FULL" - }, - { - "end": 62, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 52, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 59, - "start": 53, - "type": "REQUEST_EXECUTION" - }, - { - "end": 63, - "start": 60, - "type": "RESPONSE_HANDLING" - } - ], - "title": "routeoptimization_v1_generated_route_optimization_batch_optimize_tours_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.routeoptimization_v1.RouteOptimizationAsyncClient", - "shortName": "RouteOptimizationAsyncClient" - }, - "fullName": "google.maps.routeoptimization_v1.RouteOptimizationAsyncClient.optimize_tours", - "method": { - "fullName": "google.maps.routeoptimization.v1.RouteOptimization.OptimizeTours", - "service": { - "fullName": "google.maps.routeoptimization.v1.RouteOptimization", - "shortName": "RouteOptimization" - }, - "shortName": "OptimizeTours" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.routeoptimization_v1.types.OptimizeToursRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.maps.routeoptimization_v1.types.OptimizeToursResponse", - "shortName": "optimize_tours" - }, - "description": "Sample for OptimizeTours", - "file": "routeoptimization_v1_generated_route_optimization_optimize_tours_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "routeoptimization_v1_generated_RouteOptimization_OptimizeTours_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": "routeoptimization_v1_generated_route_optimization_optimize_tours_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.routeoptimization_v1.RouteOptimizationClient", - "shortName": "RouteOptimizationClient" - }, - "fullName": "google.maps.routeoptimization_v1.RouteOptimizationClient.optimize_tours", - "method": { - "fullName": "google.maps.routeoptimization.v1.RouteOptimization.OptimizeTours", - "service": { - "fullName": "google.maps.routeoptimization.v1.RouteOptimization", - "shortName": "RouteOptimization" - }, - "shortName": "OptimizeTours" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.routeoptimization_v1.types.OptimizeToursRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.maps.routeoptimization_v1.types.OptimizeToursResponse", - "shortName": "optimize_tours" - }, - "description": "Sample for OptimizeTours", - "file": "routeoptimization_v1_generated_route_optimization_optimize_tours_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "routeoptimization_v1_generated_RouteOptimization_OptimizeTours_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": "routeoptimization_v1_generated_route_optimization_optimize_tours_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/scripts/fixup_routeoptimization_v1_keywords.py b/owl-bot-staging/google-maps-routeoptimization/v1/scripts/fixup_routeoptimization_v1_keywords.py deleted file mode 100644 index fd04064542c9..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/scripts/fixup_routeoptimization_v1_keywords.py +++ /dev/null @@ -1,177 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 routeoptimizationCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'batch_optimize_tours': ('parent', 'model_configs', ), - 'optimize_tours': ('parent', 'timeout', 'model', 'solving_mode', 'search_mode', 'injected_first_solution_routes', 'injected_solution_constraint', 'refresh_details_routes', 'interpret_injected_solutions_using_labels', 'consider_road_traffic', 'populate_polylines', 'populate_transition_polylines', 'allow_large_deadline_despite_interruption_risk', 'use_geodesic_distances', 'geodesic_meters_per_second', 'max_validation_errors', 'label', ), - } - - 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=routeoptimizationCallTransformer(), -): - """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 routeoptimization 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-maps-routeoptimization/v1/setup.py b/owl-bot-staging/google-maps-routeoptimization/v1/setup.py deleted file mode 100644 index 035a5065f208..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/setup.py +++ /dev/null @@ -1,98 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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-maps-routeoptimization' - - -description = "Google Maps Routeoptimization API client library" - -version = None - -with open(os.path.join(package_root, 'google/maps/routeoptimization/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.0dev,!=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.0dev,!=2.24.0,!=2.25.0", - "proto-plus >= 1.22.3, <2.0.0dev", - "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'", - "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", -] -extras = { -} -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-routeoptimization" - -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-maps-routeoptimization/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.10.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.10.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.11.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.11.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.12.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.12.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.13.txt b/owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.13.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.13.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.7.txt deleted file mode 100644 index fc812592b0ee..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.7.txt +++ /dev/null @@ -1,10 +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.0dev", -# 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 diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.8.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.8.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.9.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.9.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/tests/__init__.py b/owl-bot-staging/google-maps-routeoptimization/v1/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-maps-routeoptimization/v1/tests/unit/__init__.py b/owl-bot-staging/google-maps-routeoptimization/v1/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-maps-routeoptimization/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-maps-routeoptimization/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-maps-routeoptimization/v1/tests/unit/gapic/routeoptimization_v1/__init__.py b/owl-bot-staging/google-maps-routeoptimization/v1/tests/unit/gapic/routeoptimization_v1/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/tests/unit/gapic/routeoptimization_v1/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-maps-routeoptimization/v1/tests/unit/gapic/routeoptimization_v1/test_route_optimization.py b/owl-bot-staging/google-maps-routeoptimization/v1/tests/unit/gapic/routeoptimization_v1/test_route_optimization.py deleted file mode 100644 index 9009b4f0f73f..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/tests/unit/gapic/routeoptimization_v1/test_route_optimization.py +++ /dev/null @@ -1,2698 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.longrunning import operations_pb2 # type: ignore -from google.maps.routeoptimization_v1.services.route_optimization import RouteOptimizationAsyncClient -from google.maps.routeoptimization_v1.services.route_optimization import RouteOptimizationClient -from google.maps.routeoptimization_v1.services.route_optimization import transports -from google.maps.routeoptimization_v1.types import route_optimization_service -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.type import latlng_pb2 # type: ignore -import google.auth - - -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 RouteOptimizationClient._get_default_mtls_endpoint(None) is None - assert RouteOptimizationClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert RouteOptimizationClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert RouteOptimizationClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert RouteOptimizationClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert RouteOptimizationClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert RouteOptimizationClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert RouteOptimizationClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert RouteOptimizationClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - RouteOptimizationClient._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 RouteOptimizationClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert RouteOptimizationClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert RouteOptimizationClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - RouteOptimizationClient._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 RouteOptimizationClient._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 RouteOptimizationClient._get_client_cert_source(None, False) is None - assert RouteOptimizationClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert RouteOptimizationClient._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 RouteOptimizationClient._get_client_cert_source(None, True) is mock_default_cert_source - assert RouteOptimizationClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(RouteOptimizationClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RouteOptimizationClient)) -@mock.patch.object(RouteOptimizationAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RouteOptimizationAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = RouteOptimizationClient._DEFAULT_UNIVERSE - default_endpoint = RouteOptimizationClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = RouteOptimizationClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert RouteOptimizationClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert RouteOptimizationClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == RouteOptimizationClient.DEFAULT_MTLS_ENDPOINT - assert RouteOptimizationClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert RouteOptimizationClient._get_api_endpoint(None, None, default_universe, "always") == RouteOptimizationClient.DEFAULT_MTLS_ENDPOINT - assert RouteOptimizationClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == RouteOptimizationClient.DEFAULT_MTLS_ENDPOINT - assert RouteOptimizationClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert RouteOptimizationClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - RouteOptimizationClient._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 RouteOptimizationClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert RouteOptimizationClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert RouteOptimizationClient._get_universe_domain(None, None) == RouteOptimizationClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - RouteOptimizationClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - - -@pytest.mark.parametrize("client_class,transport_name", [ - (RouteOptimizationClient, "grpc"), - (RouteOptimizationAsyncClient, "grpc_asyncio"), - (RouteOptimizationClient, "rest"), -]) -def test_route_optimization_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 == ( - 'routeoptimization.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://routeoptimization.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.RouteOptimizationGrpcTransport, "grpc"), - (transports.RouteOptimizationGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.RouteOptimizationRestTransport, "rest"), -]) -def test_route_optimization_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", [ - (RouteOptimizationClient, "grpc"), - (RouteOptimizationAsyncClient, "grpc_asyncio"), - (RouteOptimizationClient, "rest"), -]) -def test_route_optimization_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 == ( - 'routeoptimization.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://routeoptimization.googleapis.com' - ) - - -def test_route_optimization_client_get_transport_class(): - transport = RouteOptimizationClient.get_transport_class() - available_transports = [ - transports.RouteOptimizationGrpcTransport, - transports.RouteOptimizationRestTransport, - ] - assert transport in available_transports - - transport = RouteOptimizationClient.get_transport_class("grpc") - assert transport == transports.RouteOptimizationGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (RouteOptimizationClient, transports.RouteOptimizationGrpcTransport, "grpc"), - (RouteOptimizationAsyncClient, transports.RouteOptimizationGrpcAsyncIOTransport, "grpc_asyncio"), - (RouteOptimizationClient, transports.RouteOptimizationRestTransport, "rest"), -]) -@mock.patch.object(RouteOptimizationClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RouteOptimizationClient)) -@mock.patch.object(RouteOptimizationAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RouteOptimizationAsyncClient)) -def test_route_optimization_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(RouteOptimizationClient, '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(RouteOptimizationClient, '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", [ - (RouteOptimizationClient, transports.RouteOptimizationGrpcTransport, "grpc", "true"), - (RouteOptimizationAsyncClient, transports.RouteOptimizationGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (RouteOptimizationClient, transports.RouteOptimizationGrpcTransport, "grpc", "false"), - (RouteOptimizationAsyncClient, transports.RouteOptimizationGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (RouteOptimizationClient, transports.RouteOptimizationRestTransport, "rest", "true"), - (RouteOptimizationClient, transports.RouteOptimizationRestTransport, "rest", "false"), -]) -@mock.patch.object(RouteOptimizationClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RouteOptimizationClient)) -@mock.patch.object(RouteOptimizationAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RouteOptimizationAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_route_optimization_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", [ - RouteOptimizationClient, RouteOptimizationAsyncClient -]) -@mock.patch.object(RouteOptimizationClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RouteOptimizationClient)) -@mock.patch.object(RouteOptimizationAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RouteOptimizationAsyncClient)) -def test_route_optimization_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", [ - RouteOptimizationClient, RouteOptimizationAsyncClient -]) -@mock.patch.object(RouteOptimizationClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RouteOptimizationClient)) -@mock.patch.object(RouteOptimizationAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RouteOptimizationAsyncClient)) -def test_route_optimization_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = RouteOptimizationClient._DEFAULT_UNIVERSE - default_endpoint = RouteOptimizationClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = RouteOptimizationClient._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", [ - (RouteOptimizationClient, transports.RouteOptimizationGrpcTransport, "grpc"), - (RouteOptimizationAsyncClient, transports.RouteOptimizationGrpcAsyncIOTransport, "grpc_asyncio"), - (RouteOptimizationClient, transports.RouteOptimizationRestTransport, "rest"), -]) -def test_route_optimization_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", [ - (RouteOptimizationClient, transports.RouteOptimizationGrpcTransport, "grpc", grpc_helpers), - (RouteOptimizationAsyncClient, transports.RouteOptimizationGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (RouteOptimizationClient, transports.RouteOptimizationRestTransport, "rest", None), -]) -def test_route_optimization_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_route_optimization_client_client_options_from_dict(): - with mock.patch('google.maps.routeoptimization_v1.services.route_optimization.transports.RouteOptimizationGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = RouteOptimizationClient( - 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", [ - (RouteOptimizationClient, transports.RouteOptimizationGrpcTransport, "grpc", grpc_helpers), - (RouteOptimizationAsyncClient, transports.RouteOptimizationGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_route_optimization_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( - "routeoptimization.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=None, - default_host="routeoptimization.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - route_optimization_service.OptimizeToursRequest, - dict, -]) -def test_optimize_tours(request_type, transport: str = 'grpc'): - client = RouteOptimizationClient( - 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.optimize_tours), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = route_optimization_service.OptimizeToursResponse( - request_label='request_label_value', - ) - response = client.optimize_tours(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = route_optimization_service.OptimizeToursRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, route_optimization_service.OptimizeToursResponse) - assert response.request_label == 'request_label_value' - - -def test_optimize_tours_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 = RouteOptimizationClient( - 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 = route_optimization_service.OptimizeToursRequest( - parent='parent_value', - label='label_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.optimize_tours), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.optimize_tours(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == route_optimization_service.OptimizeToursRequest( - parent='parent_value', - label='label_value', - ) - -def test_optimize_tours_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = RouteOptimizationClient( - 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.optimize_tours in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.optimize_tours] = mock_rpc - request = {} - client.optimize_tours(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.optimize_tours(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_optimize_tours_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = RouteOptimizationAsyncClient( - 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.optimize_tours in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.optimize_tours] = mock_rpc - - request = {} - await client.optimize_tours(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.optimize_tours(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_optimize_tours_async(transport: str = 'grpc_asyncio', request_type=route_optimization_service.OptimizeToursRequest): - client = RouteOptimizationAsyncClient( - 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.optimize_tours), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(route_optimization_service.OptimizeToursResponse( - request_label='request_label_value', - )) - response = await client.optimize_tours(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = route_optimization_service.OptimizeToursRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, route_optimization_service.OptimizeToursResponse) - assert response.request_label == 'request_label_value' - - -@pytest.mark.asyncio -async def test_optimize_tours_async_from_dict(): - await test_optimize_tours_async(request_type=dict) - -def test_optimize_tours_field_headers(): - client = RouteOptimizationClient( - 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 = route_optimization_service.OptimizeToursRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.optimize_tours), - '__call__') as call: - call.return_value = route_optimization_service.OptimizeToursResponse() - client.optimize_tours(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_optimize_tours_field_headers_async(): - client = RouteOptimizationAsyncClient( - 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 = route_optimization_service.OptimizeToursRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.optimize_tours), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(route_optimization_service.OptimizeToursResponse()) - await client.optimize_tours(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - route_optimization_service.BatchOptimizeToursRequest, - dict, -]) -def test_batch_optimize_tours(request_type, transport: str = 'grpc'): - client = RouteOptimizationClient( - 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.batch_optimize_tours), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.batch_optimize_tours(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = route_optimization_service.BatchOptimizeToursRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_batch_optimize_tours_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 = RouteOptimizationClient( - 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 = route_optimization_service.BatchOptimizeToursRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_optimize_tours), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.batch_optimize_tours(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == route_optimization_service.BatchOptimizeToursRequest( - parent='parent_value', - ) - -def test_batch_optimize_tours_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = RouteOptimizationClient( - 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.batch_optimize_tours in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.batch_optimize_tours] = mock_rpc - request = {} - client.batch_optimize_tours(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.batch_optimize_tours(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_batch_optimize_tours_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = RouteOptimizationAsyncClient( - 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.batch_optimize_tours in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.batch_optimize_tours] = mock_rpc - - request = {} - await client.batch_optimize_tours(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.batch_optimize_tours(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_batch_optimize_tours_async(transport: str = 'grpc_asyncio', request_type=route_optimization_service.BatchOptimizeToursRequest): - client = RouteOptimizationAsyncClient( - 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.batch_optimize_tours), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.batch_optimize_tours(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = route_optimization_service.BatchOptimizeToursRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_batch_optimize_tours_async_from_dict(): - await test_batch_optimize_tours_async(request_type=dict) - -def test_batch_optimize_tours_field_headers(): - client = RouteOptimizationClient( - 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 = route_optimization_service.BatchOptimizeToursRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_optimize_tours), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.batch_optimize_tours(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_batch_optimize_tours_field_headers_async(): - client = RouteOptimizationAsyncClient( - 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 = route_optimization_service.BatchOptimizeToursRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_optimize_tours), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.batch_optimize_tours(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_optimize_tours_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 = RouteOptimizationClient( - 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.optimize_tours in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.optimize_tours] = mock_rpc - - request = {} - client.optimize_tours(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.optimize_tours(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_optimize_tours_rest_required_fields(request_type=route_optimization_service.OptimizeToursRequest): - transport_class = transports.RouteOptimizationRestTransport - - 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()).optimize_tours._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()).optimize_tours._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 = RouteOptimizationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = route_optimization_service.OptimizeToursResponse() - # 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 = route_optimization_service.OptimizeToursResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.optimize_tours(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_optimize_tours_rest_unset_required_fields(): - transport = transports.RouteOptimizationRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.optimize_tours._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -def test_batch_optimize_tours_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 = RouteOptimizationClient( - 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.batch_optimize_tours in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.batch_optimize_tours] = mock_rpc - - request = {} - client.batch_optimize_tours(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.batch_optimize_tours(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_batch_optimize_tours_rest_required_fields(request_type=route_optimization_service.BatchOptimizeToursRequest): - transport_class = transports.RouteOptimizationRestTransport - - 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()).batch_optimize_tours._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()).batch_optimize_tours._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 = RouteOptimizationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields 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 = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.batch_optimize_tours(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_batch_optimize_tours_rest_unset_required_fields(): - transport = transports.RouteOptimizationRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.batch_optimize_tours._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "modelConfigs", ))) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.RouteOptimizationGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RouteOptimizationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.RouteOptimizationGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RouteOptimizationClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.RouteOptimizationGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = RouteOptimizationClient( - 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 = RouteOptimizationClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.RouteOptimizationGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RouteOptimizationClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.RouteOptimizationGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = RouteOptimizationClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.RouteOptimizationGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.RouteOptimizationGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.RouteOptimizationGrpcTransport, - transports.RouteOptimizationGrpcAsyncIOTransport, - transports.RouteOptimizationRestTransport, -]) -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 = RouteOptimizationClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = RouteOptimizationClient( - 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_optimize_tours_empty_call_grpc(): - client = RouteOptimizationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.optimize_tours), - '__call__') as call: - call.return_value = route_optimization_service.OptimizeToursResponse() - client.optimize_tours(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = route_optimization_service.OptimizeToursRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_batch_optimize_tours_empty_call_grpc(): - client = RouteOptimizationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.batch_optimize_tours), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.batch_optimize_tours(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = route_optimization_service.BatchOptimizeToursRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = RouteOptimizationAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = RouteOptimizationAsyncClient( - 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_optimize_tours_empty_call_grpc_asyncio(): - client = RouteOptimizationAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.optimize_tours), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(route_optimization_service.OptimizeToursResponse( - request_label='request_label_value', - )) - await client.optimize_tours(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = route_optimization_service.OptimizeToursRequest() - - assert args[0] == request_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_batch_optimize_tours_empty_call_grpc_asyncio(): - client = RouteOptimizationAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.batch_optimize_tours), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.batch_optimize_tours(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = route_optimization_service.BatchOptimizeToursRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = RouteOptimizationClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_optimize_tours_rest_bad_request(request_type=route_optimization_service.OptimizeToursRequest): - client = RouteOptimizationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a 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.optimize_tours(request) - - -@pytest.mark.parametrize("request_type", [ - route_optimization_service.OptimizeToursRequest, - dict, -]) -def test_optimize_tours_rest_call_success(request_type): - client = RouteOptimizationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = route_optimization_service.OptimizeToursResponse( - request_label='request_label_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 = route_optimization_service.OptimizeToursResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.optimize_tours(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, route_optimization_service.OptimizeToursResponse) - assert response.request_label == 'request_label_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_optimize_tours_rest_interceptors(null_interceptor): - transport = transports.RouteOptimizationRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RouteOptimizationRestInterceptor(), - ) - client = RouteOptimizationClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RouteOptimizationRestInterceptor, "post_optimize_tours") as post, \ - mock.patch.object(transports.RouteOptimizationRestInterceptor, "pre_optimize_tours") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = route_optimization_service.OptimizeToursRequest.pb(route_optimization_service.OptimizeToursRequest()) - 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 = route_optimization_service.OptimizeToursResponse.to_json(route_optimization_service.OptimizeToursResponse()) - req.return_value.content = return_value - - request = route_optimization_service.OptimizeToursRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = route_optimization_service.OptimizeToursResponse() - - client.optimize_tours(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_batch_optimize_tours_rest_bad_request(request_type=route_optimization_service.BatchOptimizeToursRequest): - client = RouteOptimizationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a 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.batch_optimize_tours(request) - - -@pytest.mark.parametrize("request_type", [ - route_optimization_service.BatchOptimizeToursRequest, - dict, -]) -def test_batch_optimize_tours_rest_call_success(request_type): - client = RouteOptimizationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.batch_optimize_tours(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_optimize_tours_rest_interceptors(null_interceptor): - transport = transports.RouteOptimizationRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RouteOptimizationRestInterceptor(), - ) - client = RouteOptimizationClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.RouteOptimizationRestInterceptor, "post_batch_optimize_tours") as post, \ - mock.patch.object(transports.RouteOptimizationRestInterceptor, "pre_batch_optimize_tours") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = route_optimization_service.BatchOptimizeToursRequest.pb(route_optimization_service.BatchOptimizeToursRequest()) - 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 = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = route_optimization_service.BatchOptimizeToursRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.batch_optimize_tours(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_operation_rest_bad_request(request_type=operations_pb2.GetOperationRequest): - client = RouteOptimizationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = RouteOptimizationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_initialize_client_w_rest(): - client = RouteOptimizationClient( - 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_optimize_tours_empty_call_rest(): - client = RouteOptimizationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.optimize_tours), - '__call__') as call: - client.optimize_tours(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = route_optimization_service.OptimizeToursRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_batch_optimize_tours_empty_call_rest(): - client = RouteOptimizationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.batch_optimize_tours), - '__call__') as call: - client.batch_optimize_tours(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = route_optimization_service.BatchOptimizeToursRequest() - - assert args[0] == request_msg - - -def test_route_optimization_rest_lro_client(): - client = RouteOptimizationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - transport = client.transport - - # Ensure that we have an api-core operations client. - assert isinstance( - transport.operations_client, -operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = RouteOptimizationClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.RouteOptimizationGrpcTransport, - ) - -def test_route_optimization_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.RouteOptimizationTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_route_optimization_base_transport(): - # Instantiate the base transport. - with mock.patch('google.maps.routeoptimization_v1.services.route_optimization.transports.RouteOptimizationTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.RouteOptimizationTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'optimize_tours', - 'batch_optimize_tours', - 'get_operation', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_route_optimization_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.maps.routeoptimization_v1.services.route_optimization.transports.RouteOptimizationTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.RouteOptimizationTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_route_optimization_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.maps.routeoptimization_v1.services.route_optimization.transports.RouteOptimizationTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.RouteOptimizationTransport() - adc.assert_called_once() - - -def test_route_optimization_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) - RouteOptimizationClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.RouteOptimizationGrpcTransport, - transports.RouteOptimizationGrpcAsyncIOTransport, - ], -) -def test_route_optimization_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.RouteOptimizationGrpcTransport, - transports.RouteOptimizationGrpcAsyncIOTransport, - transports.RouteOptimizationRestTransport, - ], -) -def test_route_optimization_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.RouteOptimizationGrpcTransport, grpc_helpers), - (transports.RouteOptimizationGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_route_optimization_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( - "routeoptimization.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=["1", "2"], - default_host="routeoptimization.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.RouteOptimizationGrpcTransport, transports.RouteOptimizationGrpcAsyncIOTransport]) -def test_route_optimization_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_route_optimization_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.RouteOptimizationRestTransport ( - 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_route_optimization_host_no_port(transport_name): - client = RouteOptimizationClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='routeoptimization.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'routeoptimization.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://routeoptimization.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_route_optimization_host_with_port(transport_name): - client = RouteOptimizationClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='routeoptimization.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'routeoptimization.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://routeoptimization.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_route_optimization_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = RouteOptimizationClient( - credentials=creds1, - transport=transport_name, - ) - client2 = RouteOptimizationClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.optimize_tours._session - session2 = client2.transport.optimize_tours._session - assert session1 != session2 - session1 = client1.transport.batch_optimize_tours._session - session2 = client2.transport.batch_optimize_tours._session - assert session1 != session2 -def test_route_optimization_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.RouteOptimizationGrpcTransport( - 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_route_optimization_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.RouteOptimizationGrpcAsyncIOTransport( - 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.RouteOptimizationGrpcTransport, transports.RouteOptimizationGrpcAsyncIOTransport]) -def test_route_optimization_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.RouteOptimizationGrpcTransport, transports.RouteOptimizationGrpcAsyncIOTransport]) -def test_route_optimization_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_route_optimization_grpc_lro_client(): - client = RouteOptimizationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_route_optimization_grpc_lro_async_client(): - client = RouteOptimizationAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = RouteOptimizationClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = RouteOptimizationClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = RouteOptimizationClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = RouteOptimizationClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = RouteOptimizationClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = RouteOptimizationClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = RouteOptimizationClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = RouteOptimizationClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = RouteOptimizationClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = RouteOptimizationClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = RouteOptimizationClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = RouteOptimizationClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = RouteOptimizationClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = RouteOptimizationClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = RouteOptimizationClient.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.RouteOptimizationTransport, '_prep_wrapped_messages') as prep: - client = RouteOptimizationClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.RouteOptimizationTransport, '_prep_wrapped_messages') as prep: - transport_class = RouteOptimizationClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -def test_get_operation(transport: str = "grpc"): - client = RouteOptimizationClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc_asyncio"): - client = RouteOptimizationAsyncClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_field_headers(): - client = RouteOptimizationClient( - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = operations_pb2.Operation() - - client.get_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_operation_field_headers_async(): - client = RouteOptimizationAsyncClient( - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(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=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - client = RouteOptimizationClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - - response = client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_operation_from_dict_async(): - client = RouteOptimizationAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close_grpc(): - client = RouteOptimizationClient( - 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 = RouteOptimizationAsyncClient( - 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 = RouteOptimizationClient( - 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 = RouteOptimizationClient( - 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", [ - (RouteOptimizationClient, transports.RouteOptimizationGrpcTransport), - (RouteOptimizationAsyncClient, transports.RouteOptimizationGrpcAsyncIOTransport), -]) -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-maps-routing/v2/.coveragerc b/owl-bot-staging/google-maps-routing/v2/.coveragerc deleted file mode 100644 index d0ce5597b0a9..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/maps/routing/__init__.py - google/maps/routing/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-maps-routing/v2/.flake8 b/owl-bot-staging/google-maps-routing/v2/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/google-maps-routing/v2/MANIFEST.in b/owl-bot-staging/google-maps-routing/v2/MANIFEST.in deleted file mode 100644 index c5b56c111c00..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/maps/routing *.py -recursive-include google/maps/routing_v2 *.py diff --git a/owl-bot-staging/google-maps-routing/v2/README.rst b/owl-bot-staging/google-maps-routing/v2/README.rst deleted file mode 100644 index f0002366e552..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Maps Routing 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 Maps Routing 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 diff --git a/owl-bot-staging/google-maps-routing/v2/docs/_static/custom.css b/owl-bot-staging/google-maps-routing/v2/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/docs/_static/custom.css +++ /dev/null @@ -1,3 +0,0 @@ -dl.field-list > dt { - min-width: 100px -} diff --git a/owl-bot-staging/google-maps-routing/v2/docs/conf.py b/owl-bot-staging/google-maps-routing/v2/docs/conf.py deleted file mode 100644 index 4b30f5a14b3e..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-maps-routing 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("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# 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.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -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-maps-routing" -copyright = u"2023, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# 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 = 'en' - -# 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"] - -# 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 Maps Client Libraries for Python", - "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-maps-routing-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-maps-routing.tex", - u"google-maps-routing 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-maps-routing", - u"Google Maps Routing 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-maps-routing", - u"google-maps-routing Documentation", - author, - "google-maps-routing", - "GAPIC library for Google Maps Routing API", - "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": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", 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-maps-routing/v2/docs/index.rst b/owl-bot-staging/google-maps-routing/v2/docs/index.rst deleted file mode 100644 index 3a2d987095fc..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - routing_v2/services_ - routing_v2/types_ diff --git a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst deleted file mode 100644 index 3d52309cddae..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst +++ /dev/null @@ -1,6 +0,0 @@ -Routes ------------------------- - -.. automodule:: google.maps.routing_v2.services.routes - :members: - :inherited-members: diff --git a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services_.rst b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services_.rst deleted file mode 100644 index e96568dc434c..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Maps Routing v2 API -======================================= -.. toctree:: - :maxdepth: 2 - - routes diff --git a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types_.rst b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types_.rst deleted file mode 100644 index 176a5a812cf8..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Maps Routing v2 API -==================================== - -.. automodule:: google.maps.routing_v2.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py deleted file mode 100644 index 8d0ab7a57d0d..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py +++ /dev/null @@ -1,115 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.routing import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.maps.routing_v2.services.routes.client import RoutesClient -from google.maps.routing_v2.services.routes.async_client import RoutesAsyncClient - -from google.maps.routing_v2.types.fallback_info import FallbackInfo -from google.maps.routing_v2.types.fallback_info import FallbackReason -from google.maps.routing_v2.types.fallback_info import FallbackRoutingMode -from google.maps.routing_v2.types.geocoding_results import GeocodedWaypoint -from google.maps.routing_v2.types.geocoding_results import GeocodingResults -from google.maps.routing_v2.types.localized_time import LocalizedTime -from google.maps.routing_v2.types.location import Location -from google.maps.routing_v2.types.maneuver import Maneuver -from google.maps.routing_v2.types.navigation_instruction import NavigationInstruction -from google.maps.routing_v2.types.polyline import Polyline -from google.maps.routing_v2.types.polyline import PolylineEncoding -from google.maps.routing_v2.types.polyline import PolylineQuality -from google.maps.routing_v2.types.polyline_details import PolylineDetails -from google.maps.routing_v2.types.route import Route -from google.maps.routing_v2.types.route import RouteLeg -from google.maps.routing_v2.types.route import RouteLegStep -from google.maps.routing_v2.types.route import RouteLegStepTransitDetails -from google.maps.routing_v2.types.route import RouteLegStepTravelAdvisory -from google.maps.routing_v2.types.route import RouteLegTravelAdvisory -from google.maps.routing_v2.types.route import RouteTravelAdvisory -from google.maps.routing_v2.types.route_label import RouteLabel -from google.maps.routing_v2.types.route_modifiers import RouteModifiers -from google.maps.routing_v2.types.route_travel_mode import RouteTravelMode -from google.maps.routing_v2.types.routes_service import ComputeRouteMatrixRequest -from google.maps.routing_v2.types.routes_service import ComputeRoutesRequest -from google.maps.routing_v2.types.routes_service import ComputeRoutesResponse -from google.maps.routing_v2.types.routes_service import RouteMatrixDestination -from google.maps.routing_v2.types.routes_service import RouteMatrixElement -from google.maps.routing_v2.types.routes_service import RouteMatrixOrigin -from google.maps.routing_v2.types.routes_service import RouteMatrixElementCondition -from google.maps.routing_v2.types.routing_preference import RoutingPreference -from google.maps.routing_v2.types.speed_reading_interval import SpeedReadingInterval -from google.maps.routing_v2.types.toll_info import TollInfo -from google.maps.routing_v2.types.toll_passes import TollPass -from google.maps.routing_v2.types.traffic_model import TrafficModel -from google.maps.routing_v2.types.transit import TransitAgency -from google.maps.routing_v2.types.transit import TransitLine -from google.maps.routing_v2.types.transit import TransitStop -from google.maps.routing_v2.types.transit import TransitVehicle -from google.maps.routing_v2.types.transit_preferences import TransitPreferences -from google.maps.routing_v2.types.units import Units -from google.maps.routing_v2.types.vehicle_emission_type import VehicleEmissionType -from google.maps.routing_v2.types.vehicle_info import VehicleInfo -from google.maps.routing_v2.types.waypoint import Waypoint - -__all__ = ('RoutesClient', - 'RoutesAsyncClient', - 'FallbackInfo', - 'FallbackReason', - 'FallbackRoutingMode', - 'GeocodedWaypoint', - 'GeocodingResults', - 'LocalizedTime', - 'Location', - 'Maneuver', - 'NavigationInstruction', - 'Polyline', - 'PolylineEncoding', - 'PolylineQuality', - 'PolylineDetails', - 'Route', - 'RouteLeg', - 'RouteLegStep', - 'RouteLegStepTransitDetails', - 'RouteLegStepTravelAdvisory', - 'RouteLegTravelAdvisory', - 'RouteTravelAdvisory', - 'RouteLabel', - 'RouteModifiers', - 'RouteTravelMode', - 'ComputeRouteMatrixRequest', - 'ComputeRoutesRequest', - 'ComputeRoutesResponse', - 'RouteMatrixDestination', - 'RouteMatrixElement', - 'RouteMatrixOrigin', - 'RouteMatrixElementCondition', - 'RoutingPreference', - 'SpeedReadingInterval', - 'TollInfo', - 'TollPass', - 'TrafficModel', - 'TransitAgency', - 'TransitLine', - 'TransitStop', - 'TransitVehicle', - 'TransitPreferences', - 'Units', - 'VehicleEmissionType', - 'VehicleInfo', - 'Waypoint', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-maps-routing/v2/google/maps/routing/py.typed b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed deleted file mode 100644 index d62a4b821347..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-maps-routing package uses inline types. diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py deleted file mode 100644 index 05368186e00b..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py +++ /dev/null @@ -1,116 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.routing_v2 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.routes import RoutesClient -from .services.routes import RoutesAsyncClient - -from .types.fallback_info import FallbackInfo -from .types.fallback_info import FallbackReason -from .types.fallback_info import FallbackRoutingMode -from .types.geocoding_results import GeocodedWaypoint -from .types.geocoding_results import GeocodingResults -from .types.localized_time import LocalizedTime -from .types.location import Location -from .types.maneuver import Maneuver -from .types.navigation_instruction import NavigationInstruction -from .types.polyline import Polyline -from .types.polyline import PolylineEncoding -from .types.polyline import PolylineQuality -from .types.polyline_details import PolylineDetails -from .types.route import Route -from .types.route import RouteLeg -from .types.route import RouteLegStep -from .types.route import RouteLegStepTransitDetails -from .types.route import RouteLegStepTravelAdvisory -from .types.route import RouteLegTravelAdvisory -from .types.route import RouteTravelAdvisory -from .types.route_label import RouteLabel -from .types.route_modifiers import RouteModifiers -from .types.route_travel_mode import RouteTravelMode -from .types.routes_service import ComputeRouteMatrixRequest -from .types.routes_service import ComputeRoutesRequest -from .types.routes_service import ComputeRoutesResponse -from .types.routes_service import RouteMatrixDestination -from .types.routes_service import RouteMatrixElement -from .types.routes_service import RouteMatrixOrigin -from .types.routes_service import RouteMatrixElementCondition -from .types.routing_preference import RoutingPreference -from .types.speed_reading_interval import SpeedReadingInterval -from .types.toll_info import TollInfo -from .types.toll_passes import TollPass -from .types.traffic_model import TrafficModel -from .types.transit import TransitAgency -from .types.transit import TransitLine -from .types.transit import TransitStop -from .types.transit import TransitVehicle -from .types.transit_preferences import TransitPreferences -from .types.units import Units -from .types.vehicle_emission_type import VehicleEmissionType -from .types.vehicle_info import VehicleInfo -from .types.waypoint import Waypoint - -__all__ = ( - 'RoutesAsyncClient', -'ComputeRouteMatrixRequest', -'ComputeRoutesRequest', -'ComputeRoutesResponse', -'FallbackInfo', -'FallbackReason', -'FallbackRoutingMode', -'GeocodedWaypoint', -'GeocodingResults', -'LocalizedTime', -'Location', -'Maneuver', -'NavigationInstruction', -'Polyline', -'PolylineDetails', -'PolylineEncoding', -'PolylineQuality', -'Route', -'RouteLabel', -'RouteLeg', -'RouteLegStep', -'RouteLegStepTransitDetails', -'RouteLegStepTravelAdvisory', -'RouteLegTravelAdvisory', -'RouteMatrixDestination', -'RouteMatrixElement', -'RouteMatrixElementCondition', -'RouteMatrixOrigin', -'RouteModifiers', -'RouteTravelAdvisory', -'RouteTravelMode', -'RoutesClient', -'RoutingPreference', -'SpeedReadingInterval', -'TollInfo', -'TollPass', -'TrafficModel', -'TransitAgency', -'TransitLine', -'TransitPreferences', -'TransitStop', -'TransitVehicle', -'Units', -'VehicleEmissionType', -'VehicleInfo', -'Waypoint', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json deleted file mode 100644 index 8382cea1d39a..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json +++ /dev/null @@ -1,58 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.maps.routing_v2", - "protoPackage": "google.maps.routing.v2", - "schema": "1.0", - "services": { - "Routes": { - "clients": { - "grpc": { - "libraryClient": "RoutesClient", - "rpcs": { - "ComputeRouteMatrix": { - "methods": [ - "compute_route_matrix" - ] - }, - "ComputeRoutes": { - "methods": [ - "compute_routes" - ] - } - } - }, - "grpc-async": { - "libraryClient": "RoutesAsyncClient", - "rpcs": { - "ComputeRouteMatrix": { - "methods": [ - "compute_route_matrix" - ] - }, - "ComputeRoutes": { - "methods": [ - "compute_routes" - ] - } - } - }, - "rest": { - "libraryClient": "RoutesClient", - "rpcs": { - "ComputeRouteMatrix": { - "methods": [ - "compute_route_matrix" - ] - }, - "ComputeRoutes": { - "methods": [ - "compute_routes" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-maps-routing/v2/google/maps/routing_v2/py.typed b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed deleted file mode 100644 index d62a4b821347..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-maps-routing package uses inline types. diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py deleted file mode 100644 index 1d5f9c21bfea..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 RoutesClient -from .async_client import RoutesAsyncClient - -__all__ = ( - 'RoutesClient', - 'RoutesAsyncClient', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py deleted file mode 100644 index 5201b0eb6994..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py +++ /dev/null @@ -1,486 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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, AsyncIterable, Awaitable, Sequence, Tuple, Type, Union - -from google.maps.routing_v2 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 - - -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.maps.routing_v2.types import fallback_info -from google.maps.routing_v2.types import geocoding_results -from google.maps.routing_v2.types import route -from google.maps.routing_v2.types import routes_service -from google.protobuf import duration_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from .transports.base import RoutesTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import RoutesGrpcAsyncIOTransport -from .client import RoutesClient - -try: - from google.api_core import client_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 RoutesAsyncClient: - """The Routes API.""" - - _client: RoutesClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = RoutesClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = RoutesClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = RoutesClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = RoutesClient._DEFAULT_UNIVERSE - - common_billing_account_path = staticmethod(RoutesClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(RoutesClient.parse_common_billing_account_path) - common_folder_path = staticmethod(RoutesClient.common_folder_path) - parse_common_folder_path = staticmethod(RoutesClient.parse_common_folder_path) - common_organization_path = staticmethod(RoutesClient.common_organization_path) - parse_common_organization_path = staticmethod(RoutesClient.parse_common_organization_path) - common_project_path = staticmethod(RoutesClient.common_project_path) - parse_common_project_path = staticmethod(RoutesClient.parse_common_project_path) - common_location_path = staticmethod(RoutesClient.common_location_path) - parse_common_location_path = staticmethod(RoutesClient.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: - RoutesAsyncClient: The constructed client. - """ - return RoutesClient.from_service_account_info.__func__(RoutesAsyncClient, 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: - RoutesAsyncClient: The constructed client. - """ - return RoutesClient.from_service_account_file.__func__(RoutesAsyncClient, 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 RoutesClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> RoutesTransport: - """Returns the transport used by the client instance. - - Returns: - RoutesTransport: 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 = RoutesClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, RoutesTransport, Callable[..., RoutesTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the routes 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,RoutesTransport,Callable[..., RoutesTransport]]]): - 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 RoutesTransport 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 = RoutesClient( - 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.maps.routing_v2.RoutesAsyncClient`.", - extra = { - "serviceName": "google.maps.routing.v2.Routes", - "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.maps.routing.v2.Routes", - "credentialsType": None, - } - ) - - async def compute_routes(self, - request: Optional[Union[routes_service.ComputeRoutesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> routes_service.ComputeRoutesResponse: - r"""Returns the primary route along with optional alternate routes, - given a set of terminal and intermediate waypoints. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using URL parameter ``$fields`` or ``fields``, or by using an - HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL - parameters and - headers `__). - The value is a comma separated list of field paths. See detailed - documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of Route-level duration, distance, and polyline - (an example production setup): - ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` - - Google discourage the use of the wildcard (``*``) response field - mask, or specifying the field mask at the top level - (``routes``), because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import routing_v2 - - async def sample_compute_routes(): - # Create a client - client = routing_v2.RoutesAsyncClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRoutesRequest( - ) - - # Make the request - response = await client.compute_routes(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.routing_v2.types.ComputeRoutesRequest, dict]]): - The request object. ComputeRoutes request message. - 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.maps.routing_v2.types.ComputeRoutesResponse: - ComputeRoutes the response message. - """ - # 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, routes_service.ComputeRoutesRequest): - request = routes_service.ComputeRoutesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.compute_routes] - - # 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 - - def compute_route_matrix(self, - request: Optional[Union[routes_service.ComputeRouteMatrixRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> Awaitable[AsyncIterable[routes_service.RouteMatrixElement]]: - r"""Takes in a list of origins and destinations and returns a stream - containing route information for each combination of origin and - destination. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using the URL parameter ``$fields`` or ``fields``, or by using - the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available - URL parameters and - headers `__). - The value is a comma separated list of field paths. See this - detailed documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of route durations, distances, element status, - condition, and element indices (an example production setup): - ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` - - It is critical that you include ``status`` in your field mask as - otherwise all messages will appear to be OK. Google discourages - the use of the wildcard (``*``) response field mask, because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import routing_v2 - - async def sample_compute_route_matrix(): - # Create a client - client = routing_v2.RoutesAsyncClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRouteMatrixRequest( - ) - - # Make the request - stream = await client.compute_route_matrix(request=request) - - # Handle the response - async for response in stream: - print(response) - - Args: - request (Optional[Union[google.maps.routing_v2.types.ComputeRouteMatrixRequest, dict]]): - The request object. ComputeRouteMatrix request message - 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: - AsyncIterable[google.maps.routing_v2.types.RouteMatrixElement]: - Contains route information computed - for an origin/destination pair in the - ComputeRouteMatrix API. This proto can - be streamed to the client. - - """ - # 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, routes_service.ComputeRouteMatrixRequest): - request = routes_service.ComputeRouteMatrixRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.compute_route_matrix] - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self) -> "RoutesAsyncClient": - 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__) - - -__all__ = ( - "RoutesAsyncClient", -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py deleted file mode 100644 index e972dc2a27fc..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py +++ /dev/null @@ -1,813 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -import logging as std_logging -import os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Iterable, Sequence, Tuple, Type, Union, cast -import warnings - -from google.maps.routing_v2 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 - -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.maps.routing_v2.types import fallback_info -from google.maps.routing_v2.types import geocoding_results -from google.maps.routing_v2.types import route -from google.maps.routing_v2.types import routes_service -from google.protobuf import duration_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from .transports.base import RoutesTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import RoutesGrpcTransport -from .transports.grpc_asyncio import RoutesGrpcAsyncIOTransport -from .transports.rest import RoutesRestTransport - - -class RoutesClientMeta(type): - """Metaclass for the Routes 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[RoutesTransport]] - _transport_registry["grpc"] = RoutesGrpcTransport - _transport_registry["grpc_asyncio"] = RoutesGrpcAsyncIOTransport - _transport_registry["rest"] = RoutesRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[RoutesTransport]: - """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 RoutesClient(metaclass=RoutesClientMeta): - """The Routes 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 = "routes.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "routes.{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: - RoutesClient: 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: - RoutesClient: 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) -> RoutesTransport: - """Returns the transport used by the client instance. - - Returns: - RoutesTransport: The transport used by the client - instance. - """ - return self._transport - - @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 = RoutesClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = RoutesClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = RoutesClient._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 = RoutesClient._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 - - @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, RoutesTransport, Callable[..., RoutesTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the routes 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,RoutesTransport,Callable[..., RoutesTransport]]]): - 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 RoutesTransport 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 = RoutesClient._read_environment_variables() - self._client_cert_source = RoutesClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = RoutesClient._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, RoutesTransport) - if transport_provided: - # transport is a RoutesTransport 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(RoutesTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - RoutesClient._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[RoutesTransport], Callable[..., RoutesTransport]] = ( - RoutesClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., RoutesTransport], 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.maps.routing_v2.RoutesClient`.", - extra = { - "serviceName": "google.maps.routing.v2.Routes", - "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.maps.routing.v2.Routes", - "credentialsType": None, - } - ) - - def compute_routes(self, - request: Optional[Union[routes_service.ComputeRoutesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> routes_service.ComputeRoutesResponse: - r"""Returns the primary route along with optional alternate routes, - given a set of terminal and intermediate waypoints. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using URL parameter ``$fields`` or ``fields``, or by using an - HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL - parameters and - headers `__). - The value is a comma separated list of field paths. See detailed - documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of Route-level duration, distance, and polyline - (an example production setup): - ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` - - Google discourage the use of the wildcard (``*``) response field - mask, or specifying the field mask at the top level - (``routes``), because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import routing_v2 - - def sample_compute_routes(): - # Create a client - client = routing_v2.RoutesClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRoutesRequest( - ) - - # Make the request - response = client.compute_routes(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.routing_v2.types.ComputeRoutesRequest, dict]): - The request object. ComputeRoutes request message. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.maps.routing_v2.types.ComputeRoutesResponse: - ComputeRoutes the response message. - """ - # 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, routes_service.ComputeRoutesRequest): - request = routes_service.ComputeRoutesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.compute_routes] - - # 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 compute_route_matrix(self, - request: Optional[Union[routes_service.ComputeRouteMatrixRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> Iterable[routes_service.RouteMatrixElement]: - r"""Takes in a list of origins and destinations and returns a stream - containing route information for each combination of origin and - destination. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using the URL parameter ``$fields`` or ``fields``, or by using - the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available - URL parameters and - headers `__). - The value is a comma separated list of field paths. See this - detailed documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of route durations, distances, element status, - condition, and element indices (an example production setup): - ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` - - It is critical that you include ``status`` in your field mask as - otherwise all messages will appear to be OK. Google discourages - the use of the wildcard (``*``) response field mask, because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import routing_v2 - - def sample_compute_route_matrix(): - # Create a client - client = routing_v2.RoutesClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRouteMatrixRequest( - ) - - # Make the request - stream = client.compute_route_matrix(request=request) - - # Handle the response - for response in stream: - print(response) - - Args: - request (Union[google.maps.routing_v2.types.ComputeRouteMatrixRequest, dict]): - The request object. ComputeRouteMatrix request message - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - Iterable[google.maps.routing_v2.types.RouteMatrixElement]: - Contains route information computed - for an origin/destination pair in the - ComputeRouteMatrix API. This proto can - be streamed to the client. - - """ - # 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, routes_service.ComputeRouteMatrixRequest): - request = routes_service.ComputeRouteMatrixRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.compute_route_matrix] - - # 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) -> "RoutesClient": - 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__) - - -__all__ = ( - "RoutesClient", -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/README.rst b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/README.rst deleted file mode 100644 index ece3f327f1db..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`RoutesTransport` is the ABC for all transports. -- public child `RoutesGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `RoutesGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseRoutesRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `RoutesRestTransport` 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-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py deleted file mode 100644 index cac74dd752a0..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 RoutesTransport -from .grpc import RoutesGrpcTransport -from .grpc_asyncio import RoutesGrpcAsyncIOTransport -from .rest import RoutesRestTransport -from .rest import RoutesRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[RoutesTransport]] -_transport_registry['grpc'] = RoutesGrpcTransport -_transport_registry['grpc_asyncio'] = RoutesGrpcAsyncIOTransport -_transport_registry['rest'] = RoutesRestTransport - -__all__ = ( - 'RoutesTransport', - 'RoutesGrpcTransport', - 'RoutesGrpcAsyncIOTransport', - 'RoutesRestTransport', - 'RoutesRestInterceptor', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py deleted file mode 100644 index ecdfa6e5fcc0..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py +++ /dev/null @@ -1,167 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.routing_v2 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 - -from google.maps.routing_v2.types import routes_service - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class RoutesTransport(abc.ABC): - """Abstract transport class for Routes.""" - - AUTH_SCOPES = ( - ) - - DEFAULT_HOST: str = 'routes.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: 'routes.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to 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.compute_routes: gapic_v1.method.wrap_method( - self.compute_routes, - default_timeout=None, - client_info=client_info, - ), - self.compute_route_matrix: gapic_v1.method.wrap_method( - self.compute_route_matrix, - 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 compute_routes(self) -> Callable[ - [routes_service.ComputeRoutesRequest], - Union[ - routes_service.ComputeRoutesResponse, - Awaitable[routes_service.ComputeRoutesResponse] - ]]: - raise NotImplementedError() - - @property - def compute_route_matrix(self) -> Callable[ - [routes_service.ComputeRouteMatrixRequest], - Union[ - routes_service.RouteMatrixElement, - Awaitable[routes_service.RouteMatrixElement] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'RoutesTransport', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py deleted file mode 100644 index 8b2b7b6398bd..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py +++ /dev/null @@ -1,446 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.routing_v2.types import routes_service -from .base import RoutesTransport, 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.maps.routing.v2.Routes", - "rpcName": 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.maps.routing.v2.Routes", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class RoutesGrpcTransport(RoutesTransport): - """gRPC backend transport for Routes. - - The Routes 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 = 'routes.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: 'routes.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to 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 = 'routes.googleapis.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 compute_routes(self) -> Callable[ - [routes_service.ComputeRoutesRequest], - routes_service.ComputeRoutesResponse]: - r"""Return a callable for the compute routes method over gRPC. - - Returns the primary route along with optional alternate routes, - given a set of terminal and intermediate waypoints. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using URL parameter ``$fields`` or ``fields``, or by using an - HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL - parameters and - headers `__). - The value is a comma separated list of field paths. See detailed - documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of Route-level duration, distance, and polyline - (an example production setup): - ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` - - Google discourage the use of the wildcard (``*``) response field - mask, or specifying the field mask at the top level - (``routes``), because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - Returns: - Callable[[~.ComputeRoutesRequest], - ~.ComputeRoutesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'compute_routes' not in self._stubs: - self._stubs['compute_routes'] = self._logged_channel.unary_unary( - '/google.maps.routing.v2.Routes/ComputeRoutes', - request_serializer=routes_service.ComputeRoutesRequest.serialize, - response_deserializer=routes_service.ComputeRoutesResponse.deserialize, - ) - return self._stubs['compute_routes'] - - @property - def compute_route_matrix(self) -> Callable[ - [routes_service.ComputeRouteMatrixRequest], - routes_service.RouteMatrixElement]: - r"""Return a callable for the compute route matrix method over gRPC. - - Takes in a list of origins and destinations and returns a stream - containing route information for each combination of origin and - destination. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using the URL parameter ``$fields`` or ``fields``, or by using - the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available - URL parameters and - headers `__). - The value is a comma separated list of field paths. See this - detailed documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of route durations, distances, element status, - condition, and element indices (an example production setup): - ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` - - It is critical that you include ``status`` in your field mask as - otherwise all messages will appear to be OK. Google discourages - the use of the wildcard (``*``) response field mask, because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - Returns: - Callable[[~.ComputeRouteMatrixRequest], - ~.RouteMatrixElement]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'compute_route_matrix' not in self._stubs: - self._stubs['compute_route_matrix'] = self._logged_channel.unary_stream( - '/google.maps.routing.v2.Routes/ComputeRouteMatrix', - request_serializer=routes_service.ComputeRouteMatrixRequest.serialize, - response_deserializer=routes_service.RouteMatrixElement.deserialize, - ) - return self._stubs['compute_route_matrix'] - - def close(self): - self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'RoutesGrpcTransport', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py deleted file mode 100644 index 6f00e3511763..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py +++ /dev/null @@ -1,471 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.routing_v2.types import routes_service -from .base import RoutesTransport, DEFAULT_CLIENT_INFO -from .grpc import RoutesGrpcTransport - -try: - from google.api_core import client_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.maps.routing.v2.Routes", - "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.maps.routing.v2.Routes", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class RoutesGrpcAsyncIOTransport(RoutesTransport): - """gRPC AsyncIO backend transport for Routes. - - The Routes 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 = 'routes.googleapis.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 = 'routes.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: 'routes.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to 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 compute_routes(self) -> Callable[ - [routes_service.ComputeRoutesRequest], - Awaitable[routes_service.ComputeRoutesResponse]]: - r"""Return a callable for the compute routes method over gRPC. - - Returns the primary route along with optional alternate routes, - given a set of terminal and intermediate waypoints. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using URL parameter ``$fields`` or ``fields``, or by using an - HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL - parameters and - headers `__). - The value is a comma separated list of field paths. See detailed - documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of Route-level duration, distance, and polyline - (an example production setup): - ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` - - Google discourage the use of the wildcard (``*``) response field - mask, or specifying the field mask at the top level - (``routes``), because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - Returns: - Callable[[~.ComputeRoutesRequest], - Awaitable[~.ComputeRoutesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'compute_routes' not in self._stubs: - self._stubs['compute_routes'] = self._logged_channel.unary_unary( - '/google.maps.routing.v2.Routes/ComputeRoutes', - request_serializer=routes_service.ComputeRoutesRequest.serialize, - response_deserializer=routes_service.ComputeRoutesResponse.deserialize, - ) - return self._stubs['compute_routes'] - - @property - def compute_route_matrix(self) -> Callable[ - [routes_service.ComputeRouteMatrixRequest], - Awaitable[routes_service.RouteMatrixElement]]: - r"""Return a callable for the compute route matrix method over gRPC. - - Takes in a list of origins and destinations and returns a stream - containing route information for each combination of origin and - destination. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using the URL parameter ``$fields`` or ``fields``, or by using - the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available - URL parameters and - headers `__). - The value is a comma separated list of field paths. See this - detailed documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of route durations, distances, element status, - condition, and element indices (an example production setup): - ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` - - It is critical that you include ``status`` in your field mask as - otherwise all messages will appear to be OK. Google discourages - the use of the wildcard (``*``) response field mask, because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - Returns: - Callable[[~.ComputeRouteMatrixRequest], - Awaitable[~.RouteMatrixElement]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'compute_route_matrix' not in self._stubs: - self._stubs['compute_route_matrix'] = self._logged_channel.unary_stream( - '/google.maps.routing.v2.Routes/ComputeRouteMatrix', - request_serializer=routes_service.ComputeRouteMatrixRequest.serialize, - response_deserializer=routes_service.RouteMatrixElement.deserialize, - ) - return self._stubs['compute_route_matrix'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.compute_routes: self._wrap_method( - self.compute_routes, - default_timeout=None, - client_info=client_info, - ), - self.compute_route_matrix: self._wrap_method( - self.compute_route_matrix, - 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__ = ( - 'RoutesGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py deleted file mode 100644 index 7de15a3c0755..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py +++ /dev/null @@ -1,465 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -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.maps.routing_v2.types import routes_service - - -from .rest_base import _BaseRoutesRestTransport -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}", -) - - -class RoutesRestInterceptor: - """Interceptor for Routes. - - 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 RoutesRestTransport. - - .. code-block:: python - class MyCustomRoutesInterceptor(RoutesRestInterceptor): - def pre_compute_route_matrix(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_compute_route_matrix(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_compute_routes(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_compute_routes(self, response): - logging.log(f"Received response: {response}") - return response - - transport = RoutesRestTransport(interceptor=MyCustomRoutesInterceptor()) - client = RoutesClient(transport=transport) - - - """ - def pre_compute_route_matrix(self, request: routes_service.ComputeRouteMatrixRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[routes_service.ComputeRouteMatrixRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for compute_route_matrix - - Override in a subclass to manipulate the request or metadata - before they are sent to the Routes server. - """ - return request, metadata - - def post_compute_route_matrix(self, response: rest_streaming.ResponseIterator) -> rest_streaming.ResponseIterator: - """Post-rpc interceptor for compute_route_matrix - - Override in a subclass to manipulate the response - after it is returned by the Routes server but before - it is returned to user code. - """ - return response - - def pre_compute_routes(self, request: routes_service.ComputeRoutesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[routes_service.ComputeRoutesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for compute_routes - - Override in a subclass to manipulate the request or metadata - before they are sent to the Routes server. - """ - return request, metadata - - def post_compute_routes(self, response: routes_service.ComputeRoutesResponse) -> routes_service.ComputeRoutesResponse: - """Post-rpc interceptor for compute_routes - - Override in a subclass to manipulate the response - after it is returned by the Routes server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class RoutesRestStub: - _session: AuthorizedSession - _host: str - _interceptor: RoutesRestInterceptor - - -class RoutesRestTransport(_BaseRoutesRestTransport): - """REST backend synchronous transport for Routes. - - The Routes 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 = 'routes.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[RoutesRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'routes.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to 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 RoutesRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _ComputeRouteMatrix(_BaseRoutesRestTransport._BaseComputeRouteMatrix, RoutesRestStub): - def __hash__(self): - return hash("RoutesRestTransport.ComputeRouteMatrix") - - @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, - stream=True, - ) - return response - - def __call__(self, - request: routes_service.ComputeRouteMatrixRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> rest_streaming.ResponseIterator: - r"""Call the compute route matrix method over HTTP. - - Args: - request (~.routes_service.ComputeRouteMatrixRequest): - The request object. ComputeRouteMatrix request message - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.routes_service.RouteMatrixElement: - Contains route information computed - for an origin/destination pair in the - ComputeRouteMatrix API. This proto can - be streamed to the client. - - """ - - http_options = _BaseRoutesRestTransport._BaseComputeRouteMatrix._get_http_options() - - request, metadata = self._interceptor.pre_compute_route_matrix(request, metadata) - transcoded_request = _BaseRoutesRestTransport._BaseComputeRouteMatrix._get_transcoded_request(http_options, request) - - body = _BaseRoutesRestTransport._BaseComputeRouteMatrix._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseRoutesRestTransport._BaseComputeRouteMatrix._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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.maps.routing_v2.RoutesClient.ComputeRouteMatrix", - extra = { - "serviceName": "google.maps.routing.v2.Routes", - "rpcName": "ComputeRouteMatrix", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = RoutesRestTransport._ComputeRouteMatrix._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 = rest_streaming.ResponseIterator(response, routes_service.RouteMatrixElement) - - resp = self._interceptor.post_compute_route_matrix(resp) - return resp - - class _ComputeRoutes(_BaseRoutesRestTransport._BaseComputeRoutes, RoutesRestStub): - def __hash__(self): - return hash("RoutesRestTransport.ComputeRoutes") - - @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: routes_service.ComputeRoutesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> routes_service.ComputeRoutesResponse: - r"""Call the compute routes method over HTTP. - - Args: - request (~.routes_service.ComputeRoutesRequest): - The request object. ComputeRoutes request message. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.routes_service.ComputeRoutesResponse: - ComputeRoutes the response message. - """ - - http_options = _BaseRoutesRestTransport._BaseComputeRoutes._get_http_options() - - request, metadata = self._interceptor.pre_compute_routes(request, metadata) - transcoded_request = _BaseRoutesRestTransport._BaseComputeRoutes._get_transcoded_request(http_options, request) - - body = _BaseRoutesRestTransport._BaseComputeRoutes._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseRoutesRestTransport._BaseComputeRoutes._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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.maps.routing_v2.RoutesClient.ComputeRoutes", - extra = { - "serviceName": "google.maps.routing.v2.Routes", - "rpcName": "ComputeRoutes", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = RoutesRestTransport._ComputeRoutes._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 = routes_service.ComputeRoutesResponse() - pb_resp = routes_service.ComputeRoutesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_compute_routes(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = routes_service.ComputeRoutesResponse.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.maps.routing_v2.RoutesClient.compute_routes", - extra = { - "serviceName": "google.maps.routing.v2.Routes", - "rpcName": "ComputeRoutes", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def compute_route_matrix(self) -> Callable[ - [routes_service.ComputeRouteMatrixRequest], - routes_service.RouteMatrixElement]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ComputeRouteMatrix(self._session, self._host, self._interceptor) # type: ignore - - @property - def compute_routes(self) -> Callable[ - [routes_service.ComputeRoutesRequest], - routes_service.ComputeRoutesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ComputeRoutes(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'RoutesRestTransport', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest_base.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest_base.py deleted file mode 100644 index 89bf86170eeb..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest_base.py +++ /dev/null @@ -1,185 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 RoutesTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.maps.routing_v2.types import routes_service - - -class _BaseRoutesRestTransport(RoutesTransport): - """Base REST backend transport for Routes. - - 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 = 'routes.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: 'routes.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 _BaseComputeRouteMatrix: - 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': '/distanceMatrix/v2:computeRouteMatrix', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = routes_service.ComputeRouteMatrixRequest.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(_BaseRoutesRestTransport._BaseComputeRouteMatrix._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseComputeRoutes: - 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': '/directions/v2:computeRoutes', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = routes_service.ComputeRoutesRequest.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(_BaseRoutesRestTransport._BaseComputeRoutes._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseRoutesRestTransport', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py deleted file mode 100644 index e383324c9fc2..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py +++ /dev/null @@ -1,154 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .fallback_info import ( - FallbackInfo, - FallbackReason, - FallbackRoutingMode, -) -from .geocoding_results import ( - GeocodedWaypoint, - GeocodingResults, -) -from .localized_time import ( - LocalizedTime, -) -from .location import ( - Location, -) -from .maneuver import ( - Maneuver, -) -from .navigation_instruction import ( - NavigationInstruction, -) -from .polyline import ( - Polyline, - PolylineEncoding, - PolylineQuality, -) -from .polyline_details import ( - PolylineDetails, -) -from .route import ( - Route, - RouteLeg, - RouteLegStep, - RouteLegStepTransitDetails, - RouteLegStepTravelAdvisory, - RouteLegTravelAdvisory, - RouteTravelAdvisory, -) -from .route_label import ( - RouteLabel, -) -from .route_modifiers import ( - RouteModifiers, -) -from .route_travel_mode import ( - RouteTravelMode, -) -from .routes_service import ( - ComputeRouteMatrixRequest, - ComputeRoutesRequest, - ComputeRoutesResponse, - RouteMatrixDestination, - RouteMatrixElement, - RouteMatrixOrigin, - RouteMatrixElementCondition, -) -from .routing_preference import ( - RoutingPreference, -) -from .speed_reading_interval import ( - SpeedReadingInterval, -) -from .toll_info import ( - TollInfo, -) -from .toll_passes import ( - TollPass, -) -from .traffic_model import ( - TrafficModel, -) -from .transit import ( - TransitAgency, - TransitLine, - TransitStop, - TransitVehicle, -) -from .transit_preferences import ( - TransitPreferences, -) -from .units import ( - Units, -) -from .vehicle_emission_type import ( - VehicleEmissionType, -) -from .vehicle_info import ( - VehicleInfo, -) -from .waypoint import ( - Waypoint, -) - -__all__ = ( - 'FallbackInfo', - 'FallbackReason', - 'FallbackRoutingMode', - 'GeocodedWaypoint', - 'GeocodingResults', - 'LocalizedTime', - 'Location', - 'Maneuver', - 'NavigationInstruction', - 'Polyline', - 'PolylineEncoding', - 'PolylineQuality', - 'PolylineDetails', - 'Route', - 'RouteLeg', - 'RouteLegStep', - 'RouteLegStepTransitDetails', - 'RouteLegStepTravelAdvisory', - 'RouteLegTravelAdvisory', - 'RouteTravelAdvisory', - 'RouteLabel', - 'RouteModifiers', - 'RouteTravelMode', - 'ComputeRouteMatrixRequest', - 'ComputeRoutesRequest', - 'ComputeRoutesResponse', - 'RouteMatrixDestination', - 'RouteMatrixElement', - 'RouteMatrixOrigin', - 'RouteMatrixElementCondition', - 'RoutingPreference', - 'SpeedReadingInterval', - 'TollInfo', - 'TollPass', - 'TrafficModel', - 'TransitAgency', - 'TransitLine', - 'TransitStop', - 'TransitVehicle', - 'TransitPreferences', - 'Units', - 'VehicleEmissionType', - 'VehicleInfo', - 'Waypoint', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py deleted file mode 100644 index e9c371f86902..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py +++ /dev/null @@ -1,105 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.routing.v2', - manifest={ - 'FallbackReason', - 'FallbackRoutingMode', - 'FallbackInfo', - }, -) - - -class FallbackReason(proto.Enum): - r"""Reasons for using fallback response. - - Values: - FALLBACK_REASON_UNSPECIFIED (0): - No fallback reason specified. - SERVER_ERROR (1): - A server error happened while calculating - routes with your preferred routing mode, but we - were able to return a result calculated by an - alternative mode. - LATENCY_EXCEEDED (2): - We were not able to finish the calculation - with your preferred routing mode on time, but we - were able to return a result calculated by an - alternative mode. - """ - FALLBACK_REASON_UNSPECIFIED = 0 - SERVER_ERROR = 1 - LATENCY_EXCEEDED = 2 - - -class FallbackRoutingMode(proto.Enum): - r"""Actual routing mode used for returned fallback response. - - Values: - FALLBACK_ROUTING_MODE_UNSPECIFIED (0): - Not used. - FALLBACK_TRAFFIC_UNAWARE (1): - Indicates the ``TRAFFIC_UNAWARE`` - [``RoutingPreference``][google.maps.routing.v2.RoutingPreference] - was used to compute the response. - FALLBACK_TRAFFIC_AWARE (2): - Indicates the ``TRAFFIC_AWARE`` - [``RoutingPreference``][google.maps.routing.v2.RoutingPreference] - was used to compute the response. - """ - FALLBACK_ROUTING_MODE_UNSPECIFIED = 0 - FALLBACK_TRAFFIC_UNAWARE = 1 - FALLBACK_TRAFFIC_AWARE = 2 - - -class FallbackInfo(proto.Message): - r"""Information related to how and why a fallback result was - used. If this field is set, then it means the server used a - different routing mode from your preferred mode as fallback. - - Attributes: - routing_mode (google.maps.routing_v2.types.FallbackRoutingMode): - Routing mode used for the response. If - fallback was triggered, the mode may be - different from routing preference set in the - original client request. - reason (google.maps.routing_v2.types.FallbackReason): - The reason why fallback response was used - instead of the original response. This field is - only populated when the fallback mode is - triggered and the fallback response is returned. - """ - - routing_mode: 'FallbackRoutingMode' = proto.Field( - proto.ENUM, - number=1, - enum='FallbackRoutingMode', - ) - reason: 'FallbackReason' = proto.Field( - proto.ENUM, - number=2, - enum='FallbackReason', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py deleted file mode 100644 index e7b5ac69343c..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py +++ /dev/null @@ -1,127 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'GeocodingResults', - 'GeocodedWaypoint', - }, -) - - -class GeocodingResults(proto.Message): - r"""Contains - [``GeocodedWaypoints``][google.maps.routing.v2.GeocodedWaypoint] for - origin, destination and intermediate waypoints. Only populated for - address waypoints. - - Attributes: - origin (google.maps.routing_v2.types.GeocodedWaypoint): - Origin geocoded waypoint. - destination (google.maps.routing_v2.types.GeocodedWaypoint): - Destination geocoded waypoint. - intermediates (MutableSequence[google.maps.routing_v2.types.GeocodedWaypoint]): - A list of intermediate geocoded waypoints - each containing an index field that corresponds - to the zero-based position of the waypoint in - the order they were specified in the request. - """ - - origin: 'GeocodedWaypoint' = proto.Field( - proto.MESSAGE, - number=1, - message='GeocodedWaypoint', - ) - destination: 'GeocodedWaypoint' = proto.Field( - proto.MESSAGE, - number=2, - message='GeocodedWaypoint', - ) - intermediates: MutableSequence['GeocodedWaypoint'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='GeocodedWaypoint', - ) - - -class GeocodedWaypoint(proto.Message): - r"""Details about the locations used as waypoints. Only populated - for address waypoints. Includes details about the geocoding - results for the purposes of determining what the address was - geocoded to. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - geocoder_status (google.rpc.status_pb2.Status): - Indicates the status code resulting from the - geocoding operation. - intermediate_waypoint_request_index (int): - The index of the corresponding intermediate - waypoint in the request. Only populated if the - corresponding waypoint is an intermediate - waypoint. - - This field is a member of `oneof`_ ``_intermediate_waypoint_request_index``. - type_ (MutableSequence[str]): - The type(s) of the result, in the form of zero or more type - tags. Supported types: `Address types and address component - types `__. - partial_match (bool): - Indicates that the geocoder did not return an - exact match for the original request, though it - was able to match part of the requested address. - You may wish to examine the original request for - misspellings and/or an incomplete address. - place_id (str): - The place ID for this result. - """ - - geocoder_status: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - intermediate_waypoint_request_index: int = proto.Field( - proto.INT32, - number=2, - optional=True, - ) - type_: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - partial_match: bool = proto.Field( - proto.BOOL, - number=4, - ) - place_id: str = proto.Field( - proto.STRING, - number=5, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/localized_time.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/localized_time.py deleted file mode 100644 index cd33d5012b85..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/localized_time.py +++ /dev/null @@ -1,58 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 localized_text_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'LocalizedTime', - }, -) - - -class LocalizedTime(proto.Message): - r"""Localized description of time. - - Attributes: - time (google.type.localized_text_pb2.LocalizedText): - The time specified as a string in a given - time zone. - time_zone (str): - Contains the time zone. The value is the name of the time - zone as defined in the `IANA Time Zone - Database `__, e.g. - "America/New_York". - """ - - time: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=1, - message=localized_text_pb2.LocalizedText, - ) - time_zone: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py deleted file mode 100644 index 895301cea20d..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py +++ /dev/null @@ -1,63 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 wrappers_pb2 # type: ignore -from google.type import latlng_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'Location', - }, -) - - -class Location(proto.Message): - r"""Encapsulates a location (a geographic point, and an optional - heading). - - Attributes: - lat_lng (google.type.latlng_pb2.LatLng): - The waypoint's geographic coordinates. - heading (google.protobuf.wrappers_pb2.Int32Value): - The compass heading associated with the direction of the - flow of traffic. This value specifies the side of the road - for pickup and drop-off. Heading values can be from 0 to - 360, where 0 specifies a heading of due North, 90 specifies - a heading of due East, and so on. You can use this field - only for ``DRIVE`` and ``TWO_WHEELER`` - [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode]. - """ - - lat_lng: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=1, - message=latlng_pb2.LatLng, - ) - heading: wrappers_pb2.Int32Value = proto.Field( - proto.MESSAGE, - number=2, - message=wrappers_pb2.Int32Value, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py deleted file mode 100644 index e8275813708a..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py +++ /dev/null @@ -1,103 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.routing.v2', - manifest={ - 'Maneuver', - }, -) - - -class Maneuver(proto.Enum): - r"""A set of values that specify the navigation action to take - for the current step (for example, turn left, merge, or - straight). - - Values: - MANEUVER_UNSPECIFIED (0): - Not used. - TURN_SLIGHT_LEFT (1): - Turn slightly to the left. - TURN_SHARP_LEFT (2): - Turn sharply to the left. - UTURN_LEFT (3): - Make a left u-turn. - TURN_LEFT (4): - Turn left. - TURN_SLIGHT_RIGHT (5): - Turn slightly to the right. - TURN_SHARP_RIGHT (6): - Turn sharply to the right. - UTURN_RIGHT (7): - Make a right u-turn. - TURN_RIGHT (8): - Turn right. - STRAIGHT (9): - Go straight. - RAMP_LEFT (10): - Take the left ramp. - RAMP_RIGHT (11): - Take the right ramp. - MERGE (12): - Merge into traffic. - FORK_LEFT (13): - Take the left fork. - FORK_RIGHT (14): - Take the right fork. - FERRY (15): - Take the ferry. - FERRY_TRAIN (16): - Take the train leading onto the ferry. - ROUNDABOUT_LEFT (17): - Turn left at the roundabout. - ROUNDABOUT_RIGHT (18): - Turn right at the roundabout. - DEPART (19): - Initial maneuver. - NAME_CHANGE (20): - Used to indicate a street name change. - """ - MANEUVER_UNSPECIFIED = 0 - TURN_SLIGHT_LEFT = 1 - TURN_SHARP_LEFT = 2 - UTURN_LEFT = 3 - TURN_LEFT = 4 - TURN_SLIGHT_RIGHT = 5 - TURN_SHARP_RIGHT = 6 - UTURN_RIGHT = 7 - TURN_RIGHT = 8 - STRAIGHT = 9 - RAMP_LEFT = 10 - RAMP_RIGHT = 11 - MERGE = 12 - FORK_LEFT = 13 - FORK_RIGHT = 14 - FERRY = 15 - FERRY_TRAIN = 16 - ROUNDABOUT_LEFT = 17 - ROUNDABOUT_RIGHT = 18 - DEPART = 19 - NAME_CHANGE = 20 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py deleted file mode 100644 index f9a930014166..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py +++ /dev/null @@ -1,58 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.routing_v2.types import maneuver as gmr_maneuver - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'NavigationInstruction', - }, -) - - -class NavigationInstruction(proto.Message): - r"""Encapsulates navigation instructions for a - [``RouteLegStep``][google.maps.routing.v2.RouteLegStep]. - - Attributes: - maneuver (google.maps.routing_v2.types.Maneuver): - Encapsulates the navigation instructions for - the current step (for example, turn left, merge, - or straight). This field determines which icon - to display. - instructions (str): - Instructions for navigating this step. - """ - - maneuver: gmr_maneuver.Maneuver = proto.Field( - proto.ENUM, - number=1, - enum=gmr_maneuver.Maneuver, - ) - instructions: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py deleted file mode 100644 index fe776cd21e8b..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py +++ /dev/null @@ -1,113 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'PolylineQuality', - 'PolylineEncoding', - 'Polyline', - }, -) - - -class PolylineQuality(proto.Enum): - r"""A set of values that specify the quality of the polyline. - - Values: - POLYLINE_QUALITY_UNSPECIFIED (0): - No polyline quality preference specified. Defaults to - ``OVERVIEW``. - HIGH_QUALITY (1): - Specifies a high-quality polyline - which is composed using - more points than ``OVERVIEW``, at the cost of increased - response size. Use this value when you need more precision. - OVERVIEW (2): - Specifies an overview polyline - which is composed using a - small number of points. Use this value when displaying an - overview of the route. Using this option has a lower request - latency compared to using the ``HIGH_QUALITY`` option. - """ - POLYLINE_QUALITY_UNSPECIFIED = 0 - HIGH_QUALITY = 1 - OVERVIEW = 2 - - -class PolylineEncoding(proto.Enum): - r"""Specifies the preferred type of polyline to be returned. - - Values: - POLYLINE_ENCODING_UNSPECIFIED (0): - No polyline type preference specified. Defaults to - ``ENCODED_POLYLINE``. - ENCODED_POLYLINE (1): - Specifies a polyline encoded using the `polyline encoding - algorithm `__. - GEO_JSON_LINESTRING (2): - Specifies a polyline using the `GeoJSON LineString - format `__ - """ - POLYLINE_ENCODING_UNSPECIFIED = 0 - ENCODED_POLYLINE = 1 - GEO_JSON_LINESTRING = 2 - - -class Polyline(proto.Message): - r"""Encapsulates an encoded polyline. - - 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: - encoded_polyline (str): - The string encoding of the polyline using the `polyline - encoding - algorithm `__ - - This field is a member of `oneof`_ ``polyline_type``. - geo_json_linestring (google.protobuf.struct_pb2.Struct): - Specifies a polyline using the `GeoJSON LineString - format `__. - - This field is a member of `oneof`_ ``polyline_type``. - """ - - encoded_polyline: str = proto.Field( - proto.STRING, - number=1, - oneof='polyline_type', - ) - geo_json_linestring: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=2, - oneof='polyline_type', - message=struct_pb2.Struct, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline_details.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline_details.py deleted file mode 100644 index 7d7db2480849..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline_details.py +++ /dev/null @@ -1,150 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.routing.v2', - manifest={ - 'PolylineDetails', - }, -) - - -class PolylineDetails(proto.Message): - r"""Details corresponding to a given index or contiguous segment of a - polyline. Given a polyline with points P_0, P_1, ... , P_N - (zero-based index), the ``PolylineDetails`` defines an interval and - associated metadata. - - Attributes: - flyover_info (MutableSequence[google.maps.routing_v2.types.PolylineDetails.FlyoverInfo]): - Flyover details along the polyline. - narrow_road_info (MutableSequence[google.maps.routing_v2.types.PolylineDetails.NarrowRoadInfo]): - Narrow road details along the polyline. - """ - class RoadFeatureState(proto.Enum): - r"""Encapsulates the states of road features along a stretch of - polyline. - - Values: - ROAD_FEATURE_STATE_UNSPECIFIED (0): - The road feature's state was not computed - (default value). - EXISTS (1): - The road feature exists. - DOES_NOT_EXIST (2): - The road feature does not exist. - """ - ROAD_FEATURE_STATE_UNSPECIFIED = 0 - EXISTS = 1 - DOES_NOT_EXIST = 2 - - class PolylinePointIndex(proto.Message): - r"""Encapsulates the start and end indexes for a polyline detail. For - instances where the data corresponds to a single point, - ``start_index`` and ``end_index`` will be equal. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - start_index (int): - The start index of this detail in the - polyline. - - This field is a member of `oneof`_ ``_start_index``. - end_index (int): - The end index of this detail in the polyline. - - This field is a member of `oneof`_ ``_end_index``. - """ - - start_index: int = proto.Field( - proto.INT32, - number=1, - optional=True, - ) - end_index: int = proto.Field( - proto.INT32, - number=2, - optional=True, - ) - - class FlyoverInfo(proto.Message): - r"""Encapsulates information about flyovers along the polyline. - - Attributes: - flyover_presence (google.maps.routing_v2.types.PolylineDetails.RoadFeatureState): - Output only. Denotes whether a flyover exists - for a given stretch of the polyline. - polyline_point_index (google.maps.routing_v2.types.PolylineDetails.PolylinePointIndex): - The location of flyover related information - along the polyline. - """ - - flyover_presence: 'PolylineDetails.RoadFeatureState' = proto.Field( - proto.ENUM, - number=1, - enum='PolylineDetails.RoadFeatureState', - ) - polyline_point_index: 'PolylineDetails.PolylinePointIndex' = proto.Field( - proto.MESSAGE, - number=2, - message='PolylineDetails.PolylinePointIndex', - ) - - class NarrowRoadInfo(proto.Message): - r"""Encapsulates information about narrow roads along the - polyline. - - Attributes: - narrow_road_presence (google.maps.routing_v2.types.PolylineDetails.RoadFeatureState): - Output only. Denotes whether a narrow road - exists for a given stretch of the polyline. - polyline_point_index (google.maps.routing_v2.types.PolylineDetails.PolylinePointIndex): - The location of narrow road related - information along the polyline. - """ - - narrow_road_presence: 'PolylineDetails.RoadFeatureState' = proto.Field( - proto.ENUM, - number=1, - enum='PolylineDetails.RoadFeatureState', - ) - polyline_point_index: 'PolylineDetails.PolylinePointIndex' = proto.Field( - proto.MESSAGE, - number=2, - message='PolylineDetails.PolylinePointIndex', - ) - - flyover_info: MutableSequence[FlyoverInfo] = proto.RepeatedField( - proto.MESSAGE, - number=12, - message=FlyoverInfo, - ) - narrow_road_info: MutableSequence[NarrowRoadInfo] = proto.RepeatedField( - proto.MESSAGE, - number=13, - message=NarrowRoadInfo, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py deleted file mode 100644 index facf38d5452e..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py +++ /dev/null @@ -1,799 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.geo.type.types import viewport as ggt_viewport -from google.maps.routing_v2.types import localized_time -from google.maps.routing_v2.types import location -from google.maps.routing_v2.types import navigation_instruction as gmr_navigation_instruction -from google.maps.routing_v2.types import polyline as gmr_polyline -from google.maps.routing_v2.types import polyline_details as gmr_polyline_details -from google.maps.routing_v2.types import route_label -from google.maps.routing_v2.types import route_travel_mode -from google.maps.routing_v2.types import speed_reading_interval -from google.maps.routing_v2.types import toll_info as gmr_toll_info -from google.maps.routing_v2.types import transit -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.type import localized_text_pb2 # type: ignore -from google.type import money_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'Route', - 'RouteTravelAdvisory', - 'RouteLegTravelAdvisory', - 'RouteLegStepTravelAdvisory', - 'RouteLeg', - 'RouteLegStep', - 'RouteLegStepTransitDetails', - }, -) - - -class Route(proto.Message): - r"""Contains a route, which consists of a series of connected - road segments that join beginning, ending, and intermediate - waypoints. - - Attributes: - route_labels (MutableSequence[google.maps.routing_v2.types.RouteLabel]): - Labels for the ``Route`` that are useful to identify - specific properties of the route to compare against others. - legs (MutableSequence[google.maps.routing_v2.types.RouteLeg]): - A collection of legs (path segments between waypoints) that - make up the route. Each leg corresponds to the trip between - two non-\ ``via`` - [``Waypoints``][google.maps.routing.v2.Waypoint]. For - example, a route with no intermediate waypoints has only one - leg. A route that includes one non-\ ``via`` intermediate - waypoint has two legs. A route that includes one ``via`` - intermediate waypoint has one leg. The order of the legs - matches the order of waypoints from ``origin`` to - ``intermediates`` to ``destination``. - distance_meters (int): - The travel distance of the route, in meters. - duration (google.protobuf.duration_pb2.Duration): - The length of time needed to navigate the route. If you set - the ``routing_preference`` to ``TRAFFIC_UNAWARE``, then this - value is the same as ``static_duration``. If you set the - ``routing_preference`` to either ``TRAFFIC_AWARE`` or - ``TRAFFIC_AWARE_OPTIMAL``, then this value is calculated - taking traffic conditions into account. - static_duration (google.protobuf.duration_pb2.Duration): - The duration of travel through the route - without taking traffic conditions into - consideration. - polyline (google.maps.routing_v2.types.Polyline): - The overall route polyline. This polyline is the combined - polyline of all ``legs``. - description (str): - A description of the route. - warnings (MutableSequence[str]): - An array of warnings to show when displaying - the route. - viewport (google.geo.type.types.Viewport): - The viewport bounding box of the polyline. - travel_advisory (google.maps.routing_v2.types.RouteTravelAdvisory): - Additional information about the route. - optimized_intermediate_waypoint_index (MutableSequence[int]): - If you set - [``optimize_waypoint_order``][google.maps.routing.v2.ComputeRoutesRequest.optimize_waypoint_order] - to true, this field contains the optimized ordering of - intermediate waypoints. Otherwise, this field is empty. For - example, if you give an input of Origin: LA; Intermediate - waypoints: Dallas, Bangor, Phoenix; Destination: New York; - and the optimized intermediate waypoint order is Phoenix, - Dallas, Bangor, then this field contains the values [2, 0, - 1]. The index starts with 0 for the first intermediate - waypoint provided in the input. - localized_values (google.maps.routing_v2.types.Route.RouteLocalizedValues): - Text representations of properties of the ``Route``. - route_token (str): - An opaque token that can be passed to `Navigation - SDK `__ - to reconstruct the route during navigation, and, in the - event of rerouting, honor the original intention when the - route was created. Treat this token as an opaque blob. Don't - compare its value across requests as its value may change - even if the service returns the exact same route. - - NOTE: ``Route.route_token`` is only available for requests - that have set ``ComputeRoutesRequest.routing_preference`` to - ``TRAFFIC_AWARE`` or ``TRAFFIC_AWARE_OPTIMAL``. - ``Route.route_token`` is not supported for requests that - have Via waypoints. - polyline_details (google.maps.routing_v2.types.PolylineDetails): - Contains information about details along the - polyline. - """ - - class RouteLocalizedValues(proto.Message): - r"""Text representations of certain properties. - - Attributes: - distance (google.type.localized_text_pb2.LocalizedText): - Travel distance represented in text form. - duration (google.type.localized_text_pb2.LocalizedText): - Duration, represented in text form and localized to the - region of the query. Takes traffic conditions into - consideration. Note: If you did not request traffic - information, this value is the same value as - ``static_duration``. - static_duration (google.type.localized_text_pb2.LocalizedText): - Duration without taking traffic conditions - into consideration, represented in text form. - transit_fare (google.type.localized_text_pb2.LocalizedText): - Transit fare represented in text form. - """ - - distance: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=1, - message=localized_text_pb2.LocalizedText, - ) - duration: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=2, - message=localized_text_pb2.LocalizedText, - ) - static_duration: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=3, - message=localized_text_pb2.LocalizedText, - ) - transit_fare: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=4, - message=localized_text_pb2.LocalizedText, - ) - - route_labels: MutableSequence[route_label.RouteLabel] = proto.RepeatedField( - proto.ENUM, - number=13, - enum=route_label.RouteLabel, - ) - legs: MutableSequence['RouteLeg'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='RouteLeg', - ) - distance_meters: int = proto.Field( - proto.INT32, - number=2, - ) - duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=3, - message=duration_pb2.Duration, - ) - static_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=4, - message=duration_pb2.Duration, - ) - polyline: gmr_polyline.Polyline = proto.Field( - proto.MESSAGE, - number=5, - message=gmr_polyline.Polyline, - ) - description: str = proto.Field( - proto.STRING, - number=6, - ) - warnings: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=7, - ) - viewport: ggt_viewport.Viewport = proto.Field( - proto.MESSAGE, - number=8, - message=ggt_viewport.Viewport, - ) - travel_advisory: 'RouteTravelAdvisory' = proto.Field( - proto.MESSAGE, - number=9, - message='RouteTravelAdvisory', - ) - optimized_intermediate_waypoint_index: MutableSequence[int] = proto.RepeatedField( - proto.INT32, - number=10, - ) - localized_values: RouteLocalizedValues = proto.Field( - proto.MESSAGE, - number=11, - message=RouteLocalizedValues, - ) - route_token: str = proto.Field( - proto.STRING, - number=12, - ) - polyline_details: gmr_polyline_details.PolylineDetails = proto.Field( - proto.MESSAGE, - number=14, - message=gmr_polyline_details.PolylineDetails, - ) - - -class RouteTravelAdvisory(proto.Message): - r"""Contains the additional information that the user should be - informed about, such as possible traffic zone restrictions. - - Attributes: - toll_info (google.maps.routing_v2.types.TollInfo): - Contains information about tolls on the route. This field is - only populated if tolls are expected on the route. If this - field is set, but the ``estimatedPrice`` subfield is not - populated, then the route contains tolls, but the estimated - price is unknown. If this field is not set, then there are - no tolls expected on the route. - speed_reading_intervals (MutableSequence[google.maps.routing_v2.types.SpeedReadingInterval]): - Speed reading intervals detailing traffic density. - Applicable in case of ``TRAFFIC_AWARE`` and - ``TRAFFIC_AWARE_OPTIMAL`` routing preferences. The intervals - cover the entire polyline of the route without overlap. The - start point of a specified interval is the same as the end - point of the preceding interval. - - Example: - - :: - - polyline: A ---- B ---- C ---- D ---- E ---- F ---- G - speed_reading_intervals: [A,C), [C,D), [D,G). - fuel_consumption_microliters (int): - The predicted fuel consumption in - microliters. - route_restrictions_partially_ignored (bool): - Returned route may have restrictions that are - not suitable for requested travel mode or route - modifiers. - transit_fare (google.type.money_pb2.Money): - If present, contains the total fare or ticket costs on this - route This property is only returned for ``TRANSIT`` - requests and only for routes where fare information is - available for all transit steps. - """ - - toll_info: gmr_toll_info.TollInfo = proto.Field( - proto.MESSAGE, - number=2, - message=gmr_toll_info.TollInfo, - ) - speed_reading_intervals: MutableSequence[speed_reading_interval.SpeedReadingInterval] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=speed_reading_interval.SpeedReadingInterval, - ) - fuel_consumption_microliters: int = proto.Field( - proto.INT64, - number=5, - ) - route_restrictions_partially_ignored: bool = proto.Field( - proto.BOOL, - number=6, - ) - transit_fare: money_pb2.Money = proto.Field( - proto.MESSAGE, - number=7, - message=money_pb2.Money, - ) - - -class RouteLegTravelAdvisory(proto.Message): - r"""Contains the additional information that the user should be - informed about on a leg step, such as possible traffic zone - restrictions. - - Attributes: - toll_info (google.maps.routing_v2.types.TollInfo): - Contains information about tolls on the specific - ``RouteLeg``. This field is only populated if we expect - there are tolls on the ``RouteLeg``. If this field is set - but the estimated_price subfield is not populated, we expect - that road contains tolls but we do not know an estimated - price. If this field does not exist, then there is no toll - on the ``RouteLeg``. - speed_reading_intervals (MutableSequence[google.maps.routing_v2.types.SpeedReadingInterval]): - Speed reading intervals detailing traffic density. - Applicable in case of ``TRAFFIC_AWARE`` and - ``TRAFFIC_AWARE_OPTIMAL`` routing preferences. The intervals - cover the entire polyline of the ``RouteLeg`` without - overlap. The start point of a specified interval is the same - as the end point of the preceding interval. - - Example: - - :: - - polyline: A ---- B ---- C ---- D ---- E ---- F ---- G - speed_reading_intervals: [A,C), [C,D), [D,G). - """ - - toll_info: gmr_toll_info.TollInfo = proto.Field( - proto.MESSAGE, - number=1, - message=gmr_toll_info.TollInfo, - ) - speed_reading_intervals: MutableSequence[speed_reading_interval.SpeedReadingInterval] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=speed_reading_interval.SpeedReadingInterval, - ) - - -class RouteLegStepTravelAdvisory(proto.Message): - r"""Contains the additional information that the user should be - informed about, such as possible traffic zone restrictions on a - leg step. - - Attributes: - speed_reading_intervals (MutableSequence[google.maps.routing_v2.types.SpeedReadingInterval]): - NOTE: This field is not currently populated. - """ - - speed_reading_intervals: MutableSequence[speed_reading_interval.SpeedReadingInterval] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=speed_reading_interval.SpeedReadingInterval, - ) - - -class RouteLeg(proto.Message): - r"""Contains a segment between non-\ ``via`` waypoints. - - Attributes: - distance_meters (int): - The travel distance of the route leg, in - meters. - duration (google.protobuf.duration_pb2.Duration): - The length of time needed to navigate the leg. If the - ``route_preference`` is set to ``TRAFFIC_UNAWARE``, then - this value is the same as ``static_duration``. If the - ``route_preference`` is either ``TRAFFIC_AWARE`` or - ``TRAFFIC_AWARE_OPTIMAL``, then this value is calculated - taking traffic conditions into account. - static_duration (google.protobuf.duration_pb2.Duration): - The duration of travel through the leg, - calculated without taking traffic conditions - into consideration. - polyline (google.maps.routing_v2.types.Polyline): - The overall polyline for this leg that includes each - ``step``'s polyline. - start_location (google.maps.routing_v2.types.Location): - The start location of this leg. This location might be - different from the provided ``origin``. For example, when - the provided ``origin`` is not near a road, this is a point - on the road. - end_location (google.maps.routing_v2.types.Location): - The end location of this leg. This location might be - different from the provided ``destination``. For example, - when the provided ``destination`` is not near a road, this - is a point on the road. - steps (MutableSequence[google.maps.routing_v2.types.RouteLegStep]): - An array of steps denoting segments within - this leg. Each step represents one navigation - instruction. - travel_advisory (google.maps.routing_v2.types.RouteLegTravelAdvisory): - Contains the additional information that the - user should be informed about, such as possible - traffic zone restrictions, on a route leg. - localized_values (google.maps.routing_v2.types.RouteLeg.RouteLegLocalizedValues): - Text representations of properties of the ``RouteLeg``. - steps_overview (google.maps.routing_v2.types.RouteLeg.StepsOverview): - Overview information about the steps in this ``RouteLeg``. - This field is only populated for TRANSIT routes. - """ - - class RouteLegLocalizedValues(proto.Message): - r"""Text representations of certain properties. - - Attributes: - distance (google.type.localized_text_pb2.LocalizedText): - Travel distance represented in text form. - duration (google.type.localized_text_pb2.LocalizedText): - Duration, represented in text form and localized to the - region of the query. Takes traffic conditions into - consideration. Note: If you did not request traffic - information, this value is the same value as - static_duration. - static_duration (google.type.localized_text_pb2.LocalizedText): - Duration without taking traffic conditions - into consideration, represented in text form. - """ - - distance: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=1, - message=localized_text_pb2.LocalizedText, - ) - duration: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=2, - message=localized_text_pb2.LocalizedText, - ) - static_duration: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=3, - message=localized_text_pb2.LocalizedText, - ) - - class StepsOverview(proto.Message): - r"""Provides overview information about a list of ``RouteLegStep``\ s. - - Attributes: - multi_modal_segments (MutableSequence[google.maps.routing_v2.types.RouteLeg.StepsOverview.MultiModalSegment]): - Summarized information about different multi-modal segments - of the ``RouteLeg.steps``. This field is not populated if - the ``RouteLeg`` does not contain any multi-modal segments - in the steps. - """ - - class MultiModalSegment(proto.Message): - r"""Provides summarized information about different multi-modal segments - of the ``RouteLeg.steps``. A multi-modal segment is defined as one - or more contiguous ``RouteLegStep`` that have the same - ``RouteTravelMode``. This field is not populated if the ``RouteLeg`` - does not contain any multi-modal segments in the steps. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - step_start_index (int): - The corresponding ``RouteLegStep`` index that is the start - of a multi-modal segment. - - This field is a member of `oneof`_ ``_step_start_index``. - step_end_index (int): - The corresponding ``RouteLegStep`` index that is the end of - a multi-modal segment. - - This field is a member of `oneof`_ ``_step_end_index``. - navigation_instruction (google.maps.routing_v2.types.NavigationInstruction): - NavigationInstruction for the multi-modal - segment. - travel_mode (google.maps.routing_v2.types.RouteTravelMode): - The travel mode of the multi-modal segment. - """ - - step_start_index: int = proto.Field( - proto.INT32, - number=1, - optional=True, - ) - step_end_index: int = proto.Field( - proto.INT32, - number=2, - optional=True, - ) - navigation_instruction: gmr_navigation_instruction.NavigationInstruction = proto.Field( - proto.MESSAGE, - number=3, - message=gmr_navigation_instruction.NavigationInstruction, - ) - travel_mode: route_travel_mode.RouteTravelMode = proto.Field( - proto.ENUM, - number=4, - enum=route_travel_mode.RouteTravelMode, - ) - - multi_modal_segments: MutableSequence['RouteLeg.StepsOverview.MultiModalSegment'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='RouteLeg.StepsOverview.MultiModalSegment', - ) - - distance_meters: int = proto.Field( - proto.INT32, - number=1, - ) - duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - static_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=3, - message=duration_pb2.Duration, - ) - polyline: gmr_polyline.Polyline = proto.Field( - proto.MESSAGE, - number=4, - message=gmr_polyline.Polyline, - ) - start_location: location.Location = proto.Field( - proto.MESSAGE, - number=5, - message=location.Location, - ) - end_location: location.Location = proto.Field( - proto.MESSAGE, - number=6, - message=location.Location, - ) - steps: MutableSequence['RouteLegStep'] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message='RouteLegStep', - ) - travel_advisory: 'RouteLegTravelAdvisory' = proto.Field( - proto.MESSAGE, - number=8, - message='RouteLegTravelAdvisory', - ) - localized_values: RouteLegLocalizedValues = proto.Field( - proto.MESSAGE, - number=9, - message=RouteLegLocalizedValues, - ) - steps_overview: StepsOverview = proto.Field( - proto.MESSAGE, - number=10, - message=StepsOverview, - ) - - -class RouteLegStep(proto.Message): - r"""Contains a segment of a - [``RouteLeg``][google.maps.routing.v2.RouteLeg]. A step corresponds - to a single navigation instruction. Route legs are made up of steps. - - Attributes: - distance_meters (int): - The travel distance of this step, in meters. - In some circumstances, this field might not have - a value. - static_duration (google.protobuf.duration_pb2.Duration): - The duration of travel through this step - without taking traffic conditions into - consideration. In some circumstances, this field - might not have a value. - polyline (google.maps.routing_v2.types.Polyline): - The polyline associated with this step. - start_location (google.maps.routing_v2.types.Location): - The start location of this step. - end_location (google.maps.routing_v2.types.Location): - The end location of this step. - navigation_instruction (google.maps.routing_v2.types.NavigationInstruction): - Navigation instructions. - travel_advisory (google.maps.routing_v2.types.RouteLegStepTravelAdvisory): - Contains the additional information that the - user should be informed about, such as possible - traffic zone restrictions, on a leg step. - localized_values (google.maps.routing_v2.types.RouteLegStep.RouteLegStepLocalizedValues): - Text representations of properties of the ``RouteLegStep``. - transit_details (google.maps.routing_v2.types.RouteLegStepTransitDetails): - Details pertaining to this step if the travel mode is - ``TRANSIT``. - travel_mode (google.maps.routing_v2.types.RouteTravelMode): - The travel mode used for this step. - """ - - class RouteLegStepLocalizedValues(proto.Message): - r"""Text representations of certain properties. - - Attributes: - distance (google.type.localized_text_pb2.LocalizedText): - Travel distance represented in text form. - static_duration (google.type.localized_text_pb2.LocalizedText): - Duration without taking traffic conditions - into consideration, represented in text form. - """ - - distance: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=1, - message=localized_text_pb2.LocalizedText, - ) - static_duration: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=3, - message=localized_text_pb2.LocalizedText, - ) - - distance_meters: int = proto.Field( - proto.INT32, - number=1, - ) - static_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - polyline: gmr_polyline.Polyline = proto.Field( - proto.MESSAGE, - number=3, - message=gmr_polyline.Polyline, - ) - start_location: location.Location = proto.Field( - proto.MESSAGE, - number=4, - message=location.Location, - ) - end_location: location.Location = proto.Field( - proto.MESSAGE, - number=5, - message=location.Location, - ) - navigation_instruction: gmr_navigation_instruction.NavigationInstruction = proto.Field( - proto.MESSAGE, - number=6, - message=gmr_navigation_instruction.NavigationInstruction, - ) - travel_advisory: 'RouteLegStepTravelAdvisory' = proto.Field( - proto.MESSAGE, - number=7, - message='RouteLegStepTravelAdvisory', - ) - localized_values: RouteLegStepLocalizedValues = proto.Field( - proto.MESSAGE, - number=8, - message=RouteLegStepLocalizedValues, - ) - transit_details: 'RouteLegStepTransitDetails' = proto.Field( - proto.MESSAGE, - number=9, - message='RouteLegStepTransitDetails', - ) - travel_mode: route_travel_mode.RouteTravelMode = proto.Field( - proto.ENUM, - number=10, - enum=route_travel_mode.RouteTravelMode, - ) - - -class RouteLegStepTransitDetails(proto.Message): - r"""Additional information for the ``RouteLegStep`` related to - ``TRANSIT`` routes. - - Attributes: - stop_details (google.maps.routing_v2.types.RouteLegStepTransitDetails.TransitStopDetails): - Information about the arrival and departure - stops for the step. - localized_values (google.maps.routing_v2.types.RouteLegStepTransitDetails.TransitDetailsLocalizedValues): - Text representations of properties of the - ``RouteLegStepTransitDetails``. - headsign (str): - Specifies the direction in which to travel on - this line as marked on the vehicle or at the - departure stop. The direction is often the - terminus station. - headway (google.protobuf.duration_pb2.Duration): - Specifies the expected time as a duration - between departures from the same stop at this - time. For example, with a headway seconds value - of 600, you would expect a ten minute wait if - you should miss your bus. - transit_line (google.maps.routing_v2.types.TransitLine): - Information about the transit line used in - this step. - stop_count (int): - The number of stops from the departure to the arrival stop. - This count includes the arrival stop, but excludes the - departure stop. For example, if your route leaves from Stop - A, passes through stops B and C, and arrives at stop D, - stop_count returns 3. - trip_short_text (str): - The text that appears in schedules and sign boards to - identify a transit trip to passengers. The text should - uniquely identify a trip within a service day. For example, - "538" is the ``trip_short_text`` of the Amtrak train that - leaves San Jose, CA at 15:10 on weekdays to Sacramento, CA. - """ - - class TransitStopDetails(proto.Message): - r"""Details about the transit stops for the ``RouteLegStep``. - - Attributes: - arrival_stop (google.maps.routing_v2.types.TransitStop): - Information about the arrival stop for the - step. - arrival_time (google.protobuf.timestamp_pb2.Timestamp): - The estimated time of arrival for the step. - departure_stop (google.maps.routing_v2.types.TransitStop): - Information about the departure stop for the - step. - departure_time (google.protobuf.timestamp_pb2.Timestamp): - The estimated time of departure for the step. - """ - - arrival_stop: transit.TransitStop = proto.Field( - proto.MESSAGE, - number=1, - message=transit.TransitStop, - ) - arrival_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - departure_stop: transit.TransitStop = proto.Field( - proto.MESSAGE, - number=3, - message=transit.TransitStop, - ) - departure_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - - class TransitDetailsLocalizedValues(proto.Message): - r"""Localized descriptions of values for ``RouteTransitDetails``. - - Attributes: - arrival_time (google.maps.routing_v2.types.LocalizedTime): - Time in its formatted text representation - with a corresponding time zone. - departure_time (google.maps.routing_v2.types.LocalizedTime): - Time in its formatted text representation - with a corresponding time zone. - """ - - arrival_time: localized_time.LocalizedTime = proto.Field( - proto.MESSAGE, - number=1, - message=localized_time.LocalizedTime, - ) - departure_time: localized_time.LocalizedTime = proto.Field( - proto.MESSAGE, - number=2, - message=localized_time.LocalizedTime, - ) - - stop_details: TransitStopDetails = proto.Field( - proto.MESSAGE, - number=1, - message=TransitStopDetails, - ) - localized_values: TransitDetailsLocalizedValues = proto.Field( - proto.MESSAGE, - number=2, - message=TransitDetailsLocalizedValues, - ) - headsign: str = proto.Field( - proto.STRING, - number=3, - ) - headway: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=4, - message=duration_pb2.Duration, - ) - transit_line: transit.TransitLine = proto.Field( - proto.MESSAGE, - number=5, - message=transit.TransitLine, - ) - stop_count: int = proto.Field( - proto.INT32, - number=6, - ) - trip_short_text: str = proto.Field( - proto.STRING, - number=7, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py deleted file mode 100644 index 57aa11e9666e..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.routing.v2', - manifest={ - 'RouteLabel', - }, -) - - -class RouteLabel(proto.Enum): - r"""Labels for the [``Route``][google.maps.routing.v2.Route] that are - useful to identify specific properties of the route to compare - against others. - - Values: - ROUTE_LABEL_UNSPECIFIED (0): - Default - not used. - DEFAULT_ROUTE (1): - The default "best" route returned for the - route computation. - DEFAULT_ROUTE_ALTERNATE (2): - An alternative to the default "best" route. Routes like this - will be returned when - [``compute_alternative_routes``][google.maps.routing.v2.ComputeRoutesRequest.compute_alternative_routes] - is specified. - FUEL_EFFICIENT (3): - Fuel efficient route. Routes labeled with - this value are determined to be optimized for - Eco parameters such as fuel consumption. - SHORTER_DISTANCE (4): - Shorter travel distance route. This is an - experimental feature. - """ - ROUTE_LABEL_UNSPECIFIED = 0 - DEFAULT_ROUTE = 1 - DEFAULT_ROUTE_ALTERNATE = 2 - FUEL_EFFICIENT = 3 - SHORTER_DISTANCE = 4 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py deleted file mode 100644 index a8a386928907..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py +++ /dev/null @@ -1,98 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.routing_v2.types import toll_passes as gmr_toll_passes -from google.maps.routing_v2.types import vehicle_info as gmr_vehicle_info - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'RouteModifiers', - }, -) - - -class RouteModifiers(proto.Message): - r"""Encapsulates a set of optional conditions to satisfy when - calculating the routes. - - Attributes: - avoid_tolls (bool): - When set to true, avoids toll roads where reasonable, giving - preference to routes not containing toll roads. Applies only - to the ``DRIVE`` and ``TWO_WHEELER`` - [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode]. - avoid_highways (bool): - When set to true, avoids highways where reasonable, giving - preference to routes not containing highways. Applies only - to the ``DRIVE`` and ``TWO_WHEELER`` - [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode]. - avoid_ferries (bool): - When set to true, avoids ferries where reasonable, giving - preference to routes not containing ferries. Applies only to - the ``DRIVE`` and\ ``TWO_WHEELER`` - [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode]. - avoid_indoor (bool): - When set to true, avoids navigating indoors where - reasonable, giving preference to routes not containing - indoor navigation. Applies only to the ``WALK`` - [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode]. - vehicle_info (google.maps.routing_v2.types.VehicleInfo): - Specifies the vehicle information. - toll_passes (MutableSequence[google.maps.routing_v2.types.TollPass]): - Encapsulates information about toll passes. If toll passes - are provided, the API tries to return the pass price. If - toll passes are not provided, the API treats the toll pass - as unknown and tries to return the cash price. Applies only - to the ``DRIVE`` and ``TWO_WHEELER`` - [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode]. - """ - - avoid_tolls: bool = proto.Field( - proto.BOOL, - number=1, - ) - avoid_highways: bool = proto.Field( - proto.BOOL, - number=2, - ) - avoid_ferries: bool = proto.Field( - proto.BOOL, - number=3, - ) - avoid_indoor: bool = proto.Field( - proto.BOOL, - number=4, - ) - vehicle_info: gmr_vehicle_info.VehicleInfo = proto.Field( - proto.MESSAGE, - number=5, - message=gmr_vehicle_info.VehicleInfo, - ) - toll_passes: MutableSequence[gmr_toll_passes.TollPass] = proto.RepeatedField( - proto.ENUM, - number=6, - enum=gmr_toll_passes.TollPass, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py deleted file mode 100644 index 674af4e560a3..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py +++ /dev/null @@ -1,63 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.routing.v2', - manifest={ - 'RouteTravelMode', - }, -) - - -class RouteTravelMode(proto.Enum): - r"""A set of values used to specify the mode of travel. NOTE: ``WALK``, - ``BICYCLE``, and ``TWO_WHEELER`` routes are in beta and might - sometimes be missing clear sidewalks, pedestrian paths, or bicycling - paths. You must display this warning to the user for all walking, - bicycling, and two-wheel routes that you display in your app. - - Values: - TRAVEL_MODE_UNSPECIFIED (0): - No travel mode specified. Defaults to ``DRIVE``. - DRIVE (1): - Travel by passenger car. - BICYCLE (2): - Travel by bicycle. - WALK (3): - Travel by walking. - TWO_WHEELER (4): - Two-wheeled, motorized vehicle. For example, motorcycle. - Note that this differs from the ``BICYCLE`` travel mode - which covers human-powered mode. - TRANSIT (7): - Travel by public transit routes, where - available. - """ - TRAVEL_MODE_UNSPECIFIED = 0 - DRIVE = 1 - BICYCLE = 2 - WALK = 3 - TWO_WHEELER = 4 - TRANSIT = 7 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py deleted file mode 100644 index 1f560384693a..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py +++ /dev/null @@ -1,748 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.routing_v2.types import fallback_info as gmr_fallback_info -from google.maps.routing_v2.types import geocoding_results as gmr_geocoding_results -from google.maps.routing_v2.types import polyline -from google.maps.routing_v2.types import route -from google.maps.routing_v2.types import route_modifiers as gmr_route_modifiers -from google.maps.routing_v2.types import route_travel_mode -from google.maps.routing_v2.types import routing_preference as gmr_routing_preference -from google.maps.routing_v2.types import traffic_model as gmr_traffic_model -from google.maps.routing_v2.types import transit_preferences as gmr_transit_preferences -from google.maps.routing_v2.types import units as gmr_units -from google.maps.routing_v2.types import waypoint as gmr_waypoint -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from google.type import localized_text_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'RouteMatrixElementCondition', - 'ComputeRoutesRequest', - 'ComputeRoutesResponse', - 'ComputeRouteMatrixRequest', - 'RouteMatrixOrigin', - 'RouteMatrixDestination', - 'RouteMatrixElement', - }, -) - - -class RouteMatrixElementCondition(proto.Enum): - r"""The condition of the route being returned. - - Values: - ROUTE_MATRIX_ELEMENT_CONDITION_UNSPECIFIED (0): - Only used when the ``status`` of the element is not OK. - ROUTE_EXISTS (1): - A route was found, and the corresponding - information was filled out for the element. - ROUTE_NOT_FOUND (2): - No route could be found. Fields containing route - information, such as ``distance_meters`` or ``duration``, - will not be filled out in the element. - """ - ROUTE_MATRIX_ELEMENT_CONDITION_UNSPECIFIED = 0 - ROUTE_EXISTS = 1 - ROUTE_NOT_FOUND = 2 - - -class ComputeRoutesRequest(proto.Message): - r"""ComputeRoutes request message. - - Attributes: - origin (google.maps.routing_v2.types.Waypoint): - Required. Origin waypoint. - destination (google.maps.routing_v2.types.Waypoint): - Required. Destination waypoint. - intermediates (MutableSequence[google.maps.routing_v2.types.Waypoint]): - Optional. A set of waypoints along the route - (excluding terminal points), for either stopping - at or passing by. Up to 25 intermediate - waypoints are supported. - travel_mode (google.maps.routing_v2.types.RouteTravelMode): - Optional. Specifies the mode of - transportation. - routing_preference (google.maps.routing_v2.types.RoutingPreference): - Optional. Specifies how to compute the route. The server - attempts to use the selected routing preference to compute - the route. If the routing preference results in an error or - an extra long latency, then an error is returned. You can - specify this option only when the ``travel_mode`` is - ``DRIVE`` or ``TWO_WHEELER``, otherwise the request fails. - polyline_quality (google.maps.routing_v2.types.PolylineQuality): - Optional. Specifies your preference for the - quality of the polyline. - polyline_encoding (google.maps.routing_v2.types.PolylineEncoding): - Optional. Specifies the preferred encoding - for the polyline. - departure_time (google.protobuf.timestamp_pb2.Timestamp): - Optional. The departure time. If you don't set this value, - then this value defaults to the time that you made the - request. NOTE: You can only specify a ``departure_time`` in - the past when - [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode] - is set to ``TRANSIT``. Transit trips are available for up to - 7 days in the past or 100 days in the future. - arrival_time (google.protobuf.timestamp_pb2.Timestamp): - Optional. The arrival time. NOTE: Can only be set when - [RouteTravelMode][google.maps.routing.v2.RouteTravelMode] is - set to ``TRANSIT``. You can specify either - ``departure_time`` or ``arrival_time``, but not both. - Transit trips are available for up to 7 days in the past or - 100 days in the future. - compute_alternative_routes (bool): - Optional. Specifies whether to calculate - alternate routes in addition to the route. No - alternative routes are returned for requests - that have intermediate waypoints. - route_modifiers (google.maps.routing_v2.types.RouteModifiers): - Optional. A set of conditions to satisfy that - affect the way routes are calculated. - language_code (str): - Optional. The BCP-47 language code, such as "en-US" or - "sr-Latn". For more information, see `Unicode Locale - Identifier `__. - See `Language - Support `__ - for the list of supported languages. When you don't provide - this value, the display language is inferred from the - location of the route request. - region_code (str): - Optional. The region code, specified as a ccTLD ("top-level - domain") two-character value. For more information see - `Country code top-level - domains `__. - units (google.maps.routing_v2.types.Units): - Optional. Specifies the units of measure for the display - fields. These fields include the ``instruction`` field in - [``NavigationInstruction``][google.maps.routing.v2.NavigationInstruction]. - The units of measure used for the route, leg, step distance, - and duration are not affected by this value. If you don't - provide this value, then the display units are inferred from - the location of the first origin. - optimize_waypoint_order (bool): - Optional. If set to true, the service attempts to minimize - the overall cost of the route by re-ordering the specified - intermediate waypoints. The request fails if any of the - intermediate waypoints is a ``via`` waypoint. Use - ``ComputeRoutesResponse.Routes.optimized_intermediate_waypoint_index`` - to find the new ordering. If - ``ComputeRoutesResponseroutes.optimized_intermediate_waypoint_index`` - is not requested in the ``X-Goog-FieldMask`` header, the - request fails. If ``optimize_waypoint_order`` is set to - false, - ``ComputeRoutesResponse.optimized_intermediate_waypoint_index`` - will be empty. - requested_reference_routes (MutableSequence[google.maps.routing_v2.types.ComputeRoutesRequest.ReferenceRoute]): - Optional. Specifies what reference routes to calculate as - part of the request in addition to the default route. A - reference route is a route with a different route - calculation objective than the default route. For example a - ``FUEL_EFFICIENT`` reference route calculation takes into - account various parameters that would generate an optimal - fuel efficient route. When using this feature, look for - [``route_labels``][google.maps.routing.v2.Route.route_labels] - on the resulting routes. - extra_computations (MutableSequence[google.maps.routing_v2.types.ComputeRoutesRequest.ExtraComputation]): - Optional. A list of extra computations which - may be used to complete the request. Note: These - extra computations may return extra fields on - the response. These extra fields must also be - specified in the field mask to be returned in - the response. - traffic_model (google.maps.routing_v2.types.TrafficModel): - Optional. Specifies the assumptions to use when calculating - time in traffic. This setting affects the value returned in - the duration field in the - [``Route``][google.maps.routing.v2.Route] and - [``RouteLeg``][google.maps.routing.v2.RouteLeg] which - contains the predicted time in traffic based on historical - averages. ``TrafficModel`` is only available for requests - that have set - [``RoutingPreference``][google.maps.routing.v2.RoutingPreference] - to ``TRAFFIC_AWARE_OPTIMAL`` and - [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode] - to ``DRIVE``. Defaults to ``BEST_GUESS`` if traffic is - requested and ``TrafficModel`` is not specified. - transit_preferences (google.maps.routing_v2.types.TransitPreferences): - Optional. Specifies preferences that influence the route - returned for ``TRANSIT`` routes. NOTE: You can only specify - a ``transit_preferences`` when - [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode] - is set to ``TRANSIT``. - """ - class ReferenceRoute(proto.Enum): - r"""A supported reference route on the ComputeRoutesRequest. - - Values: - REFERENCE_ROUTE_UNSPECIFIED (0): - Not used. Requests containing this value - fail. - FUEL_EFFICIENT (1): - Fuel efficient route. - SHORTER_DISTANCE (2): - Route with shorter travel distance. This is an experimental - feature. - - For ``DRIVE`` requests, this feature prioritizes shorter - distance over driving comfort. For example, it may prefer - local roads instead of highways, take dirt roads, cut - through parking lots, etc. This feature does not return any - maneuvers that Google Maps knows to be illegal. - - For ``BICYCLE`` and ``TWO_WHEELER`` requests, this feature - returns routes similar to those returned when you don't - specify ``requested_reference_routes``. - - This feature is not compatible with any other travel modes, - via intermediate waypoints, or ``optimize_waypoint_order``; - such requests will fail. However, you can use it with any - ``routing_preference``. - """ - REFERENCE_ROUTE_UNSPECIFIED = 0 - FUEL_EFFICIENT = 1 - SHORTER_DISTANCE = 2 - - class ExtraComputation(proto.Enum): - r"""Extra computations to perform while completing the request. - - Values: - EXTRA_COMPUTATION_UNSPECIFIED (0): - Not used. Requests containing this value will - fail. - TOLLS (1): - Toll information for the route(s). - FUEL_CONSUMPTION (2): - Estimated fuel consumption for the route(s). - TRAFFIC_ON_POLYLINE (3): - Traffic aware polylines for the route(s). - HTML_FORMATTED_NAVIGATION_INSTRUCTIONS (4): - ```NavigationInstructions`` `__ - presented as a formatted HTML text string. This content is - meant to be read as-is. This content is for display only. Do - not programmatically parse it. - FLYOVER_INFO_ON_POLYLINE (7): - Flyover information for the route(s). The - ``routes.polyline_details.flyover_info`` fieldmask must be - specified to return this information. This data will only - currently be populated for certain metros in India. This - feature is experimental, and the SKU/charge is subject to - change. - NARROW_ROAD_INFO_ON_POLYLINE (8): - Narrow road information for the route(s). The - ``routes.polyline_details.narrow_road_info`` fieldmask must - be specified to return this information. This data will only - currently be populated for certain metros in India. This - feature is experimental, and the SKU/charge is subject to - change. - """ - EXTRA_COMPUTATION_UNSPECIFIED = 0 - TOLLS = 1 - FUEL_CONSUMPTION = 2 - TRAFFIC_ON_POLYLINE = 3 - HTML_FORMATTED_NAVIGATION_INSTRUCTIONS = 4 - FLYOVER_INFO_ON_POLYLINE = 7 - NARROW_ROAD_INFO_ON_POLYLINE = 8 - - origin: gmr_waypoint.Waypoint = proto.Field( - proto.MESSAGE, - number=1, - message=gmr_waypoint.Waypoint, - ) - destination: gmr_waypoint.Waypoint = proto.Field( - proto.MESSAGE, - number=2, - message=gmr_waypoint.Waypoint, - ) - intermediates: MutableSequence[gmr_waypoint.Waypoint] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=gmr_waypoint.Waypoint, - ) - travel_mode: route_travel_mode.RouteTravelMode = proto.Field( - proto.ENUM, - number=4, - enum=route_travel_mode.RouteTravelMode, - ) - routing_preference: gmr_routing_preference.RoutingPreference = proto.Field( - proto.ENUM, - number=5, - enum=gmr_routing_preference.RoutingPreference, - ) - polyline_quality: polyline.PolylineQuality = proto.Field( - proto.ENUM, - number=6, - enum=polyline.PolylineQuality, - ) - polyline_encoding: polyline.PolylineEncoding = proto.Field( - proto.ENUM, - number=12, - enum=polyline.PolylineEncoding, - ) - departure_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - arrival_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=19, - message=timestamp_pb2.Timestamp, - ) - compute_alternative_routes: bool = proto.Field( - proto.BOOL, - number=8, - ) - route_modifiers: gmr_route_modifiers.RouteModifiers = proto.Field( - proto.MESSAGE, - number=9, - message=gmr_route_modifiers.RouteModifiers, - ) - language_code: str = proto.Field( - proto.STRING, - number=10, - ) - region_code: str = proto.Field( - proto.STRING, - number=16, - ) - units: gmr_units.Units = proto.Field( - proto.ENUM, - number=11, - enum=gmr_units.Units, - ) - optimize_waypoint_order: bool = proto.Field( - proto.BOOL, - number=13, - ) - requested_reference_routes: MutableSequence[ReferenceRoute] = proto.RepeatedField( - proto.ENUM, - number=14, - enum=ReferenceRoute, - ) - extra_computations: MutableSequence[ExtraComputation] = proto.RepeatedField( - proto.ENUM, - number=15, - enum=ExtraComputation, - ) - traffic_model: gmr_traffic_model.TrafficModel = proto.Field( - proto.ENUM, - number=18, - enum=gmr_traffic_model.TrafficModel, - ) - transit_preferences: gmr_transit_preferences.TransitPreferences = proto.Field( - proto.MESSAGE, - number=20, - message=gmr_transit_preferences.TransitPreferences, - ) - - -class ComputeRoutesResponse(proto.Message): - r"""ComputeRoutes the response message. - - Attributes: - routes (MutableSequence[google.maps.routing_v2.types.Route]): - Contains an array of computed routes (up to three) when you - specify ``compute_alternatives_routes``, and contains just - one route when you don't. When this array contains multiple - entries, the first one is the most recommended route. If the - array is empty, then it means no route could be found. - fallback_info (google.maps.routing_v2.types.FallbackInfo): - In some cases when the server is not able to - compute the route results with all of the input - preferences, it may fallback to using a - different way of computation. When fallback mode - is used, this field contains detailed info about - the fallback response. Otherwise this field is - unset. - geocoding_results (google.maps.routing_v2.types.GeocodingResults): - Contains geocoding response info for - waypoints specified as addresses. - """ - - routes: MutableSequence[route.Route] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=route.Route, - ) - fallback_info: gmr_fallback_info.FallbackInfo = proto.Field( - proto.MESSAGE, - number=2, - message=gmr_fallback_info.FallbackInfo, - ) - geocoding_results: gmr_geocoding_results.GeocodingResults = proto.Field( - proto.MESSAGE, - number=3, - message=gmr_geocoding_results.GeocodingResults, - ) - - -class ComputeRouteMatrixRequest(proto.Message): - r"""ComputeRouteMatrix request message - - Attributes: - origins (MutableSequence[google.maps.routing_v2.types.RouteMatrixOrigin]): - Required. Array of origins, which determines the rows of the - response matrix. Several size restrictions apply to the - cardinality of origins and destinations: - - - The sum of the number of origins + the number of - destinations specified as either ``place_id`` or - ``address`` must be no greater than 50. - - The product of number of origins × number of destinations - must be no greater than 625 in any case. - - The product of the number of origins × number of - destinations must be no greater than 100 if - routing_preference is set to ``TRAFFIC_AWARE_OPTIMAL``. - - The product of the number of origins × number of - destinations must be no greater than 100 if travel_mode - is set to ``TRANSIT``. - destinations (MutableSequence[google.maps.routing_v2.types.RouteMatrixDestination]): - Required. Array of destinations, which - determines the columns of the response matrix. - travel_mode (google.maps.routing_v2.types.RouteTravelMode): - Optional. Specifies the mode of - transportation. - routing_preference (google.maps.routing_v2.types.RoutingPreference): - Optional. Specifies how to compute the route. The server - attempts to use the selected routing preference to compute - the route. If the routing preference results in an error or - an extra long latency, an error is returned. You can specify - this option only when the ``travel_mode`` is ``DRIVE`` or - ``TWO_WHEELER``, otherwise the request fails. - departure_time (google.protobuf.timestamp_pb2.Timestamp): - Optional. The departure time. If you don't set this value, - then this value defaults to the time that you made the - request. NOTE: You can only specify a ``departure_time`` in - the past when - [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode] - is set to ``TRANSIT``. - arrival_time (google.protobuf.timestamp_pb2.Timestamp): - Optional. The arrival time. NOTE: Can only be set when - [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode] - is set to ``TRANSIT``. You can specify either - ``departure_time`` or ``arrival_time``, but not both. - language_code (str): - Optional. The BCP-47 language code, such as "en-US" or - "sr-Latn". For more information, see `Unicode Locale - Identifier `__. - See `Language - Support `__ - for the list of supported languages. When you don't provide - this value, the display language is inferred from the - location of the first origin. - region_code (str): - Optional. The region code, specified as a ccTLD ("top-level - domain") two-character value. For more information see - `Country code top-level - domains `__. - units (google.maps.routing_v2.types.Units): - Optional. Specifies the units of measure for - the display fields. - extra_computations (MutableSequence[google.maps.routing_v2.types.ComputeRouteMatrixRequest.ExtraComputation]): - Optional. A list of extra computations which - may be used to complete the request. Note: These - extra computations may return extra fields on - the response. These extra fields must also be - specified in the field mask to be returned in - the response. - traffic_model (google.maps.routing_v2.types.TrafficModel): - Optional. Specifies the assumptions to use when calculating - time in traffic. This setting affects the value returned in - the duration field in the - [RouteMatrixElement][google.maps.routing.v2.RouteMatrixElement] - which contains the predicted time in traffic based on - historical averages. - [RoutingPreference][google.maps.routing.v2.RoutingPreference] - to ``TRAFFIC_AWARE_OPTIMAL`` and - [RouteTravelMode][google.maps.routing.v2.RouteTravelMode] to - ``DRIVE``. Defaults to ``BEST_GUESS`` if traffic is - requested and ``TrafficModel`` is not specified. - transit_preferences (google.maps.routing_v2.types.TransitPreferences): - Optional. Specifies preferences that influence the route - returned for ``TRANSIT`` routes. NOTE: You can only specify - a ``transit_preferences`` when - [RouteTravelMode][google.maps.routing.v2.RouteTravelMode] is - set to ``TRANSIT``. - """ - class ExtraComputation(proto.Enum): - r"""Extra computations to perform while completing the request. - - Values: - EXTRA_COMPUTATION_UNSPECIFIED (0): - Not used. Requests containing this value will - fail. - TOLLS (1): - Toll information for the matrix element(s). - """ - EXTRA_COMPUTATION_UNSPECIFIED = 0 - TOLLS = 1 - - origins: MutableSequence['RouteMatrixOrigin'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='RouteMatrixOrigin', - ) - destinations: MutableSequence['RouteMatrixDestination'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='RouteMatrixDestination', - ) - travel_mode: route_travel_mode.RouteTravelMode = proto.Field( - proto.ENUM, - number=3, - enum=route_travel_mode.RouteTravelMode, - ) - routing_preference: gmr_routing_preference.RoutingPreference = proto.Field( - proto.ENUM, - number=4, - enum=gmr_routing_preference.RoutingPreference, - ) - departure_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - arrival_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=11, - message=timestamp_pb2.Timestamp, - ) - language_code: str = proto.Field( - proto.STRING, - number=6, - ) - region_code: str = proto.Field( - proto.STRING, - number=9, - ) - units: gmr_units.Units = proto.Field( - proto.ENUM, - number=7, - enum=gmr_units.Units, - ) - extra_computations: MutableSequence[ExtraComputation] = proto.RepeatedField( - proto.ENUM, - number=8, - enum=ExtraComputation, - ) - traffic_model: gmr_traffic_model.TrafficModel = proto.Field( - proto.ENUM, - number=10, - enum=gmr_traffic_model.TrafficModel, - ) - transit_preferences: gmr_transit_preferences.TransitPreferences = proto.Field( - proto.MESSAGE, - number=12, - message=gmr_transit_preferences.TransitPreferences, - ) - - -class RouteMatrixOrigin(proto.Message): - r"""A single origin for ComputeRouteMatrixRequest - - Attributes: - waypoint (google.maps.routing_v2.types.Waypoint): - Required. Origin waypoint - route_modifiers (google.maps.routing_v2.types.RouteModifiers): - Optional. Modifiers for every route that - takes this as the origin - """ - - waypoint: gmr_waypoint.Waypoint = proto.Field( - proto.MESSAGE, - number=1, - message=gmr_waypoint.Waypoint, - ) - route_modifiers: gmr_route_modifiers.RouteModifiers = proto.Field( - proto.MESSAGE, - number=2, - message=gmr_route_modifiers.RouteModifiers, - ) - - -class RouteMatrixDestination(proto.Message): - r"""A single destination for ComputeRouteMatrixRequest - - Attributes: - waypoint (google.maps.routing_v2.types.Waypoint): - Required. Destination waypoint - """ - - waypoint: gmr_waypoint.Waypoint = proto.Field( - proto.MESSAGE, - number=1, - message=gmr_waypoint.Waypoint, - ) - - -class RouteMatrixElement(proto.Message): - r"""Contains route information computed for an origin/destination - pair in the ComputeRouteMatrix API. This proto can be streamed - to the client. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - origin_index (int): - Zero-based index of the origin in the - request. - - This field is a member of `oneof`_ ``_origin_index``. - destination_index (int): - Zero-based index of the destination in the - request. - - This field is a member of `oneof`_ ``_destination_index``. - status (google.rpc.status_pb2.Status): - Error status code for this element. - condition (google.maps.routing_v2.types.RouteMatrixElementCondition): - Indicates whether the route was found or not. - Independent of status. - distance_meters (int): - The travel distance of the route, in meters. - duration (google.protobuf.duration_pb2.Duration): - The length of time needed to navigate the route. If you set - the - [routing_preference][google.maps.routing.v2.ComputeRouteMatrixRequest.routing_preference] - to ``TRAFFIC_UNAWARE``, then this value is the same as - ``static_duration``. If you set the ``routing_preference`` - to either ``TRAFFIC_AWARE`` or ``TRAFFIC_AWARE_OPTIMAL``, - then this value is calculated taking traffic conditions into - account. - static_duration (google.protobuf.duration_pb2.Duration): - The duration of traveling through the route - without taking traffic conditions into - consideration. - travel_advisory (google.maps.routing_v2.types.RouteTravelAdvisory): - Additional information about the route. For - example: restriction information and toll - information - fallback_info (google.maps.routing_v2.types.FallbackInfo): - In some cases when the server is not able to - compute the route with the given preferences for - this particular origin/destination pair, it may - fall back to using a different mode of - computation. When fallback mode is used, this - field contains detailed information about the - fallback response. Otherwise this field is - unset. - localized_values (google.maps.routing_v2.types.RouteMatrixElement.LocalizedValues): - Text representations of properties of the - ``RouteMatrixElement``. - """ - - class LocalizedValues(proto.Message): - r"""Text representations of certain properties. - - Attributes: - distance (google.type.localized_text_pb2.LocalizedText): - Travel distance represented in text form. - duration (google.type.localized_text_pb2.LocalizedText): - Duration represented in text form taking traffic conditions - into consideration. Note: If traffic information was not - requested, this value is the same value as static_duration. - static_duration (google.type.localized_text_pb2.LocalizedText): - Duration represented in text form without - taking traffic conditions into consideration. - transit_fare (google.type.localized_text_pb2.LocalizedText): - Transit fare represented in text form. - """ - - distance: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=1, - message=localized_text_pb2.LocalizedText, - ) - duration: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=2, - message=localized_text_pb2.LocalizedText, - ) - static_duration: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=3, - message=localized_text_pb2.LocalizedText, - ) - transit_fare: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=4, - message=localized_text_pb2.LocalizedText, - ) - - origin_index: int = proto.Field( - proto.INT32, - number=1, - optional=True, - ) - destination_index: int = proto.Field( - proto.INT32, - number=2, - optional=True, - ) - status: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=3, - message=status_pb2.Status, - ) - condition: 'RouteMatrixElementCondition' = proto.Field( - proto.ENUM, - number=9, - enum='RouteMatrixElementCondition', - ) - distance_meters: int = proto.Field( - proto.INT32, - number=4, - ) - duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=5, - message=duration_pb2.Duration, - ) - static_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=6, - message=duration_pb2.Duration, - ) - travel_advisory: route.RouteTravelAdvisory = proto.Field( - proto.MESSAGE, - number=7, - message=route.RouteTravelAdvisory, - ) - fallback_info: gmr_fallback_info.FallbackInfo = proto.Field( - proto.MESSAGE, - number=8, - message=gmr_fallback_info.FallbackInfo, - ) - localized_values: LocalizedValues = proto.Field( - proto.MESSAGE, - number=10, - message=LocalizedValues, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py deleted file mode 100644 index a0bd24974a2d..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py +++ /dev/null @@ -1,71 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.routing.v2', - manifest={ - 'RoutingPreference', - }, -) - - -class RoutingPreference(proto.Enum): - r"""A set of values that specify factors to take into - consideration when calculating the route. - - Values: - ROUTING_PREFERENCE_UNSPECIFIED (0): - No routing preference specified. Default to - ``TRAFFIC_UNAWARE``. - TRAFFIC_UNAWARE (1): - Computes routes without taking live traffic conditions into - consideration. Suitable when traffic conditions don't matter - or are not applicable. Using this value produces the lowest - latency. Note: For - [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode] - ``DRIVE`` and ``TWO_WHEELER``, the route and duration chosen - are based on road network and average time-independent - traffic conditions, not current road conditions. - Consequently, routes may include roads that are temporarily - closed. Results for a given request may vary over time due - to changes in the road network, updated average traffic - conditions, and the distributed nature of the service. - Results may also vary between nearly-equivalent routes at - any time or frequency. - TRAFFIC_AWARE (2): - Calculates routes taking live traffic conditions into - consideration. In contrast to ``TRAFFIC_AWARE_OPTIMAL``, - some optimizations are applied to significantly reduce - latency. - TRAFFIC_AWARE_OPTIMAL (3): - Calculates the routes taking live traffic - conditions into consideration, without applying - most performance optimizations. Using this value - produces the highest latency. - """ - ROUTING_PREFERENCE_UNSPECIFIED = 0 - TRAFFIC_UNAWARE = 1 - TRAFFIC_AWARE = 2 - TRAFFIC_AWARE_OPTIMAL = 3 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py deleted file mode 100644 index 5ace8166d68d..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py +++ /dev/null @@ -1,92 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.routing.v2', - manifest={ - 'SpeedReadingInterval', - }, -) - - -class SpeedReadingInterval(proto.Message): - r"""Traffic density indicator on a contiguous segment of a polyline or - path. Given a path with points P_0, P_1, ... , P_N (zero-based - index), the ``SpeedReadingInterval`` defines an interval and - describes its traffic using the following categories. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - start_polyline_point_index (int): - The starting index of this interval in the - polyline. - - This field is a member of `oneof`_ ``_start_polyline_point_index``. - end_polyline_point_index (int): - The ending index of this interval in the - polyline. - - This field is a member of `oneof`_ ``_end_polyline_point_index``. - speed (google.maps.routing_v2.types.SpeedReadingInterval.Speed): - Traffic speed in this interval. - - This field is a member of `oneof`_ ``speed_type``. - """ - class Speed(proto.Enum): - r"""The classification of polyline speed based on traffic data. - - Values: - SPEED_UNSPECIFIED (0): - Default value. This value is unused. - NORMAL (1): - Normal speed, no slowdown is detected. - SLOW (2): - Slowdown detected, but no traffic jam formed. - TRAFFIC_JAM (3): - Traffic jam detected. - """ - SPEED_UNSPECIFIED = 0 - NORMAL = 1 - SLOW = 2 - TRAFFIC_JAM = 3 - - start_polyline_point_index: int = proto.Field( - proto.INT32, - number=1, - optional=True, - ) - end_polyline_point_index: int = proto.Field( - proto.INT32, - number=2, - optional=True, - ) - speed: Speed = proto.Field( - proto.ENUM, - number=3, - oneof='speed_type', - enum=Speed, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py deleted file mode 100644 index c6cf129bc732..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 money_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'TollInfo', - }, -) - - -class TollInfo(proto.Message): - r"""Encapsulates toll information on a - [``Route``][google.maps.routing.v2.Route] or on a - [``RouteLeg``][google.maps.routing.v2.RouteLeg]. - - Attributes: - estimated_price (MutableSequence[google.type.money_pb2.Money]): - The monetary amount of tolls for the corresponding - [``Route``][google.maps.routing.v2.Route] or - [``RouteLeg``][google.maps.routing.v2.RouteLeg]. This list - contains a money amount for each currency that is expected - to be charged by the toll stations. Typically this list will - contain only one item for routes with tolls in one currency. - For international trips, this list may contain multiple - items to reflect tolls in different currencies. - """ - - estimated_price: MutableSequence[money_pb2.Money] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=money_pb2.Money, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py deleted file mode 100644 index d0de0e8a78a8..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.routing.v2', - manifest={ - 'TollPass', - }, -) - - -class TollPass(proto.Enum): - r"""List of toll passes around the world that we support. - - Values: - TOLL_PASS_UNSPECIFIED (0): - Not used. If this value is used, then the - request fails. - AU_ETOLL_TAG (82): - Sydney toll pass. See additional details at - https://www.myetoll.com.au. - AU_EWAY_TAG (83): - Sydney toll pass. See additional details at - https://www.tollpay.com.au. - AU_LINKT (2): - Australia-wide toll pass. - See additional details at - https://www.linkt.com.au/. - AR_TELEPASE (3): - Argentina toll pass. See additional details - at https://telepase.com.ar - BR_AUTO_EXPRESO (81): - Brazil toll pass. See additional details at - https://www.autoexpreso.com - BR_CONECTCAR (7): - Brazil toll pass. See additional details at - https://conectcar.com. - BR_MOVE_MAIS (8): - Brazil toll pass. See additional details at - https://movemais.com. - BR_PASSA_RAPIDO (88): - Brazil toll pass. See additional details at - https://pasorapido.gob.do/ - BR_SEM_PARAR (9): - Brazil toll pass. See additional details at - https://www.semparar.com.br. - BR_TAGGY (10): - Brazil toll pass. See additional details at - https://taggy.com.br. - BR_VELOE (11): - Brazil toll pass. See additional details at - https://veloe.com.br/site/onde-usar. - CA_US_AKWASASNE_SEAWAY_CORPORATE_CARD (84): - Canada to United States border crossing. - CA_US_AKWASASNE_SEAWAY_TRANSIT_CARD (85): - Canada to United States border crossing. - CA_US_BLUE_WATER_EDGE_PASS (18): - Ontario, Canada to Michigan, United States - border crossing. - CA_US_CONNEXION (19): - Ontario, Canada to Michigan, United States - border crossing. - CA_US_NEXUS_CARD (20): - Canada to United States border crossing. - ID_E_TOLL (16): - Indonesia. - E-card provided by multiple banks used to pay - for tolls. All e-cards via banks are charged the - same so only one enum value is needed. E.g. - - Bank Mandiri - https://www.bankmandiri.co.id/e-money - - BCA https://www.bca.co.id/flazz - - BNI - https://www.bni.co.id/id-id/ebanking/tapcash - IN_FASTAG (78): - India. - IN_LOCAL_HP_PLATE_EXEMPT (79): - India, HP state plate exemption. - JP_ETC (98): - Japan - ETC. Electronic wireless system to collect - tolls. https://www.go-etc.jp/ - JP_ETC2 (99): - Japan - ETC2.0. New version of ETC with further discount - and bidirectional communication between devices - on vehicles and antennas on the road. - https://www.go-etc.jp/etc2/index.html - MX_IAVE (90): - Mexico toll pass. - https://iave.capufe.gob.mx/#/ - MX_PASE (91): - Mexico - https://www.pase.com.mx - MX_QUICKPASS (93): - Mexico - https://operadoravial.com/quick-pass/ - MX_SISTEMA_TELEPEAJE_CHIHUAHUA (89): - http://appsh.chihuahua.gob.mx/transparencia/?doc=/ingresos/TelepeajeFormato4.pdf - MX_TAG_IAVE (12): - Mexico - MX_TAG_TELEVIA (13): - Mexico toll pass company. One of many - operating in Mexico City. See additional details - at https://www.televia.com.mx. - MX_TELEVIA (92): - Mexico toll pass company. One of many - operating in Mexico City. - https://www.televia.com.mx - MX_VIAPASS (14): - Mexico toll pass. See additional details at - https://www.viapass.com.mx/viapass/web_home.aspx. - US_AL_FREEDOM_PASS (21): - AL, USA. - US_AK_ANTON_ANDERSON_TUNNEL_BOOK_OF_10_TICKETS (22): - AK, USA. - US_CA_FASTRAK (4): - CA, USA. - US_CA_FASTRAK_CAV_STICKER (86): - Indicates driver has any FasTrak pass in - addition to the DMV issued Clean Air Vehicle - (CAV) sticker. - https://www.bayareafastrak.org/en/guide/doINeedFlex.shtml - US_CO_EXPRESSTOLL (23): - CO, USA. - US_CO_GO_PASS (24): - CO, USA. - US_DE_EZPASSDE (25): - DE, USA. - US_FL_BOB_SIKES_TOLL_BRIDGE_PASS (65): - FL, USA. - US_FL_DUNES_COMMUNITY_DEVELOPMENT_DISTRICT_EXPRESSCARD (66): - FL, USA. - US_FL_EPASS (67): - FL, USA. - US_FL_GIBA_TOLL_PASS (68): - FL, USA. - US_FL_LEEWAY (69): - FL, USA. - US_FL_SUNPASS (70): - FL, USA. - US_FL_SUNPASS_PRO (71): - FL, USA. - US_IL_EZPASSIL (73): - IL, USA. - US_IL_IPASS (72): - IL, USA. - US_IN_EZPASSIN (26): - IN, USA. - US_KS_BESTPASS_HORIZON (27): - KS, USA. - US_KS_KTAG (28): - KS, USA. - US_KS_NATIONALPASS (29): - KS, USA. - US_KS_PREPASS_ELITEPASS (30): - KS, USA. - US_KY_RIVERLINK (31): - KY, USA. - US_LA_GEAUXPASS (32): - LA, USA. - US_LA_TOLL_TAG (33): - LA, USA. - US_MA_EZPASSMA (6): - MA, USA. - US_MD_EZPASSMD (34): - MD, USA. - US_ME_EZPASSME (35): - ME, USA. - US_MI_AMBASSADOR_BRIDGE_PREMIER_COMMUTER_CARD (36): - MI, USA. - US_MI_BCPASS (94): - MI, USA. - US_MI_GROSSE_ILE_TOLL_BRIDGE_PASS_TAG (37): - MI, USA. - US_MI_IQ_PROX_CARD (38): - MI, USA. - Deprecated as this pass type no longer exists. - US_MI_IQ_TAG (95): - MI, USA. - US_MI_MACKINAC_BRIDGE_MAC_PASS (39): - MI, USA. - US_MI_NEXPRESS_TOLL (40): - MI, USA. - US_MN_EZPASSMN (41): - MN, USA. - US_NC_EZPASSNC (42): - NC, USA. - US_NC_PEACH_PASS (87): - NC, USA. - US_NC_QUICK_PASS (43): - NC, USA. - US_NH_EZPASSNH (80): - NH, USA. - US_NJ_DOWNBEACH_EXPRESS_PASS (75): - NJ, USA. - US_NJ_EZPASSNJ (74): - NJ, USA. - US_NY_EXPRESSPASS (76): - NY, USA. - US_NY_EZPASSNY (77): - NY, USA. - US_OH_EZPASSOH (44): - OH, USA. - US_PA_EZPASSPA (45): - PA, USA. - US_RI_EZPASSRI (46): - RI, USA. - US_SC_PALPASS (47): - SC, USA. - US_TX_AVI_TAG (97): - TX, USA. - US_TX_BANCPASS (48): - TX, USA. - US_TX_DEL_RIO_PASS (49): - TX, USA. - US_TX_EFAST_PASS (50): - TX, USA. - US_TX_EAGLE_PASS_EXPRESS_CARD (51): - TX, USA. - US_TX_EPTOLL (52): - TX, USA. - US_TX_EZ_CROSS (53): - TX, USA. - US_TX_EZTAG (54): - TX, USA. - US_TX_FUEGO_TAG (96): - TX, USA. - US_TX_LAREDO_TRADE_TAG (55): - TX, USA. - US_TX_PLUSPASS (56): - TX, USA. - US_TX_TOLLTAG (57): - TX, USA. - US_TX_TXTAG (58): - TX, USA. - US_TX_XPRESS_CARD (59): - TX, USA. - US_UT_ADAMS_AVE_PARKWAY_EXPRESSCARD (60): - UT, USA. - US_VA_EZPASSVA (61): - VA, USA. - US_WA_BREEZEBY (17): - WA, USA. - US_WA_GOOD_TO_GO (1): - WA, USA. - US_WV_EZPASSWV (62): - WV, USA. - US_WV_MEMORIAL_BRIDGE_TICKETS (63): - WV, USA. - US_WV_MOV_PASS (100): - WV, USA - US_WV_NEWELL_TOLL_BRIDGE_TICKET (64): - WV, USA. - """ - TOLL_PASS_UNSPECIFIED = 0 - AU_ETOLL_TAG = 82 - AU_EWAY_TAG = 83 - AU_LINKT = 2 - AR_TELEPASE = 3 - BR_AUTO_EXPRESO = 81 - BR_CONECTCAR = 7 - BR_MOVE_MAIS = 8 - BR_PASSA_RAPIDO = 88 - BR_SEM_PARAR = 9 - BR_TAGGY = 10 - BR_VELOE = 11 - CA_US_AKWASASNE_SEAWAY_CORPORATE_CARD = 84 - CA_US_AKWASASNE_SEAWAY_TRANSIT_CARD = 85 - CA_US_BLUE_WATER_EDGE_PASS = 18 - CA_US_CONNEXION = 19 - CA_US_NEXUS_CARD = 20 - ID_E_TOLL = 16 - IN_FASTAG = 78 - IN_LOCAL_HP_PLATE_EXEMPT = 79 - JP_ETC = 98 - JP_ETC2 = 99 - MX_IAVE = 90 - MX_PASE = 91 - MX_QUICKPASS = 93 - MX_SISTEMA_TELEPEAJE_CHIHUAHUA = 89 - MX_TAG_IAVE = 12 - MX_TAG_TELEVIA = 13 - MX_TELEVIA = 92 - MX_VIAPASS = 14 - US_AL_FREEDOM_PASS = 21 - US_AK_ANTON_ANDERSON_TUNNEL_BOOK_OF_10_TICKETS = 22 - US_CA_FASTRAK = 4 - US_CA_FASTRAK_CAV_STICKER = 86 - US_CO_EXPRESSTOLL = 23 - US_CO_GO_PASS = 24 - US_DE_EZPASSDE = 25 - US_FL_BOB_SIKES_TOLL_BRIDGE_PASS = 65 - US_FL_DUNES_COMMUNITY_DEVELOPMENT_DISTRICT_EXPRESSCARD = 66 - US_FL_EPASS = 67 - US_FL_GIBA_TOLL_PASS = 68 - US_FL_LEEWAY = 69 - US_FL_SUNPASS = 70 - US_FL_SUNPASS_PRO = 71 - US_IL_EZPASSIL = 73 - US_IL_IPASS = 72 - US_IN_EZPASSIN = 26 - US_KS_BESTPASS_HORIZON = 27 - US_KS_KTAG = 28 - US_KS_NATIONALPASS = 29 - US_KS_PREPASS_ELITEPASS = 30 - US_KY_RIVERLINK = 31 - US_LA_GEAUXPASS = 32 - US_LA_TOLL_TAG = 33 - US_MA_EZPASSMA = 6 - US_MD_EZPASSMD = 34 - US_ME_EZPASSME = 35 - US_MI_AMBASSADOR_BRIDGE_PREMIER_COMMUTER_CARD = 36 - US_MI_BCPASS = 94 - US_MI_GROSSE_ILE_TOLL_BRIDGE_PASS_TAG = 37 - US_MI_IQ_PROX_CARD = 38 - US_MI_IQ_TAG = 95 - US_MI_MACKINAC_BRIDGE_MAC_PASS = 39 - US_MI_NEXPRESS_TOLL = 40 - US_MN_EZPASSMN = 41 - US_NC_EZPASSNC = 42 - US_NC_PEACH_PASS = 87 - US_NC_QUICK_PASS = 43 - US_NH_EZPASSNH = 80 - US_NJ_DOWNBEACH_EXPRESS_PASS = 75 - US_NJ_EZPASSNJ = 74 - US_NY_EXPRESSPASS = 76 - US_NY_EZPASSNY = 77 - US_OH_EZPASSOH = 44 - US_PA_EZPASSPA = 45 - US_RI_EZPASSRI = 46 - US_SC_PALPASS = 47 - US_TX_AVI_TAG = 97 - US_TX_BANCPASS = 48 - US_TX_DEL_RIO_PASS = 49 - US_TX_EFAST_PASS = 50 - US_TX_EAGLE_PASS_EXPRESS_CARD = 51 - US_TX_EPTOLL = 52 - US_TX_EZ_CROSS = 53 - US_TX_EZTAG = 54 - US_TX_FUEGO_TAG = 96 - US_TX_LAREDO_TRADE_TAG = 55 - US_TX_PLUSPASS = 56 - US_TX_TOLLTAG = 57 - US_TX_TXTAG = 58 - US_TX_XPRESS_CARD = 59 - US_UT_ADAMS_AVE_PARKWAY_EXPRESSCARD = 60 - US_VA_EZPASSVA = 61 - US_WA_BREEZEBY = 17 - US_WA_GOOD_TO_GO = 1 - US_WV_EZPASSWV = 62 - US_WV_MEMORIAL_BRIDGE_TICKETS = 63 - US_WV_MOV_PASS = 100 - US_WV_NEWELL_TOLL_BRIDGE_TICKET = 64 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/traffic_model.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/traffic_model.py deleted file mode 100644 index 0f78d92f1f45..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/traffic_model.py +++ /dev/null @@ -1,64 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.routing.v2', - manifest={ - 'TrafficModel', - }, -) - - -class TrafficModel(proto.Enum): - r"""Specifies the assumptions to use when calculating time in traffic. - This setting affects the value returned in the ``duration`` field in - the response, which contains the predicted time in traffic based on - historical averages. - - Values: - TRAFFIC_MODEL_UNSPECIFIED (0): - Unused. If specified, will default to ``BEST_GUESS``. - BEST_GUESS (1): - Indicates that the returned ``duration`` should be the best - estimate of travel time given what is known about both - historical traffic conditions and live traffic. Live traffic - becomes more important the closer the ``departure_time`` is - to now. - PESSIMISTIC (2): - Indicates that the returned duration should - be longer than the actual travel time on most - days, though occasional days with particularly - bad traffic conditions may exceed this value. - OPTIMISTIC (3): - Indicates that the returned duration should - be shorter than the actual travel time on most - days, though occasional days with particularly - good traffic conditions may be faster than this - value. - """ - TRAFFIC_MODEL_UNSPECIFIED = 0 - BEST_GUESS = 1 - PESSIMISTIC = 2 - OPTIMISTIC = 3 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/transit.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/transit.py deleted file mode 100644 index bfa6ba1e738e..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/transit.py +++ /dev/null @@ -1,259 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.routing_v2.types import location as gmr_location -from google.type import localized_text_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'TransitAgency', - 'TransitLine', - 'TransitStop', - 'TransitVehicle', - }, -) - - -class TransitAgency(proto.Message): - r"""A transit agency that operates a transit line. - - Attributes: - name (str): - The name of this transit agency. - phone_number (str): - The transit agency's locale-specific - formatted phone number. - uri (str): - The transit agency's URI. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - phone_number: str = proto.Field( - proto.STRING, - number=2, - ) - uri: str = proto.Field( - proto.STRING, - number=3, - ) - - -class TransitLine(proto.Message): - r"""Contains information about the transit line used in this - step. - - Attributes: - agencies (MutableSequence[google.maps.routing_v2.types.TransitAgency]): - The transit agency (or agencies) that - operates this transit line. - name (str): - The full name of this transit line, For - example, "8 Avenue Local". - uri (str): - the URI for this transit line as provided by - the transit agency. - color (str): - The color commonly used in signage for this - line. Represented in hexadecimal. - icon_uri (str): - The URI for the icon associated with this - line. - name_short (str): - The short name of this transit line. This - name will normally be a line number, such as - "M7" or "355". - text_color (str): - The color commonly used in text on signage - for this line. Represented in hexadecimal. - vehicle (google.maps.routing_v2.types.TransitVehicle): - The type of vehicle that operates on this - transit line. - """ - - agencies: MutableSequence['TransitAgency'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='TransitAgency', - ) - name: str = proto.Field( - proto.STRING, - number=2, - ) - uri: str = proto.Field( - proto.STRING, - number=3, - ) - color: str = proto.Field( - proto.STRING, - number=4, - ) - icon_uri: str = proto.Field( - proto.STRING, - number=5, - ) - name_short: str = proto.Field( - proto.STRING, - number=6, - ) - text_color: str = proto.Field( - proto.STRING, - number=7, - ) - vehicle: 'TransitVehicle' = proto.Field( - proto.MESSAGE, - number=8, - message='TransitVehicle', - ) - - -class TransitStop(proto.Message): - r"""Information about a transit stop. - - Attributes: - name (str): - The name of the transit stop. - location (google.maps.routing_v2.types.Location): - The location of the stop expressed in - latitude/longitude coordinates. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - location: gmr_location.Location = proto.Field( - proto.MESSAGE, - number=2, - message=gmr_location.Location, - ) - - -class TransitVehicle(proto.Message): - r"""Information about a vehicle used in transit routes. - - Attributes: - name (google.type.localized_text_pb2.LocalizedText): - The name of this vehicle, capitalized. - type_ (google.maps.routing_v2.types.TransitVehicle.TransitVehicleType): - The type of vehicle used. - icon_uri (str): - The URI for an icon associated with this - vehicle type. - local_icon_uri (str): - The URI for the icon associated with this - vehicle type, based on the local transport - signage. - """ - class TransitVehicleType(proto.Enum): - r"""The type of vehicles for transit routes. - - Values: - TRANSIT_VEHICLE_TYPE_UNSPECIFIED (0): - Unused. - BUS (1): - Bus. - CABLE_CAR (2): - A vehicle that operates on a cable, usually on the ground. - Aerial cable cars may be of the type ``GONDOLA_LIFT``. - COMMUTER_TRAIN (3): - Commuter rail. - FERRY (4): - Ferry. - FUNICULAR (5): - A vehicle that is pulled up a steep incline - by a cable. A Funicular typically consists of - two cars, with each car acting as a - counterweight for the other. - GONDOLA_LIFT (6): - An aerial cable car. - HEAVY_RAIL (7): - Heavy rail. - HIGH_SPEED_TRAIN (8): - High speed train. - INTERCITY_BUS (9): - Intercity bus. - LONG_DISTANCE_TRAIN (10): - Long distance train. - METRO_RAIL (11): - Light rail transit. - MONORAIL (12): - Monorail. - OTHER (13): - All other vehicles. - RAIL (14): - Rail. - SHARE_TAXI (15): - Share taxi is a kind of bus with the ability - to drop off and pick up passengers anywhere on - its route. - SUBWAY (16): - Underground light rail. - TRAM (17): - Above ground light rail. - TROLLEYBUS (18): - Trolleybus. - """ - TRANSIT_VEHICLE_TYPE_UNSPECIFIED = 0 - BUS = 1 - CABLE_CAR = 2 - COMMUTER_TRAIN = 3 - FERRY = 4 - FUNICULAR = 5 - GONDOLA_LIFT = 6 - HEAVY_RAIL = 7 - HIGH_SPEED_TRAIN = 8 - INTERCITY_BUS = 9 - LONG_DISTANCE_TRAIN = 10 - METRO_RAIL = 11 - MONORAIL = 12 - OTHER = 13 - RAIL = 14 - SHARE_TAXI = 15 - SUBWAY = 16 - TRAM = 17 - TROLLEYBUS = 18 - - name: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=1, - message=localized_text_pb2.LocalizedText, - ) - type_: TransitVehicleType = proto.Field( - proto.ENUM, - number=2, - enum=TransitVehicleType, - ) - icon_uri: str = proto.Field( - proto.STRING, - number=3, - ) - local_icon_uri: str = proto.Field( - proto.STRING, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/transit_preferences.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/transit_preferences.py deleted file mode 100644 index 7786f8811da3..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/transit_preferences.py +++ /dev/null @@ -1,97 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.routing.v2', - manifest={ - 'TransitPreferences', - }, -) - - -class TransitPreferences(proto.Message): - r"""Preferences for ``TRANSIT`` based routes that influence the route - that is returned. - - Attributes: - allowed_travel_modes (MutableSequence[google.maps.routing_v2.types.TransitPreferences.TransitTravelMode]): - A set of travel modes to use when getting a ``TRANSIT`` - route. Defaults to all supported modes of travel. - routing_preference (google.maps.routing_v2.types.TransitPreferences.TransitRoutingPreference): - A routing preference that, when specified, influences the - ``TRANSIT`` route returned. - """ - class TransitTravelMode(proto.Enum): - r"""A set of values used to specify the mode of transit. - - Values: - TRANSIT_TRAVEL_MODE_UNSPECIFIED (0): - No transit travel mode specified. - BUS (1): - Travel by bus. - SUBWAY (2): - Travel by subway. - TRAIN (3): - Travel by train. - LIGHT_RAIL (4): - Travel by light rail or tram. - RAIL (5): - Travel by rail. This is equivalent to a combination of - ``SUBWAY``, ``TRAIN``, and ``LIGHT_RAIL``. - """ - TRANSIT_TRAVEL_MODE_UNSPECIFIED = 0 - BUS = 1 - SUBWAY = 2 - TRAIN = 3 - LIGHT_RAIL = 4 - RAIL = 5 - - class TransitRoutingPreference(proto.Enum): - r"""Specifies routing preferences for transit routes. - - Values: - TRANSIT_ROUTING_PREFERENCE_UNSPECIFIED (0): - No preference specified. - LESS_WALKING (1): - Indicates that the calculated route should - prefer limited amounts of walking. - FEWER_TRANSFERS (2): - Indicates that the calculated route should - prefer a limited number of transfers. - """ - TRANSIT_ROUTING_PREFERENCE_UNSPECIFIED = 0 - LESS_WALKING = 1 - FEWER_TRANSFERS = 2 - - allowed_travel_modes: MutableSequence[TransitTravelMode] = proto.RepeatedField( - proto.ENUM, - number=1, - enum=TransitTravelMode, - ) - routing_preference: TransitRoutingPreference = proto.Field( - proto.ENUM, - number=2, - enum=TransitRoutingPreference, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py deleted file mode 100644 index 911de7f76fd7..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.routing.v2', - manifest={ - 'Units', - }, -) - - -class Units(proto.Enum): - r"""A set of values that specify the unit of measure used in the - display. - - Values: - UNITS_UNSPECIFIED (0): - Units of measure not specified. Defaults to - the unit of measure inferred from the request. - METRIC (1): - Metric units of measure. - IMPERIAL (2): - Imperial (English) units of measure. - """ - UNITS_UNSPECIFIED = 0 - METRIC = 1 - IMPERIAL = 2 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py deleted file mode 100644 index 9da25c5d86d9..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.routing.v2', - manifest={ - 'VehicleEmissionType', - }, -) - - -class VehicleEmissionType(proto.Enum): - r"""A set of values describing the vehicle's emission type. Applies only - to the ``DRIVE`` - [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode]. - - Values: - VEHICLE_EMISSION_TYPE_UNSPECIFIED (0): - No emission type specified. Default to ``GASOLINE``. - GASOLINE (1): - Gasoline/petrol fueled vehicle. - ELECTRIC (2): - Electricity powered vehicle. - HYBRID (3): - Hybrid fuel (such as gasoline + electric) - vehicle. - DIESEL (4): - Diesel fueled vehicle. - """ - VEHICLE_EMISSION_TYPE_UNSPECIFIED = 0 - GASOLINE = 1 - ELECTRIC = 2 - HYBRID = 3 - DIESEL = 4 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py deleted file mode 100644 index 59b79853333c..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.routing_v2.types import vehicle_emission_type - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'VehicleInfo', - }, -) - - -class VehicleInfo(proto.Message): - r"""Contains the vehicle information, such as the vehicle - emission type. - - Attributes: - emission_type (google.maps.routing_v2.types.VehicleEmissionType): - Describes the vehicle's emission type. Applies only to the - ``DRIVE`` - [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode]. - """ - - emission_type: vehicle_emission_type.VehicleEmissionType = proto.Field( - proto.ENUM, - number=2, - enum=vehicle_emission_type.VehicleEmissionType, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py deleted file mode 100644 index d6748f9d6db3..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py +++ /dev/null @@ -1,126 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.routing_v2.types import location as gmr_location - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'Waypoint', - }, -) - - -class Waypoint(proto.Message): - r"""Encapsulates a waypoint. Waypoints mark both the beginning - and end of a route, and include intermediate stops along the - route. - - 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 (google.maps.routing_v2.types.Location): - A point specified using geographic - coordinates, including an optional heading. - - This field is a member of `oneof`_ ``location_type``. - place_id (str): - The POI Place ID associated with the - waypoint. - - This field is a member of `oneof`_ ``location_type``. - address (str): - Human readable address or a plus code. - See https://plus.codes for details. - - This field is a member of `oneof`_ ``location_type``. - via (bool): - Marks this waypoint as a milestone rather a stopping point. - For each non-via waypoint in the request, the response - appends an entry to the - [``legs``][google.maps.routing.v2.Route.legs] array to - provide the details for stopovers on that leg of the trip. - Set this value to true when you want the route to pass - through this waypoint without stopping over. Via waypoints - don't cause an entry to be added to the ``legs`` array, but - they do route the journey through the waypoint. You can only - set this value on waypoints that are intermediates. The - request fails if you set this field on terminal waypoints. - If ``ComputeRoutesRequest.optimize_waypoint_order`` is set - to true then this field cannot be set to true; otherwise, - the request fails. - vehicle_stopover (bool): - Indicates that the waypoint is meant for vehicles to stop - at, where the intention is to either pickup or drop-off. - When you set this value, the calculated route won't include - non-\ ``via`` waypoints on roads that are unsuitable for - pickup and drop-off. This option works only for ``DRIVE`` - and ``TWO_WHEELER`` travel modes, and when the - ``location_type`` is - [``Location``][google.maps.routing.v2.Location]. - side_of_road (bool): - Indicates that the location of this waypoint is meant to - have a preference for the vehicle to stop at a particular - side of road. When you set this value, the route will pass - through the location so that the vehicle can stop at the - side of road that the location is biased towards from the - center of the road. This option works only for ``DRIVE`` and - ``TWO_WHEELER`` - [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode]. - """ - - location: gmr_location.Location = proto.Field( - proto.MESSAGE, - number=1, - oneof='location_type', - message=gmr_location.Location, - ) - place_id: str = proto.Field( - proto.STRING, - number=2, - oneof='location_type', - ) - address: str = proto.Field( - proto.STRING, - number=7, - oneof='location_type', - ) - via: bool = proto.Field( - proto.BOOL, - number=3, - ) - vehicle_stopover: bool = proto.Field( - proto.BOOL, - number=4, - ) - side_of_road: bool = proto.Field( - proto.BOOL, - number=5, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/mypy.ini b/owl-bot-staging/google-maps-routing/v2/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-maps-routing/v2/noxfile.py b/owl-bot-staging/google-maps-routing/v2/noxfile.py deleted file mode 100644 index b99c4c5bb684..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/noxfile.py +++ /dev/null @@ -1,280 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", - "3.12", - "3.13", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = 'google-maps-routing' - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.13" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "prerelease_deps", -] - -@nox.session(python=ALL_PYTHON) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def unit(session, protobuf_implementation): - """Run the unit test suite.""" - - 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+") - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") - - # 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") - - session.run( - 'py.test', - '--quiet', - '--cov=google/maps/routing_v2/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - -@nox.session(python=ALL_PYTHON[-1]) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def prerelease_deps(session, protobuf_implementation): - """Run the unit test suite against pre-release versions of dependencies.""" - - 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 test environment dependencies - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - - # Install the package without dependencies - session.install('-e', '.', '--no-deps') - - # We test the minimum dependency versions using the minimum Python - # version so the lowest python runtime that we test has a corresponding constraints - # file, located at `testing/constraints--.txt`, which contains all of the - # 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 - ) - ] - - session.install(*constraints_deps) - - prerel_deps = [ - "googleapis-common-protos", - "google-api-core", - "google-auth", - # Exclude grpcio!=1.67.0rc1 which does not support python 3.13 - "grpcio!=1.67.0rc1", - "grpcio-status", - "protobuf", - "proto-plus", - ] - - for dep in prerel_deps: - session.install("--pre", "--no-deps", "--upgrade", dep) - - # Remaining dependencies - other_deps = [ - "requests", - ] - session.install(*other_deps) - - # Print out prerelease package versions - - session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") - session.run("python", "-c", "import google.auth; print(google.auth.__version__)") - session.run("python", "-c", "import grpc; print(grpc.__version__)") - session.run( - "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" - ) - session.run( - "python", "-c", "import proto; print(proto.__version__)" - ) - - session.run( - 'py.test', - '--quiet', - '--cov=google/maps/routing_v2/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - - -@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=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 docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==7.0.1", "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=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", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py deleted file mode 100644 index f326b5e2134c..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ComputeRouteMatrix -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-routing - - -# [START routes_v2_generated_Routes_ComputeRouteMatrix_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.maps import routing_v2 - - -async def sample_compute_route_matrix(): - # Create a client - client = routing_v2.RoutesAsyncClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRouteMatrixRequest( - ) - - # Make the request - stream = await client.compute_route_matrix(request=request) - - # Handle the response - async for response in stream: - print(response) - -# [END routes_v2_generated_Routes_ComputeRouteMatrix_async] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py deleted file mode 100644 index 9d1e1ae87791..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ComputeRouteMatrix -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-routing - - -# [START routes_v2_generated_Routes_ComputeRouteMatrix_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.maps import routing_v2 - - -def sample_compute_route_matrix(): - # Create a client - client = routing_v2.RoutesClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRouteMatrixRequest( - ) - - # Make the request - stream = client.compute_route_matrix(request=request) - - # Handle the response - for response in stream: - print(response) - -# [END routes_v2_generated_Routes_ComputeRouteMatrix_sync] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py deleted file mode 100644 index ba59057436a1..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ComputeRoutes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-routing - - -# [START routes_v2_generated_Routes_ComputeRoutes_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.maps import routing_v2 - - -async def sample_compute_routes(): - # Create a client - client = routing_v2.RoutesAsyncClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRoutesRequest( - ) - - # Make the request - response = await client.compute_routes(request=request) - - # Handle the response - print(response) - -# [END routes_v2_generated_Routes_ComputeRoutes_async] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py deleted file mode 100644 index 49d835374e19..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ComputeRoutes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-routing - - -# [START routes_v2_generated_Routes_ComputeRoutes_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.maps import routing_v2 - - -def sample_compute_routes(): - # Create a client - client = routing_v2.RoutesClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRoutesRequest( - ) - - # Make the request - response = client.compute_routes(request=request) - - # Handle the response - print(response) - -# [END routes_v2_generated_Routes_ComputeRoutes_sync] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json deleted file mode 100644 index ebb0fa3e0c00..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json +++ /dev/null @@ -1,321 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.maps.routing.v2", - "version": "v2" - } - ], - "language": "PYTHON", - "name": "google-maps-routing", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.routing_v2.RoutesAsyncClient", - "shortName": "RoutesAsyncClient" - }, - "fullName": "google.maps.routing_v2.RoutesAsyncClient.compute_route_matrix", - "method": { - "fullName": "google.maps.routing.v2.Routes.ComputeRouteMatrix", - "service": { - "fullName": "google.maps.routing.v2.Routes", - "shortName": "Routes" - }, - "shortName": "ComputeRouteMatrix" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.routing_v2.types.ComputeRouteMatrixRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "Iterable[google.maps.routing_v2.types.RouteMatrixElement]", - "shortName": "compute_route_matrix" - }, - "description": "Sample for ComputeRouteMatrix", - "file": "routes_v2_generated_routes_compute_route_matrix_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "routes_v2_generated_Routes_ComputeRouteMatrix_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": "routes_v2_generated_routes_compute_route_matrix_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.routing_v2.RoutesClient", - "shortName": "RoutesClient" - }, - "fullName": "google.maps.routing_v2.RoutesClient.compute_route_matrix", - "method": { - "fullName": "google.maps.routing.v2.Routes.ComputeRouteMatrix", - "service": { - "fullName": "google.maps.routing.v2.Routes", - "shortName": "Routes" - }, - "shortName": "ComputeRouteMatrix" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.routing_v2.types.ComputeRouteMatrixRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "Iterable[google.maps.routing_v2.types.RouteMatrixElement]", - "shortName": "compute_route_matrix" - }, - "description": "Sample for ComputeRouteMatrix", - "file": "routes_v2_generated_routes_compute_route_matrix_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "routes_v2_generated_Routes_ComputeRouteMatrix_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": "routes_v2_generated_routes_compute_route_matrix_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.routing_v2.RoutesAsyncClient", - "shortName": "RoutesAsyncClient" - }, - "fullName": "google.maps.routing_v2.RoutesAsyncClient.compute_routes", - "method": { - "fullName": "google.maps.routing.v2.Routes.ComputeRoutes", - "service": { - "fullName": "google.maps.routing.v2.Routes", - "shortName": "Routes" - }, - "shortName": "ComputeRoutes" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.routing_v2.types.ComputeRoutesRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.maps.routing_v2.types.ComputeRoutesResponse", - "shortName": "compute_routes" - }, - "description": "Sample for ComputeRoutes", - "file": "routes_v2_generated_routes_compute_routes_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "routes_v2_generated_Routes_ComputeRoutes_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": "routes_v2_generated_routes_compute_routes_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.routing_v2.RoutesClient", - "shortName": "RoutesClient" - }, - "fullName": "google.maps.routing_v2.RoutesClient.compute_routes", - "method": { - "fullName": "google.maps.routing.v2.Routes.ComputeRoutes", - "service": { - "fullName": "google.maps.routing.v2.Routes", - "shortName": "Routes" - }, - "shortName": "ComputeRoutes" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.routing_v2.types.ComputeRoutesRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.maps.routing_v2.types.ComputeRoutesResponse", - "shortName": "compute_routes" - }, - "description": "Sample for ComputeRoutes", - "file": "routes_v2_generated_routes_compute_routes_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "routes_v2_generated_Routes_ComputeRoutes_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": "routes_v2_generated_routes_compute_routes_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py b/owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py deleted file mode 100644 index 8c26fc095087..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py +++ /dev/null @@ -1,177 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 routingCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'compute_route_matrix': ('origins', 'destinations', 'travel_mode', 'routing_preference', 'departure_time', 'arrival_time', 'language_code', 'region_code', 'units', 'extra_computations', 'traffic_model', 'transit_preferences', ), - 'compute_routes': ('origin', 'destination', 'intermediates', 'travel_mode', 'routing_preference', 'polyline_quality', 'polyline_encoding', 'departure_time', 'arrival_time', 'compute_alternative_routes', 'route_modifiers', 'language_code', 'region_code', 'units', 'optimize_waypoint_order', 'requested_reference_routes', 'extra_computations', 'traffic_model', 'transit_preferences', ), - } - - 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=routingCallTransformer(), -): - """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 routing 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-maps-routing/v2/setup.py b/owl-bot-staging/google-maps-routing/v2/setup.py deleted file mode 100644 index 4336dee44a87..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/setup.py +++ /dev/null @@ -1,99 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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-maps-routing' - - -description = "Google Maps Routing API client library" - -version = None - -with open(os.path.join(package_root, 'google/maps/routing/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.0dev,!=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.0dev,!=2.24.0,!=2.25.0", - "proto-plus >= 1.22.3, <2.0.0dev", - "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'", - "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", - "google-geo-type >= 0.1.0, <1.0.0dev", -] -extras = { -} -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-routing" - -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-maps-routing/v2/testing/constraints-3.10.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.10.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/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-geo-type diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/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-geo-type diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/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-geo-type diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.13.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.13.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.13.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-geo-type diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt deleted file mode 100644 index 277853c664a0..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/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.0dev", -# 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-geo-type==0.1.0 diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/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-geo-type diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/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-geo-type diff --git a/owl-bot-staging/google-maps-routing/v2/tests/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-maps-routing/v2/tests/unit/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-maps-routing/v2/tests/unit/gapic/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py deleted file mode 100644 index 674acf72ee20..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py +++ /dev/null @@ -1,2336 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.routing_v2.services.routes import RoutesAsyncClient -from google.maps.routing_v2.services.routes import RoutesClient -from google.maps.routing_v2.services.routes import transports -from google.maps.routing_v2.types import fallback_info -from google.maps.routing_v2.types import geocoding_results -from google.maps.routing_v2.types import location -from google.maps.routing_v2.types import polyline -from google.maps.routing_v2.types import route -from google.maps.routing_v2.types import route_modifiers -from google.maps.routing_v2.types import route_travel_mode -from google.maps.routing_v2.types import routes_service -from google.maps.routing_v2.types import routing_preference -from google.maps.routing_v2.types import toll_passes -from google.maps.routing_v2.types import traffic_model -from google.maps.routing_v2.types import transit_preferences -from google.maps.routing_v2.types import units -from google.maps.routing_v2.types import vehicle_emission_type -from google.maps.routing_v2.types import vehicle_info -from google.maps.routing_v2.types import waypoint -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from google.type import latlng_pb2 # type: ignore -import google.auth - - -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 RoutesClient._get_default_mtls_endpoint(None) is None - assert RoutesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert RoutesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert RoutesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert RoutesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert RoutesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert RoutesClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert RoutesClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert RoutesClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - RoutesClient._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 RoutesClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert RoutesClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert RoutesClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - RoutesClient._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 RoutesClient._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 RoutesClient._get_client_cert_source(None, False) is None - assert RoutesClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert RoutesClient._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 RoutesClient._get_client_cert_source(None, True) is mock_default_cert_source - assert RoutesClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(RoutesClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RoutesClient)) -@mock.patch.object(RoutesAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RoutesAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = RoutesClient._DEFAULT_UNIVERSE - default_endpoint = RoutesClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = RoutesClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert RoutesClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert RoutesClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == RoutesClient.DEFAULT_MTLS_ENDPOINT - assert RoutesClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert RoutesClient._get_api_endpoint(None, None, default_universe, "always") == RoutesClient.DEFAULT_MTLS_ENDPOINT - assert RoutesClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == RoutesClient.DEFAULT_MTLS_ENDPOINT - assert RoutesClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert RoutesClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - RoutesClient._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 RoutesClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert RoutesClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert RoutesClient._get_universe_domain(None, None) == RoutesClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - RoutesClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - - -@pytest.mark.parametrize("client_class,transport_name", [ - (RoutesClient, "grpc"), - (RoutesAsyncClient, "grpc_asyncio"), - (RoutesClient, "rest"), -]) -def test_routes_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 == ( - 'routes.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://routes.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.RoutesGrpcTransport, "grpc"), - (transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.RoutesRestTransport, "rest"), -]) -def test_routes_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", [ - (RoutesClient, "grpc"), - (RoutesAsyncClient, "grpc_asyncio"), - (RoutesClient, "rest"), -]) -def test_routes_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 == ( - 'routes.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://routes.googleapis.com' - ) - - -def test_routes_client_get_transport_class(): - transport = RoutesClient.get_transport_class() - available_transports = [ - transports.RoutesGrpcTransport, - transports.RoutesRestTransport, - ] - assert transport in available_transports - - transport = RoutesClient.get_transport_class("grpc") - assert transport == transports.RoutesGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (RoutesClient, transports.RoutesGrpcTransport, "grpc"), - (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio"), - (RoutesClient, transports.RoutesRestTransport, "rest"), -]) -@mock.patch.object(RoutesClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RoutesClient)) -@mock.patch.object(RoutesAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RoutesAsyncClient)) -def test_routes_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(RoutesClient, '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(RoutesClient, '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", [ - (RoutesClient, transports.RoutesGrpcTransport, "grpc", "true"), - (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (RoutesClient, transports.RoutesGrpcTransport, "grpc", "false"), - (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (RoutesClient, transports.RoutesRestTransport, "rest", "true"), - (RoutesClient, transports.RoutesRestTransport, "rest", "false"), -]) -@mock.patch.object(RoutesClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RoutesClient)) -@mock.patch.object(RoutesAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RoutesAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_routes_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", [ - RoutesClient, RoutesAsyncClient -]) -@mock.patch.object(RoutesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesClient)) -@mock.patch.object(RoutesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesAsyncClient)) -def test_routes_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", [ - RoutesClient, RoutesAsyncClient -]) -@mock.patch.object(RoutesClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RoutesClient)) -@mock.patch.object(RoutesAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RoutesAsyncClient)) -def test_routes_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = RoutesClient._DEFAULT_UNIVERSE - default_endpoint = RoutesClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = RoutesClient._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", [ - (RoutesClient, transports.RoutesGrpcTransport, "grpc"), - (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio"), - (RoutesClient, transports.RoutesRestTransport, "rest"), -]) -def test_routes_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", [ - (RoutesClient, transports.RoutesGrpcTransport, "grpc", grpc_helpers), - (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (RoutesClient, transports.RoutesRestTransport, "rest", None), -]) -def test_routes_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_routes_client_client_options_from_dict(): - with mock.patch('google.maps.routing_v2.services.routes.transports.RoutesGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = RoutesClient( - 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", [ - (RoutesClient, transports.RoutesGrpcTransport, "grpc", grpc_helpers), - (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_routes_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( - "routes.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( -), - scopes=None, - default_host="routes.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - routes_service.ComputeRoutesRequest, - dict, -]) -def test_compute_routes(request_type, transport: str = 'grpc'): - client = RoutesClient( - 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.compute_routes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = routes_service.ComputeRoutesResponse( - ) - response = client.compute_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = routes_service.ComputeRoutesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, routes_service.ComputeRoutesResponse) - - -def test_compute_routes_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 = RoutesClient( - 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 = routes_service.ComputeRoutesRequest( - language_code='language_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.compute_routes), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.compute_routes(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == routes_service.ComputeRoutesRequest( - language_code='language_code_value', - region_code='region_code_value', - ) - -def test_compute_routes_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = RoutesClient( - 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.compute_routes in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.compute_routes] = mock_rpc - request = {} - client.compute_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.compute_routes(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_compute_routes_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = RoutesAsyncClient( - 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.compute_routes in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.compute_routes] = mock_rpc - - request = {} - await client.compute_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.compute_routes(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_compute_routes_async(transport: str = 'grpc_asyncio', request_type=routes_service.ComputeRoutesRequest): - client = RoutesAsyncClient( - 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.compute_routes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(routes_service.ComputeRoutesResponse( - )) - response = await client.compute_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = routes_service.ComputeRoutesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, routes_service.ComputeRoutesResponse) - - -@pytest.mark.asyncio -async def test_compute_routes_async_from_dict(): - await test_compute_routes_async(request_type=dict) - - -@pytest.mark.parametrize("request_type", [ - routes_service.ComputeRouteMatrixRequest, - dict, -]) -def test_compute_route_matrix(request_type, transport: str = 'grpc'): - client = RoutesClient( - 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.compute_route_matrix), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = iter([routes_service.RouteMatrixElement()]) - response = client.compute_route_matrix(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = routes_service.ComputeRouteMatrixRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - for message in response: - assert isinstance(message, routes_service.RouteMatrixElement) - - -def test_compute_route_matrix_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 = RoutesClient( - 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 = routes_service.ComputeRouteMatrixRequest( - language_code='language_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.compute_route_matrix), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.compute_route_matrix(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == routes_service.ComputeRouteMatrixRequest( - language_code='language_code_value', - region_code='region_code_value', - ) - -def test_compute_route_matrix_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = RoutesClient( - 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.compute_route_matrix in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.compute_route_matrix] = mock_rpc - request = {} - client.compute_route_matrix(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.compute_route_matrix(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_compute_route_matrix_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = RoutesAsyncClient( - 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.compute_route_matrix in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.compute_route_matrix] = mock_rpc - - request = {} - await client.compute_route_matrix(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.compute_route_matrix(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_compute_route_matrix_async(transport: str = 'grpc_asyncio', request_type=routes_service.ComputeRouteMatrixRequest): - client = RoutesAsyncClient( - 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.compute_route_matrix), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True) - call.return_value.read = mock.AsyncMock(side_effect=[routes_service.RouteMatrixElement()]) - response = await client.compute_route_matrix(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = routes_service.ComputeRouteMatrixRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - message = await response.read() - assert isinstance(message, routes_service.RouteMatrixElement) - - -@pytest.mark.asyncio -async def test_compute_route_matrix_async_from_dict(): - await test_compute_route_matrix_async(request_type=dict) - - -def test_compute_routes_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 = RoutesClient( - 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.compute_routes in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.compute_routes] = mock_rpc - - request = {} - client.compute_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.compute_routes(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_compute_routes_rest_required_fields(request_type=routes_service.ComputeRoutesRequest): - transport_class = transports.RoutesRestTransport - - 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()).compute_routes._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()).compute_routes._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = routes_service.ComputeRoutesResponse() - # 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 = routes_service.ComputeRoutesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.compute_routes(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_compute_routes_rest_unset_required_fields(): - transport = transports.RoutesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.compute_routes._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("origin", "destination", ))) - - -def test_compute_route_matrix_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 = RoutesClient( - 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.compute_route_matrix in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.compute_route_matrix] = mock_rpc - - request = {} - client.compute_route_matrix(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.compute_route_matrix(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_compute_route_matrix_rest_required_fields(request_type=routes_service.ComputeRouteMatrixRequest): - transport_class = transports.RoutesRestTransport - - 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()).compute_route_matrix._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()).compute_route_matrix._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = routes_service.RouteMatrixElement() - # 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 = routes_service.RouteMatrixElement.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - json_return_value = "[{}]".format(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"} - - with mock.patch.object(response_value, 'iter_content') as iter_content: - iter_content.return_value = iter(json_return_value) - response = client.compute_route_matrix(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_compute_route_matrix_rest_unset_required_fields(): - transport = transports.RoutesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.compute_route_matrix._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("origins", "destinations", ))) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.RoutesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.RoutesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RoutesClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.RoutesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = RoutesClient( - 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 = RoutesClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.RoutesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RoutesClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.RoutesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = RoutesClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.RoutesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.RoutesGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.RoutesGrpcTransport, - transports.RoutesGrpcAsyncIOTransport, - transports.RoutesRestTransport, -]) -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 = RoutesClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = RoutesClient( - 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_compute_routes_empty_call_grpc(): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.compute_routes), - '__call__') as call: - call.return_value = routes_service.ComputeRoutesResponse() - client.compute_routes(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = routes_service.ComputeRoutesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_compute_route_matrix_empty_call_grpc(): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.compute_route_matrix), - '__call__') as call: - call.return_value = iter([routes_service.RouteMatrixElement()]) - client.compute_route_matrix(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = routes_service.ComputeRouteMatrixRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = RoutesAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = RoutesAsyncClient( - 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_compute_routes_empty_call_grpc_asyncio(): - client = RoutesAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.compute_routes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(routes_service.ComputeRoutesResponse( - )) - await client.compute_routes(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = routes_service.ComputeRoutesRequest() - - assert args[0] == request_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_compute_route_matrix_empty_call_grpc_asyncio(): - client = RoutesAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.compute_route_matrix), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True) - call.return_value.read = mock.AsyncMock(side_effect=[routes_service.RouteMatrixElement()]) - await client.compute_route_matrix(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = routes_service.ComputeRouteMatrixRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = RoutesClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_compute_routes_rest_bad_request(request_type=routes_service.ComputeRoutesRequest): - client = RoutesClient( - 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.compute_routes(request) - - -@pytest.mark.parametrize("request_type", [ - routes_service.ComputeRoutesRequest, - dict, -]) -def test_compute_routes_rest_call_success(request_type): - client = RoutesClient( - 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 = routes_service.ComputeRoutesResponse( - ) - - # 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 = routes_service.ComputeRoutesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.compute_routes(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, routes_service.ComputeRoutesResponse) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_compute_routes_rest_interceptors(null_interceptor): - transport = transports.RoutesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RoutesRestInterceptor(), - ) - client = RoutesClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RoutesRestInterceptor, "post_compute_routes") as post, \ - mock.patch.object(transports.RoutesRestInterceptor, "pre_compute_routes") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = routes_service.ComputeRoutesRequest.pb(routes_service.ComputeRoutesRequest()) - 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 = routes_service.ComputeRoutesResponse.to_json(routes_service.ComputeRoutesResponse()) - req.return_value.content = return_value - - request = routes_service.ComputeRoutesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = routes_service.ComputeRoutesResponse() - - client.compute_routes(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_compute_route_matrix_rest_bad_request(request_type=routes_service.ComputeRouteMatrixRequest): - client = RoutesClient( - 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.compute_route_matrix(request) - - -@pytest.mark.parametrize("request_type", [ - routes_service.ComputeRouteMatrixRequest, - dict, -]) -def test_compute_route_matrix_rest_call_success(request_type): - client = RoutesClient( - 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 = routes_service.RouteMatrixElement( - origin_index=1279, - destination_index=1817, - condition=routes_service.RouteMatrixElementCondition.ROUTE_EXISTS, - distance_meters=1594, - ) - - # 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 = routes_service.RouteMatrixElement.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - json_return_value = "[{}]".format(json_return_value) - response_value.iter_content = mock.Mock(return_value=iter(json_return_value)) - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.compute_route_matrix(request) - - assert isinstance(response, Iterable) - response = next(response) - - # Establish that the response is the type that we expect. - assert isinstance(response, routes_service.RouteMatrixElement) - assert response.origin_index == 1279 - assert response.destination_index == 1817 - assert response.condition == routes_service.RouteMatrixElementCondition.ROUTE_EXISTS - assert response.distance_meters == 1594 - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_compute_route_matrix_rest_interceptors(null_interceptor): - transport = transports.RoutesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RoutesRestInterceptor(), - ) - client = RoutesClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RoutesRestInterceptor, "post_compute_route_matrix") as post, \ - mock.patch.object(transports.RoutesRestInterceptor, "pre_compute_route_matrix") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = routes_service.ComputeRouteMatrixRequest.pb(routes_service.ComputeRouteMatrixRequest()) - 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 = routes_service.RouteMatrixElement.to_json(routes_service.RouteMatrixElement()) - req.return_value.iter_content = mock.Mock(return_value=iter(return_value)) - - request = routes_service.ComputeRouteMatrixRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = routes_service.RouteMatrixElement() - - client.compute_route_matrix(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - -def test_initialize_client_w_rest(): - client = RoutesClient( - 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_compute_routes_empty_call_rest(): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.compute_routes), - '__call__') as call: - client.compute_routes(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = routes_service.ComputeRoutesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_compute_route_matrix_empty_call_rest(): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.compute_route_matrix), - '__call__') as call: - client.compute_route_matrix(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = routes_service.ComputeRouteMatrixRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.RoutesGrpcTransport, - ) - -def test_routes_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.RoutesTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_routes_base_transport(): - # Instantiate the base transport. - with mock.patch('google.maps.routing_v2.services.routes.transports.RoutesTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.RoutesTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'compute_routes', - 'compute_route_matrix', - ) - 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_routes_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.maps.routing_v2.services.routes.transports.RoutesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.RoutesTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( -), - quota_project_id="octopus", - ) - - -def test_routes_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.maps.routing_v2.services.routes.transports.RoutesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.RoutesTransport() - adc.assert_called_once() - - -def test_routes_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) - RoutesClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.RoutesGrpcTransport, - transports.RoutesGrpcAsyncIOTransport, - ], -) -def test_routes_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=(), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.RoutesGrpcTransport, - transports.RoutesGrpcAsyncIOTransport, - transports.RoutesRestTransport, - ], -) -def test_routes_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.RoutesGrpcTransport, grpc_helpers), - (transports.RoutesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_routes_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( - "routes.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( -), - scopes=["1", "2"], - default_host="routes.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.RoutesGrpcTransport, transports.RoutesGrpcAsyncIOTransport]) -def test_routes_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_routes_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.RoutesRestTransport ( - 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_routes_host_no_port(transport_name): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='routes.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'routes.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://routes.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_routes_host_with_port(transport_name): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='routes.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'routes.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://routes.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_routes_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = RoutesClient( - credentials=creds1, - transport=transport_name, - ) - client2 = RoutesClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.compute_routes._session - session2 = client2.transport.compute_routes._session - assert session1 != session2 - session1 = client1.transport.compute_route_matrix._session - session2 = client2.transport.compute_route_matrix._session - assert session1 != session2 -def test_routes_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.RoutesGrpcTransport( - 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_routes_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.RoutesGrpcAsyncIOTransport( - 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.RoutesGrpcTransport, transports.RoutesGrpcAsyncIOTransport]) -def test_routes_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.RoutesGrpcTransport, transports.RoutesGrpcAsyncIOTransport]) -def test_routes_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_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = RoutesClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = RoutesClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = RoutesClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = RoutesClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = RoutesClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = RoutesClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = RoutesClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = RoutesClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = RoutesClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = RoutesClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = RoutesClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = RoutesClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = RoutesClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = RoutesClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = RoutesClient.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.RoutesTransport, '_prep_wrapped_messages') as prep: - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.RoutesTransport, '_prep_wrapped_messages') as prep: - transport_class = RoutesClient.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 = RoutesClient( - 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 = RoutesAsyncClient( - 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 = RoutesClient( - 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 = RoutesClient( - 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", [ - (RoutesClient, transports.RoutesGrpcTransport), - (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport), -]) -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-maps-solar/v1/.coveragerc b/owl-bot-staging/google-maps-solar/v1/.coveragerc deleted file mode 100644 index ad069738e9cd..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/maps/solar/__init__.py - google/maps/solar/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-maps-solar/v1/.flake8 b/owl-bot-staging/google-maps-solar/v1/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/google-maps-solar/v1/MANIFEST.in b/owl-bot-staging/google-maps-solar/v1/MANIFEST.in deleted file mode 100644 index 3a3118ae37a3..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/maps/solar *.py -recursive-include google/maps/solar_v1 *.py diff --git a/owl-bot-staging/google-maps-solar/v1/README.rst b/owl-bot-staging/google-maps-solar/v1/README.rst deleted file mode 100644 index dc40707ede3b..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Maps Solar 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 Maps Solar 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 diff --git a/owl-bot-staging/google-maps-solar/v1/docs/_static/custom.css b/owl-bot-staging/google-maps-solar/v1/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/docs/_static/custom.css +++ /dev/null @@ -1,3 +0,0 @@ -dl.field-list > dt { - min-width: 100px -} diff --git a/owl-bot-staging/google-maps-solar/v1/docs/conf.py b/owl-bot-staging/google-maps-solar/v1/docs/conf.py deleted file mode 100644 index f01c97e24b0b..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-maps-solar 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("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# 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.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -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-maps-solar" -copyright = u"2023, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# 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 = 'en' - -# 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"] - -# 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 Maps Client Libraries for Python", - "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-maps-solar-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-maps-solar.tex", - u"google-maps-solar 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-maps-solar", - u"Google Maps Solar 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-maps-solar", - u"google-maps-solar Documentation", - author, - "google-maps-solar", - "GAPIC library for Google Maps Solar API", - "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": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", 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-maps-solar/v1/docs/index.rst b/owl-bot-staging/google-maps-solar/v1/docs/index.rst deleted file mode 100644 index ac524abe54c3..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - solar_v1/services_ - solar_v1/types_ diff --git a/owl-bot-staging/google-maps-solar/v1/docs/solar_v1/services_.rst b/owl-bot-staging/google-maps-solar/v1/docs/solar_v1/services_.rst deleted file mode 100644 index e8894bb30331..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/docs/solar_v1/services_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Maps Solar v1 API -===================================== -.. toctree:: - :maxdepth: 2 - - solar diff --git a/owl-bot-staging/google-maps-solar/v1/docs/solar_v1/solar.rst b/owl-bot-staging/google-maps-solar/v1/docs/solar_v1/solar.rst deleted file mode 100644 index d50d0f6cb877..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/docs/solar_v1/solar.rst +++ /dev/null @@ -1,6 +0,0 @@ -Solar ------------------------ - -.. automodule:: google.maps.solar_v1.services.solar - :members: - :inherited-members: diff --git a/owl-bot-staging/google-maps-solar/v1/docs/solar_v1/types_.rst b/owl-bot-staging/google-maps-solar/v1/docs/solar_v1/types_.rst deleted file mode 100644 index 04d6a941fd87..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/docs/solar_v1/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Maps Solar v1 API -================================== - -.. automodule:: google.maps.solar_v1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-maps-solar/v1/google/maps/solar/__init__.py b/owl-bot-staging/google-maps-solar/v1/google/maps/solar/__init__.py deleted file mode 100644 index f715b18cb2e9..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/google/maps/solar/__init__.py +++ /dev/null @@ -1,69 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.solar import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.maps.solar_v1.services.solar.client import SolarClient -from google.maps.solar_v1.services.solar.async_client import SolarAsyncClient - -from google.maps.solar_v1.types.solar_service import BuildingInsights -from google.maps.solar_v1.types.solar_service import CashPurchaseSavings -from google.maps.solar_v1.types.solar_service import DataLayers -from google.maps.solar_v1.types.solar_service import FinancedPurchaseSavings -from google.maps.solar_v1.types.solar_service import FinancialAnalysis -from google.maps.solar_v1.types.solar_service import FinancialDetails -from google.maps.solar_v1.types.solar_service import FindClosestBuildingInsightsRequest -from google.maps.solar_v1.types.solar_service import GetDataLayersRequest -from google.maps.solar_v1.types.solar_service import GetGeoTiffRequest -from google.maps.solar_v1.types.solar_service import LatLngBox -from google.maps.solar_v1.types.solar_service import LeasingSavings -from google.maps.solar_v1.types.solar_service import RoofSegmentSizeAndSunshineStats -from google.maps.solar_v1.types.solar_service import RoofSegmentSummary -from google.maps.solar_v1.types.solar_service import SavingsOverTime -from google.maps.solar_v1.types.solar_service import SizeAndSunshineStats -from google.maps.solar_v1.types.solar_service import SolarPanel -from google.maps.solar_v1.types.solar_service import SolarPanelConfig -from google.maps.solar_v1.types.solar_service import SolarPotential -from google.maps.solar_v1.types.solar_service import DataLayerView -from google.maps.solar_v1.types.solar_service import ImageryQuality -from google.maps.solar_v1.types.solar_service import SolarPanelOrientation - -__all__ = ('SolarClient', - 'SolarAsyncClient', - 'BuildingInsights', - 'CashPurchaseSavings', - 'DataLayers', - 'FinancedPurchaseSavings', - 'FinancialAnalysis', - 'FinancialDetails', - 'FindClosestBuildingInsightsRequest', - 'GetDataLayersRequest', - 'GetGeoTiffRequest', - 'LatLngBox', - 'LeasingSavings', - 'RoofSegmentSizeAndSunshineStats', - 'RoofSegmentSummary', - 'SavingsOverTime', - 'SizeAndSunshineStats', - 'SolarPanel', - 'SolarPanelConfig', - 'SolarPotential', - 'DataLayerView', - 'ImageryQuality', - 'SolarPanelOrientation', -) diff --git a/owl-bot-staging/google-maps-solar/v1/google/maps/solar/gapic_version.py b/owl-bot-staging/google-maps-solar/v1/google/maps/solar/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/google/maps/solar/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-maps-solar/v1/google/maps/solar/py.typed b/owl-bot-staging/google-maps-solar/v1/google/maps/solar/py.typed deleted file mode 100644 index 9203ebe476fb..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/google/maps/solar/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-maps-solar package uses inline types. diff --git a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/__init__.py b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/__init__.py deleted file mode 100644 index 09b279b6c567..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/__init__.py +++ /dev/null @@ -1,70 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.solar_v1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.solar import SolarClient -from .services.solar import SolarAsyncClient - -from .types.solar_service import BuildingInsights -from .types.solar_service import CashPurchaseSavings -from .types.solar_service import DataLayers -from .types.solar_service import FinancedPurchaseSavings -from .types.solar_service import FinancialAnalysis -from .types.solar_service import FinancialDetails -from .types.solar_service import FindClosestBuildingInsightsRequest -from .types.solar_service import GetDataLayersRequest -from .types.solar_service import GetGeoTiffRequest -from .types.solar_service import LatLngBox -from .types.solar_service import LeasingSavings -from .types.solar_service import RoofSegmentSizeAndSunshineStats -from .types.solar_service import RoofSegmentSummary -from .types.solar_service import SavingsOverTime -from .types.solar_service import SizeAndSunshineStats -from .types.solar_service import SolarPanel -from .types.solar_service import SolarPanelConfig -from .types.solar_service import SolarPotential -from .types.solar_service import DataLayerView -from .types.solar_service import ImageryQuality -from .types.solar_service import SolarPanelOrientation - -__all__ = ( - 'SolarAsyncClient', -'BuildingInsights', -'CashPurchaseSavings', -'DataLayerView', -'DataLayers', -'FinancedPurchaseSavings', -'FinancialAnalysis', -'FinancialDetails', -'FindClosestBuildingInsightsRequest', -'GetDataLayersRequest', -'GetGeoTiffRequest', -'ImageryQuality', -'LatLngBox', -'LeasingSavings', -'RoofSegmentSizeAndSunshineStats', -'RoofSegmentSummary', -'SavingsOverTime', -'SizeAndSunshineStats', -'SolarClient', -'SolarPanel', -'SolarPanelConfig', -'SolarPanelOrientation', -'SolarPotential', -) diff --git a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/gapic_metadata.json b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/gapic_metadata.json deleted file mode 100644 index d829bb1e665f..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/gapic_metadata.json +++ /dev/null @@ -1,73 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.maps.solar_v1", - "protoPackage": "google.maps.solar.v1", - "schema": "1.0", - "services": { - "Solar": { - "clients": { - "grpc": { - "libraryClient": "SolarClient", - "rpcs": { - "FindClosestBuildingInsights": { - "methods": [ - "find_closest_building_insights" - ] - }, - "GetDataLayers": { - "methods": [ - "get_data_layers" - ] - }, - "GetGeoTiff": { - "methods": [ - "get_geo_tiff" - ] - } - } - }, - "grpc-async": { - "libraryClient": "SolarAsyncClient", - "rpcs": { - "FindClosestBuildingInsights": { - "methods": [ - "find_closest_building_insights" - ] - }, - "GetDataLayers": { - "methods": [ - "get_data_layers" - ] - }, - "GetGeoTiff": { - "methods": [ - "get_geo_tiff" - ] - } - } - }, - "rest": { - "libraryClient": "SolarClient", - "rpcs": { - "FindClosestBuildingInsights": { - "methods": [ - "find_closest_building_insights" - ] - }, - "GetDataLayers": { - "methods": [ - "get_data_layers" - ] - }, - "GetGeoTiff": { - "methods": [ - "get_geo_tiff" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/gapic_version.py b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-maps-solar/v1/google/maps/solar_v1/py.typed b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/py.typed deleted file mode 100644 index 9203ebe476fb..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-maps-solar package uses inline types. diff --git a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/__init__.py b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-maps-solar/v1/google/maps/solar_v1/services/solar/__init__.py b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/__init__.py deleted file mode 100644 index 860c1815c59b..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 SolarClient -from .async_client import SolarAsyncClient - -__all__ = ( - 'SolarClient', - 'SolarAsyncClient', -) diff --git a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/async_client.py b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/async_client.py deleted file mode 100644 index 2c7eece887bb..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/async_client.py +++ /dev/null @@ -1,549 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.solar_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 - - -try: - OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.maps.solar_v1.types import solar_service -from google.protobuf import any_pb2 # type: ignore -from google.type import date_pb2 # type: ignore -from google.type import latlng_pb2 # type: ignore -from .transports.base import SolarTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import SolarGrpcAsyncIOTransport -from .client import SolarClient - -try: - from google.api_core import client_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 SolarAsyncClient: - """Service definition for the Solar API.""" - - _client: SolarClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = SolarClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = SolarClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = SolarClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = SolarClient._DEFAULT_UNIVERSE - - common_billing_account_path = staticmethod(SolarClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(SolarClient.parse_common_billing_account_path) - common_folder_path = staticmethod(SolarClient.common_folder_path) - parse_common_folder_path = staticmethod(SolarClient.parse_common_folder_path) - common_organization_path = staticmethod(SolarClient.common_organization_path) - parse_common_organization_path = staticmethod(SolarClient.parse_common_organization_path) - common_project_path = staticmethod(SolarClient.common_project_path) - parse_common_project_path = staticmethod(SolarClient.parse_common_project_path) - common_location_path = staticmethod(SolarClient.common_location_path) - parse_common_location_path = staticmethod(SolarClient.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: - SolarAsyncClient: The constructed client. - """ - return SolarClient.from_service_account_info.__func__(SolarAsyncClient, 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: - SolarAsyncClient: The constructed client. - """ - return SolarClient.from_service_account_file.__func__(SolarAsyncClient, 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 SolarClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> SolarTransport: - """Returns the transport used by the client instance. - - Returns: - SolarTransport: 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 = SolarClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, SolarTransport, Callable[..., SolarTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the solar 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,SolarTransport,Callable[..., SolarTransport]]]): - 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 SolarTransport 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 = SolarClient( - 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.maps.solar_v1.SolarAsyncClient`.", - extra = { - "serviceName": "google.maps.solar.v1.Solar", - "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.maps.solar.v1.Solar", - "credentialsType": None, - } - ) - - async def find_closest_building_insights(self, - request: Optional[Union[solar_service.FindClosestBuildingInsightsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> solar_service.BuildingInsights: - r"""Locates the closest building to a query point. Returns an error - with code ``NOT_FOUND`` if there are no buildings within - approximately 50m of the query point. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import solar_v1 - - async def sample_find_closest_building_insights(): - # Create a client - client = solar_v1.SolarAsyncClient() - - # Initialize request argument(s) - request = solar_v1.FindClosestBuildingInsightsRequest( - ) - - # Make the request - response = await client.find_closest_building_insights(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.solar_v1.types.FindClosestBuildingInsightsRequest, dict]]): - The request object. Request message for - ``Solar.FindClosestBuildingInsights``. - 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.maps.solar_v1.types.BuildingInsights: - Response message for Solar.FindClosestBuildingInsights. - Information about the location, dimensions, and solar - potential of a building. - - """ - # 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, solar_service.FindClosestBuildingInsightsRequest): - request = solar_service.FindClosestBuildingInsightsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.find_closest_building_insights] - - # 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_data_layers(self, - request: Optional[Union[solar_service.GetDataLayersRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> solar_service.DataLayers: - r"""Gets solar information for a region surrounding a location. - Returns an error with code ``NOT_FOUND`` if the location is - outside the coverage area. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import solar_v1 - - async def sample_get_data_layers(): - # Create a client - client = solar_v1.SolarAsyncClient() - - # Initialize request argument(s) - request = solar_v1.GetDataLayersRequest( - radius_meters=0.1399, - ) - - # Make the request - response = await client.get_data_layers(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.solar_v1.types.GetDataLayersRequest, dict]]): - The request object. Request message for ``Solar.GetDataLayers``. - 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.maps.solar_v1.types.DataLayers: - Information about the solar potential of a region. The actual data - are contained in a number of GeoTIFF files covering - the requested region, for which this message contains - URLs: Each string in the DataLayers message contains - a URL from which the corresponding GeoTIFF can be - fetched. These URLs are valid for a few hours after - they've been generated. Most of the GeoTIFF files are - at a resolution of 0.1m/pixel, but the monthly flux - file is at 0.5m/pixel, and the hourly shade files are - at 1m/pixel. If a pixel_size_meters value was - specified in the GetDataLayersRequest, then the - minimum resolution in the GeoTIFF files will be that - value. - - """ - # 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, solar_service.GetDataLayersRequest): - request = solar_service.GetDataLayersRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_data_layers] - - # 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_geo_tiff(self, - request: Optional[Union[solar_service.GetGeoTiffRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> httpbody_pb2.HttpBody: - r"""Returns an image by its 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.maps import solar_v1 - - async def sample_get_geo_tiff(): - # Create a client - client = solar_v1.SolarAsyncClient() - - # Initialize request argument(s) - request = solar_v1.GetGeoTiffRequest( - id="id_value", - ) - - # Make the request - response = await client.get_geo_tiff(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.solar_v1.types.GetGeoTiffRequest, dict]]): - The request object. Request message for ``Solar.GetGeoTiff``. - 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.api.httpbody_pb2.HttpBody: - Message that represents an arbitrary HTTP body. It should only be used for - payload formats that can't be represented as JSON, - such as raw binary or an HTML page. - - This message can be used both in streaming and - non-streaming API methods in the request as well as - the response. - - It can be used as a top-level request field, which is - convenient if one wants to extract parameters from - either the URL or HTTP template into the request - fields and also want access to the raw HTTP body. - - Example: - - message GetResourceRequest { - // A unique request id. string request_id = 1; - - // The raw HTTP body is bound to this field. - google.api.HttpBody http_body = 2; - - } - - service ResourceService { - rpc GetResource(GetResourceRequest) - returns (google.api.HttpBody); - - rpc UpdateResource(google.api.HttpBody) - returns (google.protobuf.Empty); - - } - - Example with streaming methods: - - service CaldavService { - rpc GetCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - rpc UpdateCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - } - - Use of this type only changes how the request and - response bodies are handled, all other features will - continue to work unchanged. - - """ - # 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, solar_service.GetGeoTiffRequest): - request = solar_service.GetGeoTiffRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_geo_tiff] - - # 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) -> "SolarAsyncClient": - 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__) - - -__all__ = ( - "SolarAsyncClient", -) diff --git a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/client.py b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/client.py deleted file mode 100644 index 89f5172b8129..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/client.py +++ /dev/null @@ -1,876 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -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.maps.solar_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 - -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.api import httpbody_pb2 # type: ignore -from google.maps.solar_v1.types import solar_service -from google.protobuf import any_pb2 # type: ignore -from google.type import date_pb2 # type: ignore -from google.type import latlng_pb2 # type: ignore -from .transports.base import SolarTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import SolarGrpcTransport -from .transports.grpc_asyncio import SolarGrpcAsyncIOTransport -from .transports.rest import SolarRestTransport - - -class SolarClientMeta(type): - """Metaclass for the Solar 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[SolarTransport]] - _transport_registry["grpc"] = SolarGrpcTransport - _transport_registry["grpc_asyncio"] = SolarGrpcAsyncIOTransport - _transport_registry["rest"] = SolarRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[SolarTransport]: - """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 SolarClient(metaclass=SolarClientMeta): - """Service definition for the Solar 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 = "solar.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "solar.{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: - SolarClient: 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: - SolarClient: 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) -> SolarTransport: - """Returns the transport used by the client instance. - - Returns: - SolarTransport: The transport used by the client - instance. - """ - return self._transport - - @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 = SolarClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = SolarClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = SolarClient._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 = SolarClient._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 - - @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, SolarTransport, Callable[..., SolarTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the solar 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,SolarTransport,Callable[..., SolarTransport]]]): - 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 SolarTransport 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 = SolarClient._read_environment_variables() - self._client_cert_source = SolarClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = SolarClient._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, SolarTransport) - if transport_provided: - # transport is a SolarTransport 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(SolarTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - SolarClient._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[SolarTransport], Callable[..., SolarTransport]] = ( - SolarClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., SolarTransport], 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.maps.solar_v1.SolarClient`.", - extra = { - "serviceName": "google.maps.solar.v1.Solar", - "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.maps.solar.v1.Solar", - "credentialsType": None, - } - ) - - def find_closest_building_insights(self, - request: Optional[Union[solar_service.FindClosestBuildingInsightsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> solar_service.BuildingInsights: - r"""Locates the closest building to a query point. Returns an error - with code ``NOT_FOUND`` if there are no buildings within - approximately 50m of the query point. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import solar_v1 - - def sample_find_closest_building_insights(): - # Create a client - client = solar_v1.SolarClient() - - # Initialize request argument(s) - request = solar_v1.FindClosestBuildingInsightsRequest( - ) - - # Make the request - response = client.find_closest_building_insights(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.solar_v1.types.FindClosestBuildingInsightsRequest, dict]): - The request object. Request message for - ``Solar.FindClosestBuildingInsights``. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.maps.solar_v1.types.BuildingInsights: - Response message for Solar.FindClosestBuildingInsights. - Information about the location, dimensions, and solar - potential of a building. - - """ - # 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, solar_service.FindClosestBuildingInsightsRequest): - request = solar_service.FindClosestBuildingInsightsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.find_closest_building_insights] - - # 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_data_layers(self, - request: Optional[Union[solar_service.GetDataLayersRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> solar_service.DataLayers: - r"""Gets solar information for a region surrounding a location. - Returns an error with code ``NOT_FOUND`` if the location is - outside the coverage area. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import solar_v1 - - def sample_get_data_layers(): - # Create a client - client = solar_v1.SolarClient() - - # Initialize request argument(s) - request = solar_v1.GetDataLayersRequest( - radius_meters=0.1399, - ) - - # Make the request - response = client.get_data_layers(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.solar_v1.types.GetDataLayersRequest, dict]): - The request object. Request message for ``Solar.GetDataLayers``. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.maps.solar_v1.types.DataLayers: - Information about the solar potential of a region. The actual data - are contained in a number of GeoTIFF files covering - the requested region, for which this message contains - URLs: Each string in the DataLayers message contains - a URL from which the corresponding GeoTIFF can be - fetched. These URLs are valid for a few hours after - they've been generated. Most of the GeoTIFF files are - at a resolution of 0.1m/pixel, but the monthly flux - file is at 0.5m/pixel, and the hourly shade files are - at 1m/pixel. If a pixel_size_meters value was - specified in the GetDataLayersRequest, then the - minimum resolution in the GeoTIFF files will be that - value. - - """ - # 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, solar_service.GetDataLayersRequest): - request = solar_service.GetDataLayersRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_data_layers] - - # 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_geo_tiff(self, - request: Optional[Union[solar_service.GetGeoTiffRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> httpbody_pb2.HttpBody: - r"""Returns an image by its 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.maps import solar_v1 - - def sample_get_geo_tiff(): - # Create a client - client = solar_v1.SolarClient() - - # Initialize request argument(s) - request = solar_v1.GetGeoTiffRequest( - id="id_value", - ) - - # Make the request - response = client.get_geo_tiff(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.solar_v1.types.GetGeoTiffRequest, dict]): - The request object. Request message for ``Solar.GetGeoTiff``. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api.httpbody_pb2.HttpBody: - Message that represents an arbitrary HTTP body. It should only be used for - payload formats that can't be represented as JSON, - such as raw binary or an HTML page. - - This message can be used both in streaming and - non-streaming API methods in the request as well as - the response. - - It can be used as a top-level request field, which is - convenient if one wants to extract parameters from - either the URL or HTTP template into the request - fields and also want access to the raw HTTP body. - - Example: - - message GetResourceRequest { - // A unique request id. string request_id = 1; - - // The raw HTTP body is bound to this field. - google.api.HttpBody http_body = 2; - - } - - service ResourceService { - rpc GetResource(GetResourceRequest) - returns (google.api.HttpBody); - - rpc UpdateResource(google.api.HttpBody) - returns (google.protobuf.Empty); - - } - - Example with streaming methods: - - service CaldavService { - rpc GetCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - rpc UpdateCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - } - - Use of this type only changes how the request and - response bodies are handled, all other features will - continue to work unchanged. - - """ - # 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, solar_service.GetGeoTiffRequest): - request = solar_service.GetGeoTiffRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_geo_tiff] - - # 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) -> "SolarClient": - 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__) - - -__all__ = ( - "SolarClient", -) diff --git a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/README.rst b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/README.rst deleted file mode 100644 index 9860e8dc616e..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`SolarTransport` is the ABC for all transports. -- public child `SolarGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `SolarGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseSolarRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `SolarRestTransport` 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-maps-solar/v1/google/maps/solar_v1/services/solar/transports/__init__.py b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/__init__.py deleted file mode 100644 index 65c6bd1fe24b..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 SolarTransport -from .grpc import SolarGrpcTransport -from .grpc_asyncio import SolarGrpcAsyncIOTransport -from .rest import SolarRestTransport -from .rest import SolarRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SolarTransport]] -_transport_registry['grpc'] = SolarGrpcTransport -_transport_registry['grpc_asyncio'] = SolarGrpcAsyncIOTransport -_transport_registry['rest'] = SolarRestTransport - -__all__ = ( - 'SolarTransport', - 'SolarGrpcTransport', - 'SolarGrpcAsyncIOTransport', - 'SolarRestTransport', - 'SolarRestInterceptor', -) diff --git a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/base.py b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/base.py deleted file mode 100644 index 6f94fcccd295..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/base.py +++ /dev/null @@ -1,210 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.maps.solar_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 - -from google.api import httpbody_pb2 # type: ignore -from google.maps.solar_v1.types import solar_service - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class SolarTransport(abc.ABC): - """Abstract transport class for Solar.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'solar.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: 'solar.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to 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_closest_building_insights: gapic_v1.method.wrap_method( - self.find_closest_building_insights, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_data_layers: gapic_v1.method.wrap_method( - self.get_data_layers, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_geo_tiff: gapic_v1.method.wrap_method( - self.get_geo_tiff, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def find_closest_building_insights(self) -> Callable[ - [solar_service.FindClosestBuildingInsightsRequest], - Union[ - solar_service.BuildingInsights, - Awaitable[solar_service.BuildingInsights] - ]]: - raise NotImplementedError() - - @property - def get_data_layers(self) -> Callable[ - [solar_service.GetDataLayersRequest], - Union[ - solar_service.DataLayers, - Awaitable[solar_service.DataLayers] - ]]: - raise NotImplementedError() - - @property - def get_geo_tiff(self) -> Callable[ - [solar_service.GetGeoTiffRequest], - Union[ - httpbody_pb2.HttpBody, - Awaitable[httpbody_pb2.HttpBody] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'SolarTransport', -) diff --git a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/grpc.py b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/grpc.py deleted file mode 100644 index d91cce1af58c..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/grpc.py +++ /dev/null @@ -1,404 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.api import httpbody_pb2 # type: ignore -from google.maps.solar_v1.types import solar_service -from .base import SolarTransport, 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.maps.solar.v1.Solar", - "rpcName": 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.maps.solar.v1.Solar", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class SolarGrpcTransport(SolarTransport): - """gRPC backend transport for Solar. - - Service definition for the Solar 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 = 'solar.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: 'solar.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to 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 = 'solar.googleapis.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_closest_building_insights(self) -> Callable[ - [solar_service.FindClosestBuildingInsightsRequest], - solar_service.BuildingInsights]: - r"""Return a callable for the find closest building insights method over gRPC. - - Locates the closest building to a query point. Returns an error - with code ``NOT_FOUND`` if there are no buildings within - approximately 50m of the query point. - - Returns: - Callable[[~.FindClosestBuildingInsightsRequest], - ~.BuildingInsights]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_closest_building_insights' not in self._stubs: - self._stubs['find_closest_building_insights'] = self._logged_channel.unary_unary( - '/google.maps.solar.v1.Solar/FindClosestBuildingInsights', - request_serializer=solar_service.FindClosestBuildingInsightsRequest.serialize, - response_deserializer=solar_service.BuildingInsights.deserialize, - ) - return self._stubs['find_closest_building_insights'] - - @property - def get_data_layers(self) -> Callable[ - [solar_service.GetDataLayersRequest], - solar_service.DataLayers]: - r"""Return a callable for the get data layers method over gRPC. - - Gets solar information for a region surrounding a location. - Returns an error with code ``NOT_FOUND`` if the location is - outside the coverage area. - - Returns: - Callable[[~.GetDataLayersRequest], - ~.DataLayers]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_data_layers' not in self._stubs: - self._stubs['get_data_layers'] = self._logged_channel.unary_unary( - '/google.maps.solar.v1.Solar/GetDataLayers', - request_serializer=solar_service.GetDataLayersRequest.serialize, - response_deserializer=solar_service.DataLayers.deserialize, - ) - return self._stubs['get_data_layers'] - - @property - def get_geo_tiff(self) -> Callable[ - [solar_service.GetGeoTiffRequest], - httpbody_pb2.HttpBody]: - r"""Return a callable for the get geo tiff method over gRPC. - - Returns an image by its ID. - - Returns: - Callable[[~.GetGeoTiffRequest], - ~.HttpBody]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_geo_tiff' not in self._stubs: - self._stubs['get_geo_tiff'] = self._logged_channel.unary_unary( - '/google.maps.solar.v1.Solar/GetGeoTiff', - request_serializer=solar_service.GetGeoTiffRequest.serialize, - response_deserializer=httpbody_pb2.HttpBody.FromString, - ) - return self._stubs['get_geo_tiff'] - - def close(self): - self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'SolarGrpcTransport', -) diff --git a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/grpc_asyncio.py b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/grpc_asyncio.py deleted file mode 100644 index 1bd9080f8973..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/grpc_asyncio.py +++ /dev/null @@ -1,461 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.api import httpbody_pb2 # type: ignore -from google.maps.solar_v1.types import solar_service -from .base import SolarTransport, DEFAULT_CLIENT_INFO -from .grpc import SolarGrpcTransport - -try: - from google.api_core import client_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.maps.solar.v1.Solar", - "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.maps.solar.v1.Solar", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class SolarGrpcAsyncIOTransport(SolarTransport): - """gRPC AsyncIO backend transport for Solar. - - Service definition for the Solar 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 = 'solar.googleapis.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 = 'solar.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: 'solar.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to 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_closest_building_insights(self) -> Callable[ - [solar_service.FindClosestBuildingInsightsRequest], - Awaitable[solar_service.BuildingInsights]]: - r"""Return a callable for the find closest building insights method over gRPC. - - Locates the closest building to a query point. Returns an error - with code ``NOT_FOUND`` if there are no buildings within - approximately 50m of the query point. - - Returns: - Callable[[~.FindClosestBuildingInsightsRequest], - Awaitable[~.BuildingInsights]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_closest_building_insights' not in self._stubs: - self._stubs['find_closest_building_insights'] = self._logged_channel.unary_unary( - '/google.maps.solar.v1.Solar/FindClosestBuildingInsights', - request_serializer=solar_service.FindClosestBuildingInsightsRequest.serialize, - response_deserializer=solar_service.BuildingInsights.deserialize, - ) - return self._stubs['find_closest_building_insights'] - - @property - def get_data_layers(self) -> Callable[ - [solar_service.GetDataLayersRequest], - Awaitable[solar_service.DataLayers]]: - r"""Return a callable for the get data layers method over gRPC. - - Gets solar information for a region surrounding a location. - Returns an error with code ``NOT_FOUND`` if the location is - outside the coverage area. - - Returns: - Callable[[~.GetDataLayersRequest], - Awaitable[~.DataLayers]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_data_layers' not in self._stubs: - self._stubs['get_data_layers'] = self._logged_channel.unary_unary( - '/google.maps.solar.v1.Solar/GetDataLayers', - request_serializer=solar_service.GetDataLayersRequest.serialize, - response_deserializer=solar_service.DataLayers.deserialize, - ) - return self._stubs['get_data_layers'] - - @property - def get_geo_tiff(self) -> Callable[ - [solar_service.GetGeoTiffRequest], - Awaitable[httpbody_pb2.HttpBody]]: - r"""Return a callable for the get geo tiff method over gRPC. - - Returns an image by its ID. - - Returns: - Callable[[~.GetGeoTiffRequest], - Awaitable[~.HttpBody]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_geo_tiff' not in self._stubs: - self._stubs['get_geo_tiff'] = self._logged_channel.unary_unary( - '/google.maps.solar.v1.Solar/GetGeoTiff', - request_serializer=solar_service.GetGeoTiffRequest.serialize, - response_deserializer=httpbody_pb2.HttpBody.FromString, - ) - return self._stubs['get_geo_tiff'] - - 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_closest_building_insights: self._wrap_method( - self.find_closest_building_insights, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_data_layers: self._wrap_method( - self.get_data_layers, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_geo_tiff: self._wrap_method( - self.get_geo_tiff, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - 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__ = ( - 'SolarGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/rest.py b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/rest.py deleted file mode 100644 index ced1d9a2a090..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/rest.py +++ /dev/null @@ -1,694 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -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.api import httpbody_pb2 # type: ignore -from google.maps.solar_v1.types import solar_service - - -from .rest_base import _BaseSolarRestTransport -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}", -) - - -class SolarRestInterceptor: - """Interceptor for Solar. - - 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 SolarRestTransport. - - .. code-block:: python - class MyCustomSolarInterceptor(SolarRestInterceptor): - def pre_find_closest_building_insights(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_find_closest_building_insights(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_data_layers(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_data_layers(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_geo_tiff(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_geo_tiff(self, response): - logging.log(f"Received response: {response}") - return response - - transport = SolarRestTransport(interceptor=MyCustomSolarInterceptor()) - client = SolarClient(transport=transport) - - - """ - def pre_find_closest_building_insights(self, request: solar_service.FindClosestBuildingInsightsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[solar_service.FindClosestBuildingInsightsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for find_closest_building_insights - - Override in a subclass to manipulate the request or metadata - before they are sent to the Solar server. - """ - return request, metadata - - def post_find_closest_building_insights(self, response: solar_service.BuildingInsights) -> solar_service.BuildingInsights: - """Post-rpc interceptor for find_closest_building_insights - - Override in a subclass to manipulate the response - after it is returned by the Solar server but before - it is returned to user code. - """ - return response - - def pre_get_data_layers(self, request: solar_service.GetDataLayersRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[solar_service.GetDataLayersRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_data_layers - - Override in a subclass to manipulate the request or metadata - before they are sent to the Solar server. - """ - return request, metadata - - def post_get_data_layers(self, response: solar_service.DataLayers) -> solar_service.DataLayers: - """Post-rpc interceptor for get_data_layers - - Override in a subclass to manipulate the response - after it is returned by the Solar server but before - it is returned to user code. - """ - return response - - def pre_get_geo_tiff(self, request: solar_service.GetGeoTiffRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[solar_service.GetGeoTiffRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_geo_tiff - - Override in a subclass to manipulate the request or metadata - before they are sent to the Solar server. - """ - return request, metadata - - def post_get_geo_tiff(self, response: httpbody_pb2.HttpBody) -> httpbody_pb2.HttpBody: - """Post-rpc interceptor for get_geo_tiff - - Override in a subclass to manipulate the response - after it is returned by the Solar server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class SolarRestStub: - _session: AuthorizedSession - _host: str - _interceptor: SolarRestInterceptor - - -class SolarRestTransport(_BaseSolarRestTransport): - """REST backend synchronous transport for Solar. - - Service definition for the Solar 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 = 'solar.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[SolarRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'solar.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to 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 SolarRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _FindClosestBuildingInsights(_BaseSolarRestTransport._BaseFindClosestBuildingInsights, SolarRestStub): - def __hash__(self): - return hash("SolarRestTransport.FindClosestBuildingInsights") - - @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: solar_service.FindClosestBuildingInsightsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> solar_service.BuildingInsights: - r"""Call the find closest building - insights method over HTTP. - - Args: - request (~.solar_service.FindClosestBuildingInsightsRequest): - The request object. Request message for - ``Solar.FindClosestBuildingInsights``. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.solar_service.BuildingInsights: - Response message for - ``Solar.FindClosestBuildingInsights``. Information about - the location, dimensions, and solar potential of a - building. - - """ - - http_options = _BaseSolarRestTransport._BaseFindClosestBuildingInsights._get_http_options() - - request, metadata = self._interceptor.pre_find_closest_building_insights(request, metadata) - transcoded_request = _BaseSolarRestTransport._BaseFindClosestBuildingInsights._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseSolarRestTransport._BaseFindClosestBuildingInsights._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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.maps.solar_v1.SolarClient.FindClosestBuildingInsights", - extra = { - "serviceName": "google.maps.solar.v1.Solar", - "rpcName": "FindClosestBuildingInsights", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = SolarRestTransport._FindClosestBuildingInsights._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 = solar_service.BuildingInsights() - pb_resp = solar_service.BuildingInsights.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_find_closest_building_insights(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = solar_service.BuildingInsights.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.maps.solar_v1.SolarClient.find_closest_building_insights", - extra = { - "serviceName": "google.maps.solar.v1.Solar", - "rpcName": "FindClosestBuildingInsights", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetDataLayers(_BaseSolarRestTransport._BaseGetDataLayers, SolarRestStub): - def __hash__(self): - return hash("SolarRestTransport.GetDataLayers") - - @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: solar_service.GetDataLayersRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> solar_service.DataLayers: - r"""Call the get data layers method over HTTP. - - Args: - request (~.solar_service.GetDataLayersRequest): - The request object. Request message for ``Solar.GetDataLayers``. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.solar_service.DataLayers: - Information about the solar potential of a region. The - actual data are contained in a number of GeoTIFF files - covering the requested region, for which this message - contains URLs: Each string in the ``DataLayers`` message - contains a URL from which the corresponding GeoTIFF can - be fetched. These URLs are valid for a few hours after - they've been generated. Most of the GeoTIFF files are at - a resolution of 0.1m/pixel, but the monthly flux file is - at 0.5m/pixel, and the hourly shade files are at - 1m/pixel. If a ``pixel_size_meters`` value was specified - in the ``GetDataLayersRequest``, then the minimum - resolution in the GeoTIFF files will be that value. - - """ - - http_options = _BaseSolarRestTransport._BaseGetDataLayers._get_http_options() - - request, metadata = self._interceptor.pre_get_data_layers(request, metadata) - transcoded_request = _BaseSolarRestTransport._BaseGetDataLayers._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseSolarRestTransport._BaseGetDataLayers._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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.maps.solar_v1.SolarClient.GetDataLayers", - extra = { - "serviceName": "google.maps.solar.v1.Solar", - "rpcName": "GetDataLayers", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = SolarRestTransport._GetDataLayers._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 = solar_service.DataLayers() - pb_resp = solar_service.DataLayers.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_data_layers(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = solar_service.DataLayers.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.maps.solar_v1.SolarClient.get_data_layers", - extra = { - "serviceName": "google.maps.solar.v1.Solar", - "rpcName": "GetDataLayers", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetGeoTiff(_BaseSolarRestTransport._BaseGetGeoTiff, SolarRestStub): - def __hash__(self): - return hash("SolarRestTransport.GetGeoTiff") - - @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: solar_service.GetGeoTiffRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> httpbody_pb2.HttpBody: - r"""Call the get geo tiff method over HTTP. - - Args: - request (~.solar_service.GetGeoTiffRequest): - The request object. Request message for ``Solar.GetGeoTiff``. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.httpbody_pb2.HttpBody: - Message that represents an arbitrary HTTP body. It - should only be used for payload formats that can't be - represented as JSON, such as raw binary or an HTML page. - - This message can be used both in streaming and - non-streaming API methods in the request as well as the - response. - - It can be used as a top-level request field, which is - convenient if one wants to extract parameters from - either the URL or HTTP template into the request fields - and also want access to the raw HTTP body. - - Example: - - :: - - message GetResourceRequest { - // A unique request id. - string request_id = 1; - - // The raw HTTP body is bound to this field. - google.api.HttpBody http_body = 2; - - } - - service ResourceService { - rpc GetResource(GetResourceRequest) - returns (google.api.HttpBody); - rpc UpdateResource(google.api.HttpBody) - returns (google.protobuf.Empty); - - } - - Example with streaming methods: - - :: - - service CaldavService { - rpc GetCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - rpc UpdateCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - } - - Use of this type only changes how the request and - response bodies are handled, all other features will - continue to work unchanged. - - """ - - http_options = _BaseSolarRestTransport._BaseGetGeoTiff._get_http_options() - - request, metadata = self._interceptor.pre_get_geo_tiff(request, metadata) - transcoded_request = _BaseSolarRestTransport._BaseGetGeoTiff._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseSolarRestTransport._BaseGetGeoTiff._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(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.maps.solar_v1.SolarClient.GetGeoTiff", - extra = { - "serviceName": "google.maps.solar.v1.Solar", - "rpcName": "GetGeoTiff", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = SolarRestTransport._GetGeoTiff._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 = httpbody_pb2.HttpBody() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_geo_tiff(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.maps.solar_v1.SolarClient.get_geo_tiff", - extra = { - "serviceName": "google.maps.solar.v1.Solar", - "rpcName": "GetGeoTiff", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def find_closest_building_insights(self) -> Callable[ - [solar_service.FindClosestBuildingInsightsRequest], - solar_service.BuildingInsights]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._FindClosestBuildingInsights(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_data_layers(self) -> Callable[ - [solar_service.GetDataLayersRequest], - solar_service.DataLayers]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetDataLayers(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_geo_tiff(self) -> Callable[ - [solar_service.GetGeoTiffRequest], - httpbody_pb2.HttpBody]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetGeoTiff(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'SolarRestTransport', -) diff --git a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/rest_base.py b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/rest_base.py deleted file mode 100644 index 7c3b2ee3d17a..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/rest_base.py +++ /dev/null @@ -1,203 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 SolarTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.api import httpbody_pb2 # type: ignore -from google.maps.solar_v1.types import solar_service - - -class _BaseSolarRestTransport(SolarTransport): - """Base REST backend transport for Solar. - - 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 = 'solar.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: 'solar.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 _BaseFindClosestBuildingInsights: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "location" : {}, } - - @classmethod - def _get_unset_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': '/v1/buildingInsights:findClosest', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = solar_service.FindClosestBuildingInsightsRequest.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(_BaseSolarRestTransport._BaseFindClosestBuildingInsights._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetDataLayers: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "location" : {}, "radiusMeters" : 0.0, } - - @classmethod - def _get_unset_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': '/v1/dataLayers:get', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = solar_service.GetDataLayersRequest.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(_BaseSolarRestTransport._BaseGetDataLayers._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetGeoTiff: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "id" : "", } - - @classmethod - def _get_unset_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': '/v1/geoTiff:get', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = solar_service.GetGeoTiffRequest.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(_BaseSolarRestTransport._BaseGetGeoTiff._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseSolarRestTransport', -) diff --git a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/types/__init__.py b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/types/__init__.py deleted file mode 100644 index f0543dfdf183..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/types/__init__.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .solar_service import ( - BuildingInsights, - CashPurchaseSavings, - DataLayers, - FinancedPurchaseSavings, - FinancialAnalysis, - FinancialDetails, - FindClosestBuildingInsightsRequest, - GetDataLayersRequest, - GetGeoTiffRequest, - LatLngBox, - LeasingSavings, - RoofSegmentSizeAndSunshineStats, - RoofSegmentSummary, - SavingsOverTime, - SizeAndSunshineStats, - SolarPanel, - SolarPanelConfig, - SolarPotential, - DataLayerView, - ImageryQuality, - SolarPanelOrientation, -) - -__all__ = ( - 'BuildingInsights', - 'CashPurchaseSavings', - 'DataLayers', - 'FinancedPurchaseSavings', - 'FinancialAnalysis', - 'FinancialDetails', - 'FindClosestBuildingInsightsRequest', - 'GetDataLayersRequest', - 'GetGeoTiffRequest', - 'LatLngBox', - 'LeasingSavings', - 'RoofSegmentSizeAndSunshineStats', - 'RoofSegmentSummary', - 'SavingsOverTime', - 'SizeAndSunshineStats', - 'SolarPanel', - 'SolarPanelConfig', - 'SolarPotential', - 'DataLayerView', - 'ImageryQuality', - 'SolarPanelOrientation', -) diff --git a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/types/solar_service.py b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/types/solar_service.py deleted file mode 100644 index fccb525f1b78..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/types/solar_service.py +++ /dev/null @@ -1,1306 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 date_pb2 # type: ignore -from google.type import latlng_pb2 # type: ignore -from google.type import money_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.solar.v1', - manifest={ - 'DataLayerView', - 'ImageryQuality', - 'SolarPanelOrientation', - 'FindClosestBuildingInsightsRequest', - 'LatLngBox', - 'BuildingInsights', - 'SolarPotential', - 'RoofSegmentSizeAndSunshineStats', - 'SizeAndSunshineStats', - 'SolarPanel', - 'SolarPanelConfig', - 'RoofSegmentSummary', - 'FinancialAnalysis', - 'FinancialDetails', - 'SavingsOverTime', - 'LeasingSavings', - 'CashPurchaseSavings', - 'FinancedPurchaseSavings', - 'GetDataLayersRequest', - 'DataLayers', - 'GetGeoTiffRequest', - }, -) - - -class DataLayerView(proto.Enum): - r"""What subset of the solar information to return. - - Values: - DATA_LAYER_VIEW_UNSPECIFIED (0): - Equivalent to FULL. - DSM_LAYER (1): - Get the DSM only. - IMAGERY_LAYERS (2): - Get the DSM, RGB, and mask. - IMAGERY_AND_ANNUAL_FLUX_LAYERS (3): - Get the DSM, RGB, mask, and annual flux. - IMAGERY_AND_ALL_FLUX_LAYERS (4): - Get the DSM, RGB, mask, annual flux, and - monthly flux. - FULL_LAYERS (5): - Get all data. - """ - DATA_LAYER_VIEW_UNSPECIFIED = 0 - DSM_LAYER = 1 - IMAGERY_LAYERS = 2 - IMAGERY_AND_ANNUAL_FLUX_LAYERS = 3 - IMAGERY_AND_ALL_FLUX_LAYERS = 4 - FULL_LAYERS = 5 - - -class ImageryQuality(proto.Enum): - r"""The quality of the imagery used to compute some API result. - - Note: Regardless of imagery quality level, DSM outputs always - have a resolution of 0.1 m/pixel, monthly flux outputs always - have a resolution of 0.5 m/pixel, and hourly shade outputs - always have a resolution of 1 m/pixel. - - Values: - IMAGERY_QUALITY_UNSPECIFIED (0): - No quality is known. - HIGH (1): - The underlying imagery and DSM data were - processed at 0.1 m/pixel. - MEDIUM (2): - The underlying imagery and DSM data were - processed at 0.25 m/pixel. - LOW (3): - The underlying imagery and DSM data were - processed at 0.5 m/pixel. - """ - IMAGERY_QUALITY_UNSPECIFIED = 0 - HIGH = 1 - MEDIUM = 2 - LOW = 3 - - -class SolarPanelOrientation(proto.Enum): - r"""The orientation of a solar panel. This must be interpreted - relative to the azimuth of the roof segment that the panel is - placed on. - - Values: - SOLAR_PANEL_ORIENTATION_UNSPECIFIED (0): - No panel orientation is known. - LANDSCAPE (1): - A ``LANDSCAPE`` panel has its long edge perpendicular to the - azimuth direction of the roof segment that it is placed on. - PORTRAIT (2): - A ``PORTRAIT`` panel has its long edge parallel to the - azimuth direction of the roof segment that it is placed on. - """ - SOLAR_PANEL_ORIENTATION_UNSPECIFIED = 0 - LANDSCAPE = 1 - PORTRAIT = 2 - - -class FindClosestBuildingInsightsRequest(proto.Message): - r"""Request message for ``Solar.FindClosestBuildingInsights``. - - Attributes: - location (google.type.latlng_pb2.LatLng): - Required. The longitude and latitude from - which the API looks for the nearest known - building. - required_quality (google.maps.solar_v1.types.ImageryQuality): - Optional. The minimum quality level allowed - in the results. No result with lower quality - than this will be returned. Not specifying this - is equivalent to restricting to HIGH quality - only. - exact_quality_required (bool): - Optional. Whether to require exact quality of the imagery. - If set to false, the ``required_quality`` field is - interpreted as the minimum required quality, such that HIGH - quality imagery may be returned when ``required_quality`` is - set to MEDIUM. If set to true, ``required_quality`` is - interpreted as the exact required quality and only - ``MEDIUM`` quality imagery is returned if - ``required_quality`` is set to ``MEDIUM``. - """ - - location: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=1, - message=latlng_pb2.LatLng, - ) - required_quality: 'ImageryQuality' = proto.Field( - proto.ENUM, - number=3, - enum='ImageryQuality', - ) - exact_quality_required: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class LatLngBox(proto.Message): - r"""A bounding box in lat/lng coordinates. - - Attributes: - sw (google.type.latlng_pb2.LatLng): - The southwest corner of the box. - ne (google.type.latlng_pb2.LatLng): - The northeast corner of the box. - """ - - sw: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=1, - message=latlng_pb2.LatLng, - ) - ne: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=2, - message=latlng_pb2.LatLng, - ) - - -class BuildingInsights(proto.Message): - r"""Response message for ``Solar.FindClosestBuildingInsights``. - Information about the location, dimensions, and solar potential of a - building. - - Attributes: - name (str): - The resource name for the building, of the format - ``building/``. - center (google.type.latlng_pb2.LatLng): - A point near the center of the building. - bounding_box (google.maps.solar_v1.types.LatLngBox): - The bounding box of the building. - imagery_date (google.type.date_pb2.Date): - Date that the underlying imagery was - acquired. This is approximate. - imagery_processed_date (google.type.date_pb2.Date): - When processing was completed on this - imagery. - postal_code (str): - Postal code (e.g., US zip code) this building - is contained by. - administrative_area (str): - Administrative area 1 (e.g., in the US, the - state) that contains this building. For example, - in the US, the abbreviation might be "MA" or - "CA.". - statistical_area (str): - Statistical area (e.g., US census tract) this - building is in. - region_code (str): - Region code for the country (or region) this - building is in. - solar_potential (google.maps.solar_v1.types.SolarPotential): - Solar potential of the building. - imagery_quality (google.maps.solar_v1.types.ImageryQuality): - The quality of the imagery used to compute - the data for this building. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - center: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=2, - message=latlng_pb2.LatLng, - ) - bounding_box: 'LatLngBox' = proto.Field( - proto.MESSAGE, - number=9, - message='LatLngBox', - ) - imagery_date: date_pb2.Date = proto.Field( - proto.MESSAGE, - number=3, - message=date_pb2.Date, - ) - imagery_processed_date: date_pb2.Date = proto.Field( - proto.MESSAGE, - number=11, - message=date_pb2.Date, - ) - postal_code: str = proto.Field( - proto.STRING, - number=4, - ) - administrative_area: str = proto.Field( - proto.STRING, - number=5, - ) - statistical_area: str = proto.Field( - proto.STRING, - number=6, - ) - region_code: str = proto.Field( - proto.STRING, - number=7, - ) - solar_potential: 'SolarPotential' = proto.Field( - proto.MESSAGE, - number=8, - message='SolarPotential', - ) - imagery_quality: 'ImageryQuality' = proto.Field( - proto.ENUM, - number=10, - enum='ImageryQuality', - ) - - -class SolarPotential(proto.Message): - r"""Information about the solar potential of a building. A number of - fields in this are defined in terms of "panels". The fields - [panel_capacity_watts] - [google.maps.solar.v1.SolarPotential.panel_capacity_watts], - [panel_height_meters] - [google.maps.solar.v1.SolarPotential.panel_height_meters], and - [panel_width_meters] - [google.maps.solar.v1.SolarPotential.panel_width_meters] describe - the parameters of the model of panel used in these calculations. - - Attributes: - max_array_panels_count (int): - Size of the maximum array - that is, the - maximum number of panels that can fit on the - roof. - panel_capacity_watts (float): - Capacity, in watts, of the panel used in the - calculations. - panel_height_meters (float): - Height, in meters in portrait orientation, of - the panel used in the calculations. - panel_width_meters (float): - Width, in meters in portrait orientation, of - the panel used in the calculations. - panel_lifetime_years (int): - The expected lifetime, in years, of the solar - panels. This is used in the financial - calculations. - max_array_area_meters2 (float): - Size, in square meters, of the maximum array. - max_sunshine_hours_per_year (float): - Maximum number of sunshine hours received per - year, by any point on the roof. Sunshine hours - are a measure of the total amount of insolation - (energy) received per year. 1 sunshine hour = 1 - kWh per kW (where kW refers to kW of capacity - under Standard Testing Conditions). - carbon_offset_factor_kg_per_mwh (float): - Equivalent amount of CO2 produced per MWh of - grid electricity. This is a measure of the - carbon intensity of grid electricity displaced - by solar electricity. - whole_roof_stats (google.maps.solar_v1.types.SizeAndSunshineStats): - Total size and sunlight quantiles for the part of the roof - that was assigned to some roof segment. Despite the name, - this may not include the entire building. See - [building_stats] - [google.maps.solar.v1.SolarPotential.building_stats]. - building_stats (google.maps.solar_v1.types.SizeAndSunshineStats): - Size and sunlight quantiles for the entire building, - including parts of the roof that were not assigned to some - roof segment. Because the orientations of these parts are - not well characterised, the roof area estimate is - unreliable, but the ground area estimate is reliable. It may - be that a more reliable whole building roof area can be - obtained by scaling the roof area from [whole_roof_stats] - [google.maps.solar.v1.SolarPotential.whole_roof_stats] by - the ratio of the ground areas of ``building_stats`` and - ``whole_roof_stats``. - roof_segment_stats (MutableSequence[google.maps.solar_v1.types.RoofSegmentSizeAndSunshineStats]): - Size and sunlight quantiles for each roof - segment. - solar_panels (MutableSequence[google.maps.solar_v1.types.SolarPanel]): - Each [SolarPanel] [google.maps.solar.v1.SolarPanel] - describes a single solar panel. They are listed in the order - that the panel layout algorithm placed this. This is - usually, though not always, in decreasing order of annual - energy production. - solar_panel_configs (MutableSequence[google.maps.solar_v1.types.SolarPanelConfig]): - Each [SolarPanelConfig] - [google.maps.solar.v1.SolarPanelConfig] describes a - different arrangement of solar panels on the roof. They are - in order of increasing number of panels. The - ``SolarPanelConfig`` with [panels_count] - [google.maps.solar.v1.SolarPanelConfig.panels_count]=N is - based on the first N panels in the ``solar_panels`` list. - This field is only populated if at least 4 panels can fit on - a roof. - financial_analyses (MutableSequence[google.maps.solar_v1.types.FinancialAnalysis]): - A [FinancialAnalysis] - [google.maps.solar.v1.FinancialAnalysis] gives the savings - from going solar assuming a given monthly bill and a given - electricity provider. They are in order of increasing order - of monthly bill amount. This field will be empty for - buildings in areas for which the Solar API does not have - enough information to perform financial computations. - """ - - max_array_panels_count: int = proto.Field( - proto.INT32, - number=1, - ) - panel_capacity_watts: float = proto.Field( - proto.FLOAT, - number=9, - ) - panel_height_meters: float = proto.Field( - proto.FLOAT, - number=10, - ) - panel_width_meters: float = proto.Field( - proto.FLOAT, - number=11, - ) - panel_lifetime_years: int = proto.Field( - proto.INT32, - number=12, - ) - max_array_area_meters2: float = proto.Field( - proto.FLOAT, - number=2, - ) - max_sunshine_hours_per_year: float = proto.Field( - proto.FLOAT, - number=3, - ) - carbon_offset_factor_kg_per_mwh: float = proto.Field( - proto.FLOAT, - number=4, - ) - whole_roof_stats: 'SizeAndSunshineStats' = proto.Field( - proto.MESSAGE, - number=5, - message='SizeAndSunshineStats', - ) - building_stats: 'SizeAndSunshineStats' = proto.Field( - proto.MESSAGE, - number=13, - message='SizeAndSunshineStats', - ) - roof_segment_stats: MutableSequence['RoofSegmentSizeAndSunshineStats'] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message='RoofSegmentSizeAndSunshineStats', - ) - solar_panels: MutableSequence['SolarPanel'] = proto.RepeatedField( - proto.MESSAGE, - number=14, - message='SolarPanel', - ) - solar_panel_configs: MutableSequence['SolarPanelConfig'] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message='SolarPanelConfig', - ) - financial_analyses: MutableSequence['FinancialAnalysis'] = proto.RepeatedField( - proto.MESSAGE, - number=8, - message='FinancialAnalysis', - ) - - -class RoofSegmentSizeAndSunshineStats(proto.Message): - r"""Information about the size and sunniness quantiles of a roof - segment. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - pitch_degrees (float): - Angle of the roof segment relative to the - theoretical ground plane. 0 = parallel to the - ground, 90 = perpendicular to the ground. - - This field is a member of `oneof`_ ``_pitch_degrees``. - azimuth_degrees (float): - Compass direction the roof segment is pointing in. 0 = - North, 90 = East, 180 = South. For a "flat" roof segment - (``pitch_degrees`` very near 0), azimuth is not well - defined, so for consistency, we define it arbitrarily to be - 0 (North). - - This field is a member of `oneof`_ ``_azimuth_degrees``. - stats (google.maps.solar_v1.types.SizeAndSunshineStats): - Total size and sunlight quantiles for the - roof segment. - center (google.type.latlng_pb2.LatLng): - A point near the center of the roof segment. - bounding_box (google.maps.solar_v1.types.LatLngBox): - The bounding box of the roof segment. - plane_height_at_center_meters (float): - The height of the roof segment plane, in meters above sea - level, at the point designated by ``center``. Together with - the pitch, azimuth, and center location, this fully defines - the roof segment plane. - - This field is a member of `oneof`_ ``_plane_height_at_center_meters``. - """ - - pitch_degrees: float = proto.Field( - proto.FLOAT, - number=1, - optional=True, - ) - azimuth_degrees: float = proto.Field( - proto.FLOAT, - number=2, - optional=True, - ) - stats: 'SizeAndSunshineStats' = proto.Field( - proto.MESSAGE, - number=3, - message='SizeAndSunshineStats', - ) - center: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=4, - message=latlng_pb2.LatLng, - ) - bounding_box: 'LatLngBox' = proto.Field( - proto.MESSAGE, - number=5, - message='LatLngBox', - ) - plane_height_at_center_meters: float = proto.Field( - proto.FLOAT, - number=6, - optional=True, - ) - - -class SizeAndSunshineStats(proto.Message): - r"""Size and sunniness quantiles of a roof, or part of a roof. - - Attributes: - area_meters2 (float): - The area of the roof or roof segment, in m^2. - This is the roof area (accounting for tilt), not - the ground footprint area. - sunshine_quantiles (MutableSequence[float]): - Quantiles of the pointwise sunniness across the area. If - there are N values here, this represents the (N-1)-iles. For - example, if there are 5 values, then they would be the - quartiles (min, 25%, 50%, 75%, max). Values are in annual - kWh/kW like [max_sunshine_hours_per_year] - [google.maps.solar.v1.SolarPotential.max_sunshine_hours_per_year]. - ground_area_meters2 (float): - The ground footprint area covered by the roof - or roof segment, in m^2. - """ - - area_meters2: float = proto.Field( - proto.FLOAT, - number=1, - ) - sunshine_quantiles: MutableSequence[float] = proto.RepeatedField( - proto.FLOAT, - number=2, - ) - ground_area_meters2: float = proto.Field( - proto.FLOAT, - number=3, - ) - - -class SolarPanel(proto.Message): - r"""SolarPanel describes the position, orientation, and production of a - single solar panel. See the [panel_height_meters] - [google.maps.solar.v1.SolarPotential.panel_height_meters], - [panel_width_meters] - [google.maps.solar.v1.SolarPotential.panel_width_meters], and - [panel_capacity_watts] - [google.maps.solar.v1.SolarPotential.panel_capacity_watts] fields in - [SolarPotential] [google.maps.solar.v1.SolarPotential] for - information on the parameters of the panel. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - center (google.type.latlng_pb2.LatLng): - The centre of the panel. - orientation (google.maps.solar_v1.types.SolarPanelOrientation): - The orientation of the panel. - yearly_energy_dc_kwh (float): - How much sunlight energy this layout captures - over the course of a year, in DC kWh. - segment_index (int): - Index in [roof_segment_stats] - [google.maps.solar.v1.SolarPotential.roof_segment_stats] of - the ``RoofSegmentSizeAndSunshineStats`` which corresponds to - the roof segment that this panel is placed on. - - This field is a member of `oneof`_ ``_segment_index``. - """ - - center: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=1, - message=latlng_pb2.LatLng, - ) - orientation: 'SolarPanelOrientation' = proto.Field( - proto.ENUM, - number=2, - enum='SolarPanelOrientation', - ) - yearly_energy_dc_kwh: float = proto.Field( - proto.FLOAT, - number=3, - ) - segment_index: int = proto.Field( - proto.INT32, - number=4, - optional=True, - ) - - -class SolarPanelConfig(proto.Message): - r"""SolarPanelConfig describes a particular placement of solar - panels on the roof. - - Attributes: - panels_count (int): - Total number of panels. Note that this is redundant to (the - sum of) the corresponding fields in [roof_segment_summaries] - [google.maps.solar.v1.SolarPanelConfig.roof_segment_summaries]. - yearly_energy_dc_kwh (float): - How much sunlight energy this layout captures - over the course of a year, in DC kWh, assuming - the panels described above. - roof_segment_summaries (MutableSequence[google.maps.solar_v1.types.RoofSegmentSummary]): - Information about the production of each roof segment that - is carrying at least one panel in this layout. - ``roof_segment_summaries[i]`` describes the i-th roof - segment, including its size, expected production and - orientation. - """ - - panels_count: int = proto.Field( - proto.INT32, - number=1, - ) - yearly_energy_dc_kwh: float = proto.Field( - proto.FLOAT, - number=2, - ) - roof_segment_summaries: MutableSequence['RoofSegmentSummary'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='RoofSegmentSummary', - ) - - -class RoofSegmentSummary(proto.Message): - r"""Information about a roof segment on the building, with some - number of panels placed on it. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - pitch_degrees (float): - Angle of the roof segment relative to the - theoretical ground plane. 0 = parallel to the - ground, 90 = perpendicular to the ground. - - This field is a member of `oneof`_ ``_pitch_degrees``. - azimuth_degrees (float): - Compass direction the roof segment is pointing in. 0 = - North, 90 = East, 180 = South. For a "flat" roof segment - (``pitch_degrees`` very near 0), azimuth is not well - defined, so for consistency, we define it arbitrarily to be - 0 (North). - - This field is a member of `oneof`_ ``_azimuth_degrees``. - panels_count (int): - The total number of panels on this segment. - yearly_energy_dc_kwh (float): - How much sunlight energy this part of the - layout captures over the course of a year, in DC - kWh, assuming the panels described above. - segment_index (int): - Index in [roof_segment_stats] - [google.maps.solar.v1.SolarPotential.roof_segment_stats] of - the corresponding ``RoofSegmentSizeAndSunshineStats``. - - This field is a member of `oneof`_ ``_segment_index``. - """ - - pitch_degrees: float = proto.Field( - proto.FLOAT, - number=2, - optional=True, - ) - azimuth_degrees: float = proto.Field( - proto.FLOAT, - number=3, - optional=True, - ) - panels_count: int = proto.Field( - proto.INT32, - number=7, - ) - yearly_energy_dc_kwh: float = proto.Field( - proto.FLOAT, - number=8, - ) - segment_index: int = proto.Field( - proto.INT32, - number=9, - optional=True, - ) - - -class FinancialAnalysis(proto.Message): - r"""Analysis of the cost and benefits of the optimum solar layout - for a particular electric bill size. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - monthly_bill (google.type.money_pb2.Money): - The monthly electric bill this analysis - assumes. - default_bill (bool): - Whether this is the bill size selected to be the default - bill for the area this building is in. Exactly one - ``FinancialAnalysis`` in ``BuildingSolarPotential`` should - have ``default_bill`` set. - average_kwh_per_month (float): - How much electricity the house uses in an - average month, based on the bill size and the - local electricity rates. - panel_config_index (int): - Index in [solar_panel_configs] - [google.maps.solar.v1.SolarPotential.solar_panel_configs] of - the optimum solar layout for this bill size. This can be -1 - indicating that there is no layout. In this case, the - remaining submessages will be omitted. - - This field is a member of `oneof`_ ``_panel_config_index``. - financial_details (google.maps.solar_v1.types.FinancialDetails): - Financial information that applies regardless - of the financing method used. - leasing_savings (google.maps.solar_v1.types.LeasingSavings): - Cost and benefit of leasing the solar panels. - cash_purchase_savings (google.maps.solar_v1.types.CashPurchaseSavings): - Cost and benefit of buying the solar panels - with cash. - financed_purchase_savings (google.maps.solar_v1.types.FinancedPurchaseSavings): - Cost and benefit of buying the solar panels - by financing the purchase. - """ - - monthly_bill: money_pb2.Money = proto.Field( - proto.MESSAGE, - number=3, - message=money_pb2.Money, - ) - default_bill: bool = proto.Field( - proto.BOOL, - number=4, - ) - average_kwh_per_month: float = proto.Field( - proto.FLOAT, - number=5, - ) - panel_config_index: int = proto.Field( - proto.INT32, - number=6, - optional=True, - ) - financial_details: 'FinancialDetails' = proto.Field( - proto.MESSAGE, - number=7, - message='FinancialDetails', - ) - leasing_savings: 'LeasingSavings' = proto.Field( - proto.MESSAGE, - number=8, - message='LeasingSavings', - ) - cash_purchase_savings: 'CashPurchaseSavings' = proto.Field( - proto.MESSAGE, - number=9, - message='CashPurchaseSavings', - ) - financed_purchase_savings: 'FinancedPurchaseSavings' = proto.Field( - proto.MESSAGE, - number=10, - message='FinancedPurchaseSavings', - ) - - -class FinancialDetails(proto.Message): - r"""Details of a financial analysis. Some of these details are already - stored at higher levels (e.g., out of pocket cost). Total money - amounts are over a lifetime period defined by the - [panel_lifetime_years] - [google.maps.solar.v1.SolarPotential.panel_lifetime_years] field in - [SolarPotential] [google.maps.solar.v1.SolarPotential]. Note: The - out of pocket cost of purchasing the panels is given in the - [out_of_pocket_cost] - [google.maps.solar.v1.CashPurchaseSavings.out_of_pocket_cost] field - in [CashPurchaseSavings] [google.maps.solar.v1.CashPurchaseSavings]. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - initial_ac_kwh_per_year (float): - How many AC kWh we think the solar panels - will generate in their first year. - remaining_lifetime_utility_bill (google.type.money_pb2.Money): - Utility bill for electricity not produced by - solar, for the lifetime of the panels. - federal_incentive (google.type.money_pb2.Money): - Amount of money available from federal - incentives; this applies if the user buys (with - or without a loan) the panels. - state_incentive (google.type.money_pb2.Money): - Amount of money available from state - incentives; this applies if the user buys (with - or without a loan) the panels. - utility_incentive (google.type.money_pb2.Money): - Amount of money available from utility - incentives; this applies if the user buys (with - or without a loan) the panels. - lifetime_srec_total (google.type.money_pb2.Money): - Amount of money the user will receive from - Solar Renewable Energy Credits over the panel - lifetime; this applies if the user buys (with or - without a loan) the panels. - cost_of_electricity_without_solar (google.type.money_pb2.Money): - Total cost of electricity the user would have - paid over the lifetime period if they didn't - install solar. - net_metering_allowed (bool): - Whether net metering is allowed. - solar_percentage (float): - Percentage (0-100) of the user's power - supplied by solar. Valid for the first year but - approximately correct for future years. - - This field is a member of `oneof`_ ``_solar_percentage``. - percentage_exported_to_grid (float): - The percentage (0-100) of solar electricity - production we assumed was exported to the grid, - based on the first quarter of production. This - affects the calculations if net metering is not - allowed. - - This field is a member of `oneof`_ ``_percentage_exported_to_grid``. - """ - - initial_ac_kwh_per_year: float = proto.Field( - proto.FLOAT, - number=1, - ) - remaining_lifetime_utility_bill: money_pb2.Money = proto.Field( - proto.MESSAGE, - number=2, - message=money_pb2.Money, - ) - federal_incentive: money_pb2.Money = proto.Field( - proto.MESSAGE, - number=3, - message=money_pb2.Money, - ) - state_incentive: money_pb2.Money = proto.Field( - proto.MESSAGE, - number=4, - message=money_pb2.Money, - ) - utility_incentive: money_pb2.Money = proto.Field( - proto.MESSAGE, - number=5, - message=money_pb2.Money, - ) - lifetime_srec_total: money_pb2.Money = proto.Field( - proto.MESSAGE, - number=6, - message=money_pb2.Money, - ) - cost_of_electricity_without_solar: money_pb2.Money = proto.Field( - proto.MESSAGE, - number=7, - message=money_pb2.Money, - ) - net_metering_allowed: bool = proto.Field( - proto.BOOL, - number=8, - ) - solar_percentage: float = proto.Field( - proto.FLOAT, - number=9, - optional=True, - ) - percentage_exported_to_grid: float = proto.Field( - proto.FLOAT, - number=10, - optional=True, - ) - - -class SavingsOverTime(proto.Message): - r"""Financial information that's shared between different - financing methods. - - Attributes: - savings_year1 (google.type.money_pb2.Money): - Savings in the first year after panel - installation. - savings_year20 (google.type.money_pb2.Money): - Savings in the first twenty years after panel - installation. - present_value_of_savings_year20 (google.type.money_pb2.Money): - Using the assumed discount rate, what is the - present value of the cumulative 20-year savings? - savings_lifetime (google.type.money_pb2.Money): - Savings in the entire panel lifetime. - present_value_of_savings_lifetime (google.type.money_pb2.Money): - Using the assumed discount rate, what is the - present value of the cumulative lifetime - savings? - financially_viable (bool): - Indicates whether this scenario is - financially viable. Will be false for scenarios - with poor financial viability (e.g., - money-losing). - """ - - savings_year1: money_pb2.Money = proto.Field( - proto.MESSAGE, - number=1, - message=money_pb2.Money, - ) - savings_year20: money_pb2.Money = proto.Field( - proto.MESSAGE, - number=2, - message=money_pb2.Money, - ) - present_value_of_savings_year20: money_pb2.Money = proto.Field( - proto.MESSAGE, - number=3, - message=money_pb2.Money, - ) - savings_lifetime: money_pb2.Money = proto.Field( - proto.MESSAGE, - number=5, - message=money_pb2.Money, - ) - present_value_of_savings_lifetime: money_pb2.Money = proto.Field( - proto.MESSAGE, - number=6, - message=money_pb2.Money, - ) - financially_viable: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class LeasingSavings(proto.Message): - r"""Cost and benefit of leasing a particular configuration of - solar panels with a particular electricity usage. - - Attributes: - leases_allowed (bool): - Whether leases are allowed in this - juristiction (leases are not allowed in some - states). If this field is false, then the values - in this message should probably be ignored. - leases_supported (bool): - Whether leases are supported in this juristiction by the - financial calculation engine. If this field is false, then - the values in this message should probably be ignored. This - is independent of ``leases_allowed``: in some areas leases - are allowed, but under conditions that aren't handled by the - financial models. - annual_leasing_cost (google.type.money_pb2.Money): - Estimated annual leasing cost. - savings (google.maps.solar_v1.types.SavingsOverTime): - How much is saved (or not) over the lifetime - period. - """ - - leases_allowed: bool = proto.Field( - proto.BOOL, - number=1, - ) - leases_supported: bool = proto.Field( - proto.BOOL, - number=2, - ) - annual_leasing_cost: money_pb2.Money = proto.Field( - proto.MESSAGE, - number=3, - message=money_pb2.Money, - ) - savings: 'SavingsOverTime' = proto.Field( - proto.MESSAGE, - number=4, - message='SavingsOverTime', - ) - - -class CashPurchaseSavings(proto.Message): - r"""Cost and benefit of an outright purchase of a particular - configuration of solar panels with a particular electricity - usage. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - out_of_pocket_cost (google.type.money_pb2.Money): - Initial cost before tax incentives: the amount that must be - paid out-of-pocket. Contrast with ``upfront_cost``, which is - after tax incentives. - upfront_cost (google.type.money_pb2.Money): - Initial cost after tax incentives: it's the amount that must - be paid during first year. Contrast with - ``out_of_pocket_cost``, which is before tax incentives. - rebate_value (google.type.money_pb2.Money): - The value of all tax rebates. - payback_years (float): - Number of years until payback occurs. A - negative value means payback never occurs within - the lifetime period. - - This field is a member of `oneof`_ ``_payback_years``. - savings (google.maps.solar_v1.types.SavingsOverTime): - How much is saved (or not) over the lifetime - period. - """ - - out_of_pocket_cost: money_pb2.Money = proto.Field( - proto.MESSAGE, - number=1, - message=money_pb2.Money, - ) - upfront_cost: money_pb2.Money = proto.Field( - proto.MESSAGE, - number=2, - message=money_pb2.Money, - ) - rebate_value: money_pb2.Money = proto.Field( - proto.MESSAGE, - number=3, - message=money_pb2.Money, - ) - payback_years: float = proto.Field( - proto.FLOAT, - number=4, - optional=True, - ) - savings: 'SavingsOverTime' = proto.Field( - proto.MESSAGE, - number=5, - message='SavingsOverTime', - ) - - -class FinancedPurchaseSavings(proto.Message): - r"""Cost and benefit of using a loan to buy a particular - configuration of solar panels with a particular electricity - usage. - - Attributes: - annual_loan_payment (google.type.money_pb2.Money): - Annual loan payments. - rebate_value (google.type.money_pb2.Money): - The value of all tax rebates (including - Federal Investment Tax Credit (ITC)). - loan_interest_rate (float): - The interest rate on loans assumed in this - set of calculations. - savings (google.maps.solar_v1.types.SavingsOverTime): - How much is saved (or not) over the lifetime - period. - """ - - annual_loan_payment: money_pb2.Money = proto.Field( - proto.MESSAGE, - number=1, - message=money_pb2.Money, - ) - rebate_value: money_pb2.Money = proto.Field( - proto.MESSAGE, - number=2, - message=money_pb2.Money, - ) - loan_interest_rate: float = proto.Field( - proto.FLOAT, - number=3, - ) - savings: 'SavingsOverTime' = proto.Field( - proto.MESSAGE, - number=4, - message='SavingsOverTime', - ) - - -class GetDataLayersRequest(proto.Message): - r"""Request message for ``Solar.GetDataLayers``. - - Attributes: - location (google.type.latlng_pb2.LatLng): - Required. The longitude and latitude for the - center of the region to get data for. - radius_meters (float): - Required. The radius, in meters, defining the region - surrounding that centre point for which data should be - returned. The limitations on this value are: - - - Any value up to 100m can always be specified. - - Values over 100m can be specified, as long as - ``radius_meters`` <= ``pixel_size_meters * 1000``. - - However, for values over 175m, the ``DataLayerView`` in - the request must not include monthly flux or hourly - shade. - view (google.maps.solar_v1.types.DataLayerView): - Optional. The desired subset of the data to - return. - required_quality (google.maps.solar_v1.types.ImageryQuality): - Optional. The minimum quality level allowed - in the results. No result with lower quality - than this will be returned. Not specifying this - is equivalent to restricting to HIGH quality - only. - pixel_size_meters (float): - Optional. The minimum scale, in meters per pixel, of the - data to return. Values of 0.1 (the default, if this field is - not set explicitly), 0.25, 0.5, and 1.0 are supported. - Imagery components whose normal resolution is less than - ``pixel_size_meters`` will be returned at the resolution - specified by ``pixel_size_meters``; imagery components whose - normal resolution is equal to or greater than - ``pixel_size_meters`` will be returned at that normal - resolution. - exact_quality_required (bool): - Optional. Whether to require exact quality of the imagery. - If set to false, the ``required_quality`` field is - interpreted as the minimum required quality, such that HIGH - quality imagery may be returned when ``required_quality`` is - set to MEDIUM. If set to true, ``required_quality`` is - interpreted as the exact required quality and only - ``MEDIUM`` quality imagery is returned if - ``required_quality`` is set to ``MEDIUM``. - """ - - location: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=1, - message=latlng_pb2.LatLng, - ) - radius_meters: float = proto.Field( - proto.FLOAT, - number=2, - ) - view: 'DataLayerView' = proto.Field( - proto.ENUM, - number=3, - enum='DataLayerView', - ) - required_quality: 'ImageryQuality' = proto.Field( - proto.ENUM, - number=5, - enum='ImageryQuality', - ) - pixel_size_meters: float = proto.Field( - proto.FLOAT, - number=6, - ) - exact_quality_required: bool = proto.Field( - proto.BOOL, - number=7, - ) - - -class DataLayers(proto.Message): - r"""Information about the solar potential of a region. The actual data - are contained in a number of GeoTIFF files covering the requested - region, for which this message contains URLs: Each string in the - ``DataLayers`` message contains a URL from which the corresponding - GeoTIFF can be fetched. These URLs are valid for a few hours after - they've been generated. Most of the GeoTIFF files are at a - resolution of 0.1m/pixel, but the monthly flux file is at - 0.5m/pixel, and the hourly shade files are at 1m/pixel. If a - ``pixel_size_meters`` value was specified in the - ``GetDataLayersRequest``, then the minimum resolution in the GeoTIFF - files will be that value. - - Attributes: - imagery_date (google.type.date_pb2.Date): - When the source imagery (from which all the - other data are derived) in this region was - taken. It is necessarily somewhat approximate, - as the images may have been taken over more than - one day. - imagery_processed_date (google.type.date_pb2.Date): - When processing was completed on this - imagery. - dsm_url (str): - The URL for an image of the DSM (Digital - Surface Model) of the region. Values are in - meters above EGM96 geoid (i.e., sea level). - Invalid locations (where we don't have data) are - stored as -9999. - rgb_url (str): - The URL for an image of RGB data (aerial - photo) of the region. - mask_url (str): - The URL for the building mask image: one bit - per pixel saying whether that pixel is - considered to be part of a rooftop or not. - annual_flux_url (str): - The URL for the annual flux map (annual sunlight on roofs) - of the region. Values are kWh/kW/year. This is *unmasked - flux*: flux is computed for every location, not just - building rooftops. Invalid locations are stored as -9999: - locations outside our coverage area will be invalid, and a - few locations inside the coverage area, where we were unable - to calculate flux, will also be invalid. - monthly_flux_url (str): - The URL for the monthly flux map (sunlight on - roofs, broken down by month) of the region. - Values are kWh/kW/year. The GeoTIFF pointed to - by this URL will contain twelve bands, - corresponding to January...December, in order. - hourly_shade_urls (MutableSequence[str]): - Twelve URLs for hourly shade, corresponding to - January...December, in order. Each GeoTIFF will contain 24 - bands, corresponding to the 24 hours of the day. Each pixel - is a 32 bit integer, corresponding to the (up to) 31 days of - that month; a 1 bit means that the corresponding location is - able to see the sun at that day, of that hour, of that - month. Invalid locations are stored as -9999 (since this is - negative, it has bit 31 set, and no valid value could have - bit 31 set as that would correspond to the 32nd day of the - month). - - An example may be useful. If you want to know whether a - point (at pixel location (x, y)) saw sun at 4pm on the 22nd - of June you would: - - 1. fetch the sixth URL in this list (corresponding to June). - 2. look up the 17th channel (corresponding to 4pm). - 3. read the 32-bit value at (x, y). - 4. read bit 21 of the value (corresponding to the 22nd of - the month). - 5. if that bit is a 1, then that spot saw the sun at 4pm 22 - June. - - More formally: Given ``month`` (1-12), ``day`` (1...month - max; February has 28 days) and ``hour`` (0-23), the - shade/sun for that month/day/hour at a position ``(x, y)`` - is the bit - - :: - - (hourly_shade[month - 1])(x, y)[hour] & (1 << (day - 1)) - - where ``(x, y)`` is spatial indexing, ``[month - 1]`` refers - to fetching the ``month - 1``\ st URL (indexing from zero), - ``[hour]`` is indexing into the channels, and a final - non-zero result means "sunny". There are no leap days, and - DST doesn't exist (all days are 24 hours long; noon is - always "standard time" noon). - imagery_quality (google.maps.solar_v1.types.ImageryQuality): - The quality of the result's imagery. - """ - - imagery_date: date_pb2.Date = proto.Field( - proto.MESSAGE, - number=1, - message=date_pb2.Date, - ) - imagery_processed_date: date_pb2.Date = proto.Field( - proto.MESSAGE, - number=2, - message=date_pb2.Date, - ) - dsm_url: str = proto.Field( - proto.STRING, - number=3, - ) - rgb_url: str = proto.Field( - proto.STRING, - number=4, - ) - mask_url: str = proto.Field( - proto.STRING, - number=5, - ) - annual_flux_url: str = proto.Field( - proto.STRING, - number=6, - ) - monthly_flux_url: str = proto.Field( - proto.STRING, - number=7, - ) - hourly_shade_urls: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=8, - ) - imagery_quality: 'ImageryQuality' = proto.Field( - proto.ENUM, - number=9, - enum='ImageryQuality', - ) - - -class GetGeoTiffRequest(proto.Message): - r"""Request message for ``Solar.GetGeoTiff``. - - Attributes: - id (str): - Required. The ID of the asset being - requested. - """ - - id: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-solar/v1/mypy.ini b/owl-bot-staging/google-maps-solar/v1/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-maps-solar/v1/noxfile.py b/owl-bot-staging/google-maps-solar/v1/noxfile.py deleted file mode 100644 index b6a24bc4aae0..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/noxfile.py +++ /dev/null @@ -1,280 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", - "3.12", - "3.13", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = 'google-maps-solar' - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.13" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "prerelease_deps", -] - -@nox.session(python=ALL_PYTHON) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def unit(session, protobuf_implementation): - """Run the unit test suite.""" - - 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+") - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") - - # 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") - - session.run( - 'py.test', - '--quiet', - '--cov=google/maps/solar_v1/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - -@nox.session(python=ALL_PYTHON[-1]) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def prerelease_deps(session, protobuf_implementation): - """Run the unit test suite against pre-release versions of dependencies.""" - - 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 test environment dependencies - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - - # Install the package without dependencies - session.install('-e', '.', '--no-deps') - - # We test the minimum dependency versions using the minimum Python - # version so the lowest python runtime that we test has a corresponding constraints - # file, located at `testing/constraints--.txt`, which contains all of the - # 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 - ) - ] - - session.install(*constraints_deps) - - prerel_deps = [ - "googleapis-common-protos", - "google-api-core", - "google-auth", - # Exclude grpcio!=1.67.0rc1 which does not support python 3.13 - "grpcio!=1.67.0rc1", - "grpcio-status", - "protobuf", - "proto-plus", - ] - - for dep in prerel_deps: - session.install("--pre", "--no-deps", "--upgrade", dep) - - # Remaining dependencies - other_deps = [ - "requests", - ] - session.install(*other_deps) - - # Print out prerelease package versions - - session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") - session.run("python", "-c", "import google.auth; print(google.auth.__version__)") - session.run("python", "-c", "import grpc; print(grpc.__version__)") - session.run( - "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" - ) - session.run( - "python", "-c", "import proto; print(proto.__version__)" - ) - - session.run( - 'py.test', - '--quiet', - '--cov=google/maps/solar_v1/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - - -@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=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 docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==7.0.1", "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=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", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) diff --git a/owl-bot-staging/google-maps-solar/v1/samples/generated_samples/snippet_metadata_google.maps.solar.v1.json b/owl-bot-staging/google-maps-solar/v1/samples/generated_samples/snippet_metadata_google.maps.solar.v1.json deleted file mode 100644 index b0cd14fdb324..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/samples/generated_samples/snippet_metadata_google.maps.solar.v1.json +++ /dev/null @@ -1,474 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.maps.solar.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "google-maps-solar", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.solar_v1.SolarAsyncClient", - "shortName": "SolarAsyncClient" - }, - "fullName": "google.maps.solar_v1.SolarAsyncClient.find_closest_building_insights", - "method": { - "fullName": "google.maps.solar.v1.Solar.FindClosestBuildingInsights", - "service": { - "fullName": "google.maps.solar.v1.Solar", - "shortName": "Solar" - }, - "shortName": "FindClosestBuildingInsights" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.solar_v1.types.FindClosestBuildingInsightsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.maps.solar_v1.types.BuildingInsights", - "shortName": "find_closest_building_insights" - }, - "description": "Sample for FindClosestBuildingInsights", - "file": "solar_v1_generated_solar_find_closest_building_insights_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "solar_v1_generated_Solar_FindClosestBuildingInsights_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": "solar_v1_generated_solar_find_closest_building_insights_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.solar_v1.SolarClient", - "shortName": "SolarClient" - }, - "fullName": "google.maps.solar_v1.SolarClient.find_closest_building_insights", - "method": { - "fullName": "google.maps.solar.v1.Solar.FindClosestBuildingInsights", - "service": { - "fullName": "google.maps.solar.v1.Solar", - "shortName": "Solar" - }, - "shortName": "FindClosestBuildingInsights" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.solar_v1.types.FindClosestBuildingInsightsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.maps.solar_v1.types.BuildingInsights", - "shortName": "find_closest_building_insights" - }, - "description": "Sample for FindClosestBuildingInsights", - "file": "solar_v1_generated_solar_find_closest_building_insights_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "solar_v1_generated_Solar_FindClosestBuildingInsights_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": "solar_v1_generated_solar_find_closest_building_insights_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.solar_v1.SolarAsyncClient", - "shortName": "SolarAsyncClient" - }, - "fullName": "google.maps.solar_v1.SolarAsyncClient.get_data_layers", - "method": { - "fullName": "google.maps.solar.v1.Solar.GetDataLayers", - "service": { - "fullName": "google.maps.solar.v1.Solar", - "shortName": "Solar" - }, - "shortName": "GetDataLayers" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.solar_v1.types.GetDataLayersRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.maps.solar_v1.types.DataLayers", - "shortName": "get_data_layers" - }, - "description": "Sample for GetDataLayers", - "file": "solar_v1_generated_solar_get_data_layers_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "solar_v1_generated_Solar_GetDataLayers_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": "solar_v1_generated_solar_get_data_layers_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.solar_v1.SolarClient", - "shortName": "SolarClient" - }, - "fullName": "google.maps.solar_v1.SolarClient.get_data_layers", - "method": { - "fullName": "google.maps.solar.v1.Solar.GetDataLayers", - "service": { - "fullName": "google.maps.solar.v1.Solar", - "shortName": "Solar" - }, - "shortName": "GetDataLayers" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.solar_v1.types.GetDataLayersRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.maps.solar_v1.types.DataLayers", - "shortName": "get_data_layers" - }, - "description": "Sample for GetDataLayers", - "file": "solar_v1_generated_solar_get_data_layers_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "solar_v1_generated_Solar_GetDataLayers_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": "solar_v1_generated_solar_get_data_layers_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.solar_v1.SolarAsyncClient", - "shortName": "SolarAsyncClient" - }, - "fullName": "google.maps.solar_v1.SolarAsyncClient.get_geo_tiff", - "method": { - "fullName": "google.maps.solar.v1.Solar.GetGeoTiff", - "service": { - "fullName": "google.maps.solar.v1.Solar", - "shortName": "Solar" - }, - "shortName": "GetGeoTiff" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.solar_v1.types.GetGeoTiffRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api.httpbody_pb2.HttpBody", - "shortName": "get_geo_tiff" - }, - "description": "Sample for GetGeoTiff", - "file": "solar_v1_generated_solar_get_geo_tiff_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "solar_v1_generated_Solar_GetGeoTiff_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": "solar_v1_generated_solar_get_geo_tiff_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.solar_v1.SolarClient", - "shortName": "SolarClient" - }, - "fullName": "google.maps.solar_v1.SolarClient.get_geo_tiff", - "method": { - "fullName": "google.maps.solar.v1.Solar.GetGeoTiff", - "service": { - "fullName": "google.maps.solar.v1.Solar", - "shortName": "Solar" - }, - "shortName": "GetGeoTiff" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.solar_v1.types.GetGeoTiffRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api.httpbody_pb2.HttpBody", - "shortName": "get_geo_tiff" - }, - "description": "Sample for GetGeoTiff", - "file": "solar_v1_generated_solar_get_geo_tiff_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "solar_v1_generated_Solar_GetGeoTiff_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": "solar_v1_generated_solar_get_geo_tiff_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_find_closest_building_insights_async.py b/owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_find_closest_building_insights_async.py deleted file mode 100644 index 5058da619386..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_find_closest_building_insights_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for FindClosestBuildingInsights -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-solar - - -# [START solar_v1_generated_Solar_FindClosestBuildingInsights_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.maps import solar_v1 - - -async def sample_find_closest_building_insights(): - # Create a client - client = solar_v1.SolarAsyncClient() - - # Initialize request argument(s) - request = solar_v1.FindClosestBuildingInsightsRequest( - ) - - # Make the request - response = await client.find_closest_building_insights(request=request) - - # Handle the response - print(response) - -# [END solar_v1_generated_Solar_FindClosestBuildingInsights_async] diff --git a/owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_find_closest_building_insights_sync.py b/owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_find_closest_building_insights_sync.py deleted file mode 100644 index a08c85dc78de..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_find_closest_building_insights_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for FindClosestBuildingInsights -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-solar - - -# [START solar_v1_generated_Solar_FindClosestBuildingInsights_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.maps import solar_v1 - - -def sample_find_closest_building_insights(): - # Create a client - client = solar_v1.SolarClient() - - # Initialize request argument(s) - request = solar_v1.FindClosestBuildingInsightsRequest( - ) - - # Make the request - response = client.find_closest_building_insights(request=request) - - # Handle the response - print(response) - -# [END solar_v1_generated_Solar_FindClosestBuildingInsights_sync] diff --git a/owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_get_data_layers_async.py b/owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_get_data_layers_async.py deleted file mode 100644 index c97710ca5564..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_get_data_layers_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetDataLayers -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-solar - - -# [START solar_v1_generated_Solar_GetDataLayers_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.maps import solar_v1 - - -async def sample_get_data_layers(): - # Create a client - client = solar_v1.SolarAsyncClient() - - # Initialize request argument(s) - request = solar_v1.GetDataLayersRequest( - radius_meters=0.1399, - ) - - # Make the request - response = await client.get_data_layers(request=request) - - # Handle the response - print(response) - -# [END solar_v1_generated_Solar_GetDataLayers_async] diff --git a/owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_get_data_layers_sync.py b/owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_get_data_layers_sync.py deleted file mode 100644 index d9d0aff7cef8..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_get_data_layers_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetDataLayers -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-solar - - -# [START solar_v1_generated_Solar_GetDataLayers_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.maps import solar_v1 - - -def sample_get_data_layers(): - # Create a client - client = solar_v1.SolarClient() - - # Initialize request argument(s) - request = solar_v1.GetDataLayersRequest( - radius_meters=0.1399, - ) - - # Make the request - response = client.get_data_layers(request=request) - - # Handle the response - print(response) - -# [END solar_v1_generated_Solar_GetDataLayers_sync] diff --git a/owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_get_geo_tiff_async.py b/owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_get_geo_tiff_async.py deleted file mode 100644 index 7833a4f51179..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_get_geo_tiff_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetGeoTiff -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-solar - - -# [START solar_v1_generated_Solar_GetGeoTiff_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.maps import solar_v1 - - -async def sample_get_geo_tiff(): - # Create a client - client = solar_v1.SolarAsyncClient() - - # Initialize request argument(s) - request = solar_v1.GetGeoTiffRequest( - id="id_value", - ) - - # Make the request - response = await client.get_geo_tiff(request=request) - - # Handle the response - print(response) - -# [END solar_v1_generated_Solar_GetGeoTiff_async] diff --git a/owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_get_geo_tiff_sync.py b/owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_get_geo_tiff_sync.py deleted file mode 100644 index 1349f69d8c1f..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/samples/generated_samples/solar_v1_generated_solar_get_geo_tiff_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetGeoTiff -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-solar - - -# [START solar_v1_generated_Solar_GetGeoTiff_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.maps import solar_v1 - - -def sample_get_geo_tiff(): - # Create a client - client = solar_v1.SolarClient() - - # Initialize request argument(s) - request = solar_v1.GetGeoTiffRequest( - id="id_value", - ) - - # Make the request - response = client.get_geo_tiff(request=request) - - # Handle the response - print(response) - -# [END solar_v1_generated_Solar_GetGeoTiff_sync] diff --git a/owl-bot-staging/google-maps-solar/v1/scripts/fixup_solar_v1_keywords.py b/owl-bot-staging/google-maps-solar/v1/scripts/fixup_solar_v1_keywords.py deleted file mode 100644 index 4431e778567d..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/scripts/fixup_solar_v1_keywords.py +++ /dev/null @@ -1,178 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 solarCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'find_closest_building_insights': ('location', 'required_quality', 'exact_quality_required', ), - 'get_data_layers': ('location', 'radius_meters', 'view', 'required_quality', 'pixel_size_meters', 'exact_quality_required', ), - 'get_geo_tiff': ('id', ), - } - - 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=solarCallTransformer(), -): - """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 solar 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-maps-solar/v1/setup.py b/owl-bot-staging/google-maps-solar/v1/setup.py deleted file mode 100644 index 8032e03cfd67..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/setup.py +++ /dev/null @@ -1,98 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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-maps-solar' - - -description = "Google Maps Solar API client library" - -version = None - -with open(os.path.join(package_root, 'google/maps/solar/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.0dev,!=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.0dev,!=2.24.0,!=2.25.0", - "proto-plus >= 1.22.3, <2.0.0dev", - "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'", - "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", -] -extras = { -} -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-solar" - -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-maps-solar/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-maps-solar/v1/testing/constraints-3.10.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/testing/constraints-3.10.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/google-maps-solar/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-maps-solar/v1/testing/constraints-3.11.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/testing/constraints-3.11.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/google-maps-solar/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-maps-solar/v1/testing/constraints-3.12.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/testing/constraints-3.12.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/google-maps-solar/v1/testing/constraints-3.13.txt b/owl-bot-staging/google-maps-solar/v1/testing/constraints-3.13.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/testing/constraints-3.13.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/google-maps-solar/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-maps-solar/v1/testing/constraints-3.7.txt deleted file mode 100644 index fc812592b0ee..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/testing/constraints-3.7.txt +++ /dev/null @@ -1,10 +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.0dev", -# 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 diff --git a/owl-bot-staging/google-maps-solar/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-maps-solar/v1/testing/constraints-3.8.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/testing/constraints-3.8.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/google-maps-solar/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-maps-solar/v1/testing/constraints-3.9.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/testing/constraints-3.9.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/google-maps-solar/v1/tests/__init__.py b/owl-bot-staging/google-maps-solar/v1/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-maps-solar/v1/tests/unit/__init__.py b/owl-bot-staging/google-maps-solar/v1/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-maps-solar/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-maps-solar/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-maps-solar/v1/tests/unit/gapic/solar_v1/__init__.py b/owl-bot-staging/google-maps-solar/v1/tests/unit/gapic/solar_v1/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/tests/unit/gapic/solar_v1/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-maps-solar/v1/tests/unit/gapic/solar_v1/test_solar.py b/owl-bot-staging/google-maps-solar/v1/tests/unit/gapic/solar_v1/test_solar.py deleted file mode 100644 index 6789c2cffbdc..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/tests/unit/gapic/solar_v1/test_solar.py +++ /dev/null @@ -1,2872 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 import httpbody_pb2 # type: ignore -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.maps.solar_v1.services.solar import SolarAsyncClient -from google.maps.solar_v1.services.solar import SolarClient -from google.maps.solar_v1.services.solar import transports -from google.maps.solar_v1.types import solar_service -from google.oauth2 import service_account -from google.protobuf import any_pb2 # type: ignore -from google.type import date_pb2 # type: ignore -from google.type import latlng_pb2 # type: ignore -import google.auth - - -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 SolarClient._get_default_mtls_endpoint(None) is None - assert SolarClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert SolarClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert SolarClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert SolarClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert SolarClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert SolarClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert SolarClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert SolarClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - SolarClient._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 SolarClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert SolarClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert SolarClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - SolarClient._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 SolarClient._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 SolarClient._get_client_cert_source(None, False) is None - assert SolarClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert SolarClient._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 SolarClient._get_client_cert_source(None, True) is mock_default_cert_source - assert SolarClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(SolarClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SolarClient)) -@mock.patch.object(SolarAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SolarAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = SolarClient._DEFAULT_UNIVERSE - default_endpoint = SolarClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = SolarClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert SolarClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert SolarClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == SolarClient.DEFAULT_MTLS_ENDPOINT - assert SolarClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert SolarClient._get_api_endpoint(None, None, default_universe, "always") == SolarClient.DEFAULT_MTLS_ENDPOINT - assert SolarClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == SolarClient.DEFAULT_MTLS_ENDPOINT - assert SolarClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert SolarClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - SolarClient._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 SolarClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert SolarClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert SolarClient._get_universe_domain(None, None) == SolarClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - SolarClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - - -@pytest.mark.parametrize("client_class,transport_name", [ - (SolarClient, "grpc"), - (SolarAsyncClient, "grpc_asyncio"), - (SolarClient, "rest"), -]) -def test_solar_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 == ( - 'solar.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://solar.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.SolarGrpcTransport, "grpc"), - (transports.SolarGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.SolarRestTransport, "rest"), -]) -def test_solar_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", [ - (SolarClient, "grpc"), - (SolarAsyncClient, "grpc_asyncio"), - (SolarClient, "rest"), -]) -def test_solar_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 == ( - 'solar.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://solar.googleapis.com' - ) - - -def test_solar_client_get_transport_class(): - transport = SolarClient.get_transport_class() - available_transports = [ - transports.SolarGrpcTransport, - transports.SolarRestTransport, - ] - assert transport in available_transports - - transport = SolarClient.get_transport_class("grpc") - assert transport == transports.SolarGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SolarClient, transports.SolarGrpcTransport, "grpc"), - (SolarAsyncClient, transports.SolarGrpcAsyncIOTransport, "grpc_asyncio"), - (SolarClient, transports.SolarRestTransport, "rest"), -]) -@mock.patch.object(SolarClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SolarClient)) -@mock.patch.object(SolarAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SolarAsyncClient)) -def test_solar_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(SolarClient, '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(SolarClient, '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", [ - (SolarClient, transports.SolarGrpcTransport, "grpc", "true"), - (SolarAsyncClient, transports.SolarGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (SolarClient, transports.SolarGrpcTransport, "grpc", "false"), - (SolarAsyncClient, transports.SolarGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (SolarClient, transports.SolarRestTransport, "rest", "true"), - (SolarClient, transports.SolarRestTransport, "rest", "false"), -]) -@mock.patch.object(SolarClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SolarClient)) -@mock.patch.object(SolarAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SolarAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_solar_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", [ - SolarClient, SolarAsyncClient -]) -@mock.patch.object(SolarClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SolarClient)) -@mock.patch.object(SolarAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SolarAsyncClient)) -def test_solar_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", [ - SolarClient, SolarAsyncClient -]) -@mock.patch.object(SolarClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SolarClient)) -@mock.patch.object(SolarAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SolarAsyncClient)) -def test_solar_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = SolarClient._DEFAULT_UNIVERSE - default_endpoint = SolarClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = SolarClient._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", [ - (SolarClient, transports.SolarGrpcTransport, "grpc"), - (SolarAsyncClient, transports.SolarGrpcAsyncIOTransport, "grpc_asyncio"), - (SolarClient, transports.SolarRestTransport, "rest"), -]) -def test_solar_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", [ - (SolarClient, transports.SolarGrpcTransport, "grpc", grpc_helpers), - (SolarAsyncClient, transports.SolarGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (SolarClient, transports.SolarRestTransport, "rest", None), -]) -def test_solar_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_solar_client_client_options_from_dict(): - with mock.patch('google.maps.solar_v1.services.solar.transports.SolarGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = SolarClient( - 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", [ - (SolarClient, transports.SolarGrpcTransport, "grpc", grpc_helpers), - (SolarAsyncClient, transports.SolarGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_solar_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( - "solar.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=None, - default_host="solar.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - solar_service.FindClosestBuildingInsightsRequest, - dict, -]) -def test_find_closest_building_insights(request_type, transport: str = 'grpc'): - client = SolarClient( - 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_closest_building_insights), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = solar_service.BuildingInsights( - name='name_value', - postal_code='postal_code_value', - administrative_area='administrative_area_value', - statistical_area='statistical_area_value', - region_code='region_code_value', - imagery_quality=solar_service.ImageryQuality.HIGH, - ) - response = client.find_closest_building_insights(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = solar_service.FindClosestBuildingInsightsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, solar_service.BuildingInsights) - assert response.name == 'name_value' - assert response.postal_code == 'postal_code_value' - assert response.administrative_area == 'administrative_area_value' - assert response.statistical_area == 'statistical_area_value' - assert response.region_code == 'region_code_value' - assert response.imagery_quality == solar_service.ImageryQuality.HIGH - - -def test_find_closest_building_insights_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 = SolarClient( - 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 = solar_service.FindClosestBuildingInsightsRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.find_closest_building_insights), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.find_closest_building_insights(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == solar_service.FindClosestBuildingInsightsRequest( - ) - -def test_find_closest_building_insights_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SolarClient( - 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_closest_building_insights in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_closest_building_insights] = mock_rpc - request = {} - client.find_closest_building_insights(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.find_closest_building_insights(request) - - # Establish that a new wrapper 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_closest_building_insights_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = SolarAsyncClient( - 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_closest_building_insights in client._client._transport._wrapped_methods - - # 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_closest_building_insights] = mock_rpc - - request = {} - await client.find_closest_building_insights(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.find_closest_building_insights(request) - - # Establish that a new wrapper 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_closest_building_insights_async(transport: str = 'grpc_asyncio', request_type=solar_service.FindClosestBuildingInsightsRequest): - client = SolarAsyncClient( - 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_closest_building_insights), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(solar_service.BuildingInsights( - name='name_value', - postal_code='postal_code_value', - administrative_area='administrative_area_value', - statistical_area='statistical_area_value', - region_code='region_code_value', - imagery_quality=solar_service.ImageryQuality.HIGH, - )) - response = await client.find_closest_building_insights(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = solar_service.FindClosestBuildingInsightsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, solar_service.BuildingInsights) - assert response.name == 'name_value' - assert response.postal_code == 'postal_code_value' - assert response.administrative_area == 'administrative_area_value' - assert response.statistical_area == 'statistical_area_value' - assert response.region_code == 'region_code_value' - assert response.imagery_quality == solar_service.ImageryQuality.HIGH - - -@pytest.mark.asyncio -async def test_find_closest_building_insights_async_from_dict(): - await test_find_closest_building_insights_async(request_type=dict) - - -@pytest.mark.parametrize("request_type", [ - solar_service.GetDataLayersRequest, - dict, -]) -def test_get_data_layers(request_type, transport: str = 'grpc'): - client = SolarClient( - 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_data_layers), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = solar_service.DataLayers( - dsm_url='dsm_url_value', - rgb_url='rgb_url_value', - mask_url='mask_url_value', - annual_flux_url='annual_flux_url_value', - monthly_flux_url='monthly_flux_url_value', - hourly_shade_urls=['hourly_shade_urls_value'], - imagery_quality=solar_service.ImageryQuality.HIGH, - ) - response = client.get_data_layers(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = solar_service.GetDataLayersRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, solar_service.DataLayers) - assert response.dsm_url == 'dsm_url_value' - assert response.rgb_url == 'rgb_url_value' - assert response.mask_url == 'mask_url_value' - assert response.annual_flux_url == 'annual_flux_url_value' - assert response.monthly_flux_url == 'monthly_flux_url_value' - assert response.hourly_shade_urls == ['hourly_shade_urls_value'] - assert response.imagery_quality == solar_service.ImageryQuality.HIGH - - -def test_get_data_layers_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 = SolarClient( - 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 = solar_service.GetDataLayersRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_data_layers), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_data_layers(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == solar_service.GetDataLayersRequest( - ) - -def test_get_data_layers_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SolarClient( - 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_data_layers in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_data_layers] = mock_rpc - request = {} - client.get_data_layers(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_data_layers(request) - - # Establish that a new wrapper 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_data_layers_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = SolarAsyncClient( - 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_data_layers in client._client._transport._wrapped_methods - - # 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_data_layers] = mock_rpc - - request = {} - await client.get_data_layers(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_data_layers(request) - - # Establish that a new wrapper 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_data_layers_async(transport: str = 'grpc_asyncio', request_type=solar_service.GetDataLayersRequest): - client = SolarAsyncClient( - 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_data_layers), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(solar_service.DataLayers( - dsm_url='dsm_url_value', - rgb_url='rgb_url_value', - mask_url='mask_url_value', - annual_flux_url='annual_flux_url_value', - monthly_flux_url='monthly_flux_url_value', - hourly_shade_urls=['hourly_shade_urls_value'], - imagery_quality=solar_service.ImageryQuality.HIGH, - )) - response = await client.get_data_layers(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = solar_service.GetDataLayersRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, solar_service.DataLayers) - assert response.dsm_url == 'dsm_url_value' - assert response.rgb_url == 'rgb_url_value' - assert response.mask_url == 'mask_url_value' - assert response.annual_flux_url == 'annual_flux_url_value' - assert response.monthly_flux_url == 'monthly_flux_url_value' - assert response.hourly_shade_urls == ['hourly_shade_urls_value'] - assert response.imagery_quality == solar_service.ImageryQuality.HIGH - - -@pytest.mark.asyncio -async def test_get_data_layers_async_from_dict(): - await test_get_data_layers_async(request_type=dict) - - -@pytest.mark.parametrize("request_type", [ - solar_service.GetGeoTiffRequest, - dict, -]) -def test_get_geo_tiff(request_type, transport: str = 'grpc'): - client = SolarClient( - 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_geo_tiff), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = httpbody_pb2.HttpBody( - content_type='content_type_value', - data=b'data_blob', - ) - response = client.get_geo_tiff(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = solar_service.GetGeoTiffRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, httpbody_pb2.HttpBody) - assert response.content_type == 'content_type_value' - assert response.data == b'data_blob' - - -def test_get_geo_tiff_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 = SolarClient( - 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 = solar_service.GetGeoTiffRequest( - id='id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_geo_tiff), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_geo_tiff(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == solar_service.GetGeoTiffRequest( - id='id_value', - ) - -def test_get_geo_tiff_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SolarClient( - 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_geo_tiff in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_geo_tiff] = mock_rpc - request = {} - client.get_geo_tiff(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_geo_tiff(request) - - # Establish that a new wrapper 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_geo_tiff_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = SolarAsyncClient( - 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_geo_tiff in client._client._transport._wrapped_methods - - # 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_geo_tiff] = mock_rpc - - request = {} - await client.get_geo_tiff(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_geo_tiff(request) - - # Establish that a new wrapper 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_geo_tiff_async(transport: str = 'grpc_asyncio', request_type=solar_service.GetGeoTiffRequest): - client = SolarAsyncClient( - 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_geo_tiff), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody( - content_type='content_type_value', - data=b'data_blob', - )) - response = await client.get_geo_tiff(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = solar_service.GetGeoTiffRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, httpbody_pb2.HttpBody) - assert response.content_type == 'content_type_value' - assert response.data == b'data_blob' - - -@pytest.mark.asyncio -async def test_get_geo_tiff_async_from_dict(): - await test_get_geo_tiff_async(request_type=dict) - - -def test_find_closest_building_insights_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 = SolarClient( - 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_closest_building_insights in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_closest_building_insights] = mock_rpc - - request = {} - client.find_closest_building_insights(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.find_closest_building_insights(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_closest_building_insights_rest_required_fields(request_type=solar_service.FindClosestBuildingInsightsRequest): - transport_class = transports.SolarRestTransport - - 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()).find_closest_building_insights._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()).find_closest_building_insights._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("exact_quality_required", "location", "required_quality", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = SolarClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = solar_service.BuildingInsights() - # 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 = solar_service.BuildingInsights.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_closest_building_insights(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_find_closest_building_insights_rest_unset_required_fields(): - transport = transports.SolarRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.find_closest_building_insights._get_unset_required_fields({}) - assert set(unset_fields) == (set(("exactQualityRequired", "location", "requiredQuality", )) & set(("location", ))) - - -def test_get_data_layers_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 = SolarClient( - 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_data_layers in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_data_layers] = mock_rpc - - request = {} - client.get_data_layers(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_data_layers(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_data_layers_rest_required_fields(request_type=solar_service.GetDataLayersRequest): - transport_class = transports.SolarRestTransport - - request_init = {} - request_init["radius_meters"] = 0.0 - request = 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 "radiusMeters" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_data_layers._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "radiusMeters" in jsonified_request - assert jsonified_request["radiusMeters"] == request_init["radius_meters"] - - jsonified_request["radiusMeters"] = 0.1399 - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_data_layers._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("exact_quality_required", "location", "pixel_size_meters", "radius_meters", "required_quality", "view", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "radiusMeters" in jsonified_request - assert jsonified_request["radiusMeters"] == 0.1399 - - client = SolarClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = solar_service.DataLayers() - # 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 = solar_service.DataLayers.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_data_layers(request) - - expected_params = [ - ( - "radiusMeters", - str(0.0), - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_data_layers_rest_unset_required_fields(): - transport = transports.SolarRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_data_layers._get_unset_required_fields({}) - assert set(unset_fields) == (set(("exactQualityRequired", "location", "pixelSizeMeters", "radiusMeters", "requiredQuality", "view", )) & set(("location", "radiusMeters", ))) - - -def test_get_geo_tiff_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 = SolarClient( - 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_geo_tiff in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_geo_tiff] = mock_rpc - - request = {} - client.get_geo_tiff(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_geo_tiff(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_geo_tiff_rest_required_fields(request_type=solar_service.GetGeoTiffRequest): - transport_class = transports.SolarRestTransport - - request_init = {} - request_init["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 "id" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_geo_tiff._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "id" in jsonified_request - assert jsonified_request["id"] == request_init["id"] - - jsonified_request["id"] = 'id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_geo_tiff._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "id" in jsonified_request - assert jsonified_request["id"] == 'id_value' - - client = SolarClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = httpbody_pb2.HttpBody() - # 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 = json_format.MessageToJson(return_value) - - response_value._content = json_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_geo_tiff(request) - - expected_params = [ - ( - "id", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_geo_tiff_rest_unset_required_fields(): - transport = transports.SolarRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_geo_tiff._get_unset_required_fields({}) - assert set(unset_fields) == (set(("id", )) & set(("id", ))) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.SolarGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SolarClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.SolarGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SolarClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.SolarGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SolarClient( - 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 = SolarClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.SolarGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SolarClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.SolarGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = SolarClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.SolarGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.SolarGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.SolarGrpcTransport, - transports.SolarGrpcAsyncIOTransport, - transports.SolarRestTransport, -]) -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 = SolarClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = SolarClient( - 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_closest_building_insights_empty_call_grpc(): - client = SolarClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.find_closest_building_insights), - '__call__') as call: - call.return_value = solar_service.BuildingInsights() - client.find_closest_building_insights(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = solar_service.FindClosestBuildingInsightsRequest() - - assert args[0] == request_msg - - -# This 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_data_layers_empty_call_grpc(): - client = SolarClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_data_layers), - '__call__') as call: - call.return_value = solar_service.DataLayers() - client.get_data_layers(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = solar_service.GetDataLayersRequest() - - assert args[0] == request_msg - - -# This 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_geo_tiff_empty_call_grpc(): - client = SolarClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_geo_tiff), - '__call__') as call: - call.return_value = httpbody_pb2.HttpBody() - client.get_geo_tiff(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = solar_service.GetGeoTiffRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = SolarAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = SolarAsyncClient( - 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_closest_building_insights_empty_call_grpc_asyncio(): - client = SolarAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.find_closest_building_insights), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(solar_service.BuildingInsights( - name='name_value', - postal_code='postal_code_value', - administrative_area='administrative_area_value', - statistical_area='statistical_area_value', - region_code='region_code_value', - imagery_quality=solar_service.ImageryQuality.HIGH, - )) - await client.find_closest_building_insights(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = solar_service.FindClosestBuildingInsightsRequest() - - assert args[0] == request_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_data_layers_empty_call_grpc_asyncio(): - client = SolarAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_data_layers), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(solar_service.DataLayers( - dsm_url='dsm_url_value', - rgb_url='rgb_url_value', - mask_url='mask_url_value', - annual_flux_url='annual_flux_url_value', - monthly_flux_url='monthly_flux_url_value', - hourly_shade_urls=['hourly_shade_urls_value'], - imagery_quality=solar_service.ImageryQuality.HIGH, - )) - await client.get_data_layers(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = solar_service.GetDataLayersRequest() - - assert args[0] == request_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_geo_tiff_empty_call_grpc_asyncio(): - client = SolarAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_geo_tiff), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody( - content_type='content_type_value', - data=b'data_blob', - )) - await client.get_geo_tiff(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = solar_service.GetGeoTiffRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = SolarClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_find_closest_building_insights_rest_bad_request(request_type=solar_service.FindClosestBuildingInsightsRequest): - client = SolarClient( - 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.find_closest_building_insights(request) - - -@pytest.mark.parametrize("request_type", [ - solar_service.FindClosestBuildingInsightsRequest, - dict, -]) -def test_find_closest_building_insights_rest_call_success(request_type): - client = SolarClient( - 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 = solar_service.BuildingInsights( - name='name_value', - postal_code='postal_code_value', - administrative_area='administrative_area_value', - statistical_area='statistical_area_value', - region_code='region_code_value', - imagery_quality=solar_service.ImageryQuality.HIGH, - ) - - # 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 = solar_service.BuildingInsights.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_closest_building_insights(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, solar_service.BuildingInsights) - assert response.name == 'name_value' - assert response.postal_code == 'postal_code_value' - assert response.administrative_area == 'administrative_area_value' - assert response.statistical_area == 'statistical_area_value' - assert response.region_code == 'region_code_value' - assert response.imagery_quality == solar_service.ImageryQuality.HIGH - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_find_closest_building_insights_rest_interceptors(null_interceptor): - transport = transports.SolarRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SolarRestInterceptor(), - ) - client = SolarClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SolarRestInterceptor, "post_find_closest_building_insights") as post, \ - mock.patch.object(transports.SolarRestInterceptor, "pre_find_closest_building_insights") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = solar_service.FindClosestBuildingInsightsRequest.pb(solar_service.FindClosestBuildingInsightsRequest()) - 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 = solar_service.BuildingInsights.to_json(solar_service.BuildingInsights()) - req.return_value.content = return_value - - request = solar_service.FindClosestBuildingInsightsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = solar_service.BuildingInsights() - - client.find_closest_building_insights(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_data_layers_rest_bad_request(request_type=solar_service.GetDataLayersRequest): - client = SolarClient( - 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.get_data_layers(request) - - -@pytest.mark.parametrize("request_type", [ - solar_service.GetDataLayersRequest, - dict, -]) -def test_get_data_layers_rest_call_success(request_type): - client = SolarClient( - 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 = solar_service.DataLayers( - dsm_url='dsm_url_value', - rgb_url='rgb_url_value', - mask_url='mask_url_value', - annual_flux_url='annual_flux_url_value', - monthly_flux_url='monthly_flux_url_value', - hourly_shade_urls=['hourly_shade_urls_value'], - imagery_quality=solar_service.ImageryQuality.HIGH, - ) - - # 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 = solar_service.DataLayers.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_data_layers(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, solar_service.DataLayers) - assert response.dsm_url == 'dsm_url_value' - assert response.rgb_url == 'rgb_url_value' - assert response.mask_url == 'mask_url_value' - assert response.annual_flux_url == 'annual_flux_url_value' - assert response.monthly_flux_url == 'monthly_flux_url_value' - assert response.hourly_shade_urls == ['hourly_shade_urls_value'] - assert response.imagery_quality == solar_service.ImageryQuality.HIGH - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_data_layers_rest_interceptors(null_interceptor): - transport = transports.SolarRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SolarRestInterceptor(), - ) - client = SolarClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SolarRestInterceptor, "post_get_data_layers") as post, \ - mock.patch.object(transports.SolarRestInterceptor, "pre_get_data_layers") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = solar_service.GetDataLayersRequest.pb(solar_service.GetDataLayersRequest()) - 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 = solar_service.DataLayers.to_json(solar_service.DataLayers()) - req.return_value.content = return_value - - request = solar_service.GetDataLayersRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = solar_service.DataLayers() - - client.get_data_layers(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_geo_tiff_rest_bad_request(request_type=solar_service.GetGeoTiffRequest): - client = SolarClient( - 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.get_geo_tiff(request) - - -@pytest.mark.parametrize("request_type", [ - solar_service.GetGeoTiffRequest, - dict, -]) -def test_get_geo_tiff_rest_call_success(request_type): - client = SolarClient( - 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 = httpbody_pb2.HttpBody( - content_type='content_type_value', - data=b'data_blob', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_geo_tiff(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, httpbody_pb2.HttpBody) - assert response.content_type == 'content_type_value' - assert response.data == b'data_blob' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_geo_tiff_rest_interceptors(null_interceptor): - transport = transports.SolarRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SolarRestInterceptor(), - ) - client = SolarClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SolarRestInterceptor, "post_get_geo_tiff") as post, \ - mock.patch.object(transports.SolarRestInterceptor, "pre_get_geo_tiff") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = solar_service.GetGeoTiffRequest.pb(solar_service.GetGeoTiffRequest()) - 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 = json_format.MessageToJson(httpbody_pb2.HttpBody()) - req.return_value.content = return_value - - request = solar_service.GetGeoTiffRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = httpbody_pb2.HttpBody() - - client.get_geo_tiff(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - -def test_initialize_client_w_rest(): - client = SolarClient( - 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_closest_building_insights_empty_call_rest(): - client = SolarClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.find_closest_building_insights), - '__call__') as call: - client.find_closest_building_insights(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = solar_service.FindClosestBuildingInsightsRequest() - - assert args[0] == request_msg - - -# This 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_data_layers_empty_call_rest(): - client = SolarClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_data_layers), - '__call__') as call: - client.get_data_layers(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = solar_service.GetDataLayersRequest() - - assert args[0] == request_msg - - -# This 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_geo_tiff_empty_call_rest(): - client = SolarClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_geo_tiff), - '__call__') as call: - client.get_geo_tiff(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = solar_service.GetGeoTiffRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = SolarClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.SolarGrpcTransport, - ) - -def test_solar_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.SolarTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_solar_base_transport(): - # Instantiate the base transport. - with mock.patch('google.maps.solar_v1.services.solar.transports.SolarTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.SolarTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'find_closest_building_insights', - 'get_data_layers', - 'get_geo_tiff', - ) - 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_solar_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.maps.solar_v1.services.solar.transports.SolarTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SolarTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_solar_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.maps.solar_v1.services.solar.transports.SolarTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SolarTransport() - adc.assert_called_once() - - -def test_solar_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) - SolarClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.SolarGrpcTransport, - transports.SolarGrpcAsyncIOTransport, - ], -) -def test_solar_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.SolarGrpcTransport, - transports.SolarGrpcAsyncIOTransport, - transports.SolarRestTransport, - ], -) -def test_solar_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.SolarGrpcTransport, grpc_helpers), - (transports.SolarGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_solar_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( - "solar.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=["1", "2"], - default_host="solar.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.SolarGrpcTransport, transports.SolarGrpcAsyncIOTransport]) -def test_solar_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_solar_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.SolarRestTransport ( - 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_solar_host_no_port(transport_name): - client = SolarClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='solar.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'solar.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://solar.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_solar_host_with_port(transport_name): - client = SolarClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='solar.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'solar.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://solar.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_solar_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = SolarClient( - credentials=creds1, - transport=transport_name, - ) - client2 = SolarClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.find_closest_building_insights._session - session2 = client2.transport.find_closest_building_insights._session - assert session1 != session2 - session1 = client1.transport.get_data_layers._session - session2 = client2.transport.get_data_layers._session - assert session1 != session2 - session1 = client1.transport.get_geo_tiff._session - session2 = client2.transport.get_geo_tiff._session - assert session1 != session2 -def test_solar_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SolarGrpcTransport( - 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_solar_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SolarGrpcAsyncIOTransport( - 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.SolarGrpcTransport, transports.SolarGrpcAsyncIOTransport]) -def test_solar_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.SolarGrpcTransport, transports.SolarGrpcAsyncIOTransport]) -def test_solar_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_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = SolarClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = SolarClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = SolarClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = SolarClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = SolarClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = SolarClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = SolarClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = SolarClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = SolarClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = SolarClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = SolarClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = SolarClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = SolarClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = SolarClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = SolarClient.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.SolarTransport, '_prep_wrapped_messages') as prep: - client = SolarClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.SolarTransport, '_prep_wrapped_messages') as prep: - transport_class = SolarClient.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 = SolarClient( - 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 = SolarAsyncClient( - 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 = SolarClient( - 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 = SolarClient( - 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", [ - (SolarClient, transports.SolarGrpcTransport), - (SolarAsyncClient, transports.SolarGrpcAsyncIOTransport), -]) -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 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 29227d4cf419..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py 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 2d47c575078c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/shopping/merchant_accounts *.py -recursive-include google/shopping/merchant_accounts_v1beta *.py 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 7f9da4dde09e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/README.rst +++ /dev/null @@ -1,49 +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 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 06423be0b592..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/_static/custom.css +++ /dev/null @@ -1,3 +0,0 @@ -dl.field-list > dt { - min-width: 100px -} 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 c05de3e02b27..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# 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.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -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"2023, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# 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 = 'en' - -# 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"] - -# 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 Python", - "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", - u"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", - u"google-shopping-merchant-accounts Documentation", - author, - "google-shopping-merchant-accounts", - "GAPIC library for Google Shopping Merchant Accounts API", - "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": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", 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 fc03b88376b9..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -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/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/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/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/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 b9c209efb0f7..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/services_.rst +++ /dev/null @@ -1,20 +0,0 @@ -Services for Google Shopping Merchant Accounts v1beta API -========================================================= -.. toctree:: - :maxdepth: 2 - - account_issue_service - accounts_service - account_tax_service - autofeed_settings_service - business_identity_service - business_info_service - email_preferences_service - homepage_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/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 9e156f01c727..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts/__init__.py +++ /dev/null @@ -1,271 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.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.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.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.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.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.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.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.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.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', - 'BusinessIdentityServiceClient', - 'BusinessIdentityServiceAsyncClient', - 'BusinessInfoServiceClient', - 'BusinessInfoServiceAsyncClient', - 'EmailPreferencesServiceClient', - 'EmailPreferencesServiceAsyncClient', - 'HomepageServiceClient', - 'HomepageServiceAsyncClient', - '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', - 'BusinessIdentity', - 'GetBusinessIdentityRequest', - 'UpdateBusinessIdentityRequest', - 'BusinessInfo', - 'GetBusinessInfoRequest', - 'UpdateBusinessInfoRequest', - 'CustomerService', - 'EmailPreferences', - 'GetEmailPreferencesRequest', - 'UpdateEmailPreferencesRequest', - 'ClaimHomepageRequest', - 'GetHomepageRequest', - 'Homepage', - 'UnclaimHomepageRequest', - 'UpdateHomepageRequest', - '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', - '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 558c8aab67c5..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 318d5a29d75e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/__init__.py +++ /dev/null @@ -1,272 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.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.email_preferences_service import EmailPreferencesServiceClient -from .services.email_preferences_service import EmailPreferencesServiceAsyncClient -from .services.homepage_service import HomepageServiceClient -from .services.homepage_service import HomepageServiceAsyncClient -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.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.customerservice import CustomerService -from .types.emailpreferences import EmailPreferences -from .types.emailpreferences import GetEmailPreferencesRequest -from .types.emailpreferences import UpdateEmailPreferencesRequest -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.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.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', - 'BusinessIdentityServiceAsyncClient', - 'BusinessInfoServiceAsyncClient', - 'EmailPreferencesServiceAsyncClient', - 'HomepageServiceAsyncClient', - 'OnlineReturnPolicyServiceAsyncClient', - 'ProgramsServiceAsyncClient', - 'RegionsServiceAsyncClient', - 'ShippingSettingsServiceAsyncClient', - 'TermsOfServiceAgreementStateServiceAsyncClient', - 'TermsOfServiceServiceAsyncClient', - 'UserServiceAsyncClient', -'AcceptTermsOfServiceRequest', -'Accepted', -'AccessRight', -'Account', -'AccountAggregation', -'AccountIssue', -'AccountIssueServiceClient', -'AccountTax', -'AccountTaxServiceClient', -'AccountsServiceClient', -'Address', -'AutofeedSettings', -'AutofeedSettingsServiceClient', -'BusinessDayConfig', -'BusinessIdentity', -'BusinessIdentityServiceClient', -'BusinessInfo', -'BusinessInfoServiceClient', -'CarrierRate', -'ClaimHomepageRequest', -'CreateAndConfigureAccountRequest', -'CreateRegionRequest', -'CreateUserRequest', -'CustomerService', -'CutoffTime', -'DeleteAccountRequest', -'DeleteRegionRequest', -'DeleteUserRequest', -'DeliveryTime', -'DisableProgramRequest', -'Distance', -'EmailPreferences', -'EmailPreferencesServiceClient', -'EnableProgramRequest', -'GetAccountRequest', -'GetAccountTaxRequest', -'GetAutofeedSettingsRequest', -'GetBusinessIdentityRequest', -'GetBusinessInfoRequest', -'GetEmailPreferencesRequest', -'GetHomepageRequest', -'GetOnlineReturnPolicyRequest', -'GetProgramRequest', -'GetRegionRequest', -'GetShippingSettingsRequest', -'GetTermsOfServiceAgreementStateRequest', -'GetTermsOfServiceRequest', -'GetUserRequest', -'Headers', -'Homepage', -'HomepageServiceClient', -'InsertShippingSettingsRequest', -'ListAccountIssuesRequest', -'ListAccountIssuesResponse', -'ListAccountTaxRequest', -'ListAccountTaxResponse', -'ListAccountsRequest', -'ListAccountsResponse', -'ListOnlineReturnPoliciesRequest', -'ListOnlineReturnPoliciesResponse', -'ListProgramsRequest', -'ListProgramsResponse', -'ListRegionsRequest', -'ListRegionsResponse', -'ListSubAccountsRequest', -'ListSubAccountsResponse', -'ListUsersRequest', -'ListUsersResponse', -'LocationIdSet', -'MinimumOrderValueTable', -'OnlineReturnPolicy', -'OnlineReturnPolicyServiceClient', -'PhoneVerificationState', -'Program', -'ProgramsServiceClient', -'RateGroup', -'Region', -'RegionsServiceClient', -'Required', -'RetrieveForApplicationTermsOfServiceAgreementStateRequest', -'RetrieveLatestTermsOfServiceRequest', -'Row', -'Service', -'ShippingSettings', -'ShippingSettingsServiceClient', -'Table', -'TaxRule', -'TermsOfService', -'TermsOfServiceAgreementState', -'TermsOfServiceAgreementStateServiceClient', -'TermsOfServiceKind', -'TermsOfServiceServiceClient', -'TransitTable', -'UnclaimHomepageRequest', -'UpdateAccountRequest', -'UpdateAccountTaxRequest', -'UpdateAutofeedSettingsRequest', -'UpdateBusinessIdentityRequest', -'UpdateBusinessInfoRequest', -'UpdateEmailPreferencesRequest', -'UpdateHomepageRequest', -'UpdateRegionRequest', -'UpdateUserRequest', -'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 2e91ad70f4fb..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/gapic_metadata.json +++ /dev/null @@ -1,969 +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" - ] - } - } - } - } - }, - "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" - ] - } - } - } - } - }, - "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" - ] - } - } - } - } - }, - "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" - ] - } - } - } - } - }, - "OnlineReturnPolicyService": { - "clients": { - "grpc": { - "libraryClient": "OnlineReturnPolicyServiceClient", - "rpcs": { - "GetOnlineReturnPolicy": { - "methods": [ - "get_online_return_policy" - ] - }, - "ListOnlineReturnPolicies": { - "methods": [ - "list_online_return_policies" - ] - } - } - }, - "grpc-async": { - "libraryClient": "OnlineReturnPolicyServiceAsyncClient", - "rpcs": { - "GetOnlineReturnPolicy": { - "methods": [ - "get_online_return_policy" - ] - }, - "ListOnlineReturnPolicies": { - "methods": [ - "list_online_return_policies" - ] - } - } - }, - "rest": { - "libraryClient": "OnlineReturnPolicyServiceClient", - "rpcs": { - "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/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 558c8aab67c5..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 deleted file mode 100644 index 266769df6234..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 e9503e61c4e8..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,381 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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__) - - -__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 909711ad55d2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/client.py +++ /dev/null @@ -1,725 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -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 - -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 - - @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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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__) - - -__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 ca38590648cd..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 7d3ac1a8d330..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 532331ca04e4..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,154 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -from google.shopping.merchant_accounts_v1beta.types import accountissue - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__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 bb4547d3b27f..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,348 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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": 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 117c3d45e9cf..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 94e482233831..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,326 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -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}", -) - - -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 - - Override in a subclass to manipulate the response - after it is returned by the AccountIssueService server but before - it is returned to user code. - """ - return response - - -@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) - 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 628a4b21d9db..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 dc7ccee2a580..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 9faa031fb5ed..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,616 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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. - has_flattened_params = any([account_tax, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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__) - - -__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 0e8d18d36bd8..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/client.py +++ /dev/null @@ -1,949 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -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 - -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 - - @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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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. - has_flattened_params = any([account_tax, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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__) - - -__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 57914d3f1844..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 fd12652efc95..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 6ba9fea502e2..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,183 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -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__) - - -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 21f42661e594..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,408 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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": 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 17793cd138a7..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 70655f66c5d8..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,648 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -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}", -) - - -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 - - Override in a subclass to manipulate the response - after it is returned by the AccountTaxService server but before - it is returned to user code. - """ - return response - - 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 - - Override in a subclass to manipulate the response - after it is returned by the AccountTaxService server but before - it is returned to user code. - """ - return response - - 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 - - Override in a subclass to manipulate the response - after it is returned by the AccountTaxService server but before - it is returned to user code. - """ - return response - - -@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) - 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) - 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) - 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 b59c5110eb06..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 deleted file mode 100644 index cb03ea8db3a4..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 deleted file mode 100644 index 4cded9f2e2ae..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/async_client.py +++ /dev/null @@ -1,886 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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. - has_flattened_params = any([account, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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. - has_flattened_params = any([provider]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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__) - - -__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 07475ab32691..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/client.py +++ /dev/null @@ -1,1236 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -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 - -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 - - @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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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. - has_flattened_params = any([account, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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. - has_flattened_params = any([provider]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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__) - - -__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 6356d2d27050..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/__init__.py deleted file mode 100644 index 505cf532d8d3..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 deleted file mode 100644 index 7b3e8374c54b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/base.py +++ /dev/null @@ -1,225 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -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__) - - -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 8418472b4fd1..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/grpc.py +++ /dev/null @@ -1,502 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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": 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 a3ea31567fff..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 775fd9064497..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/rest.py +++ /dev/null @@ -1,1040 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -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}", -) - - -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 - - Override in a subclass to manipulate the response - after it is returned by the AccountsService server but before - it is returned to user code. - """ - return response - - 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 - - Override in a subclass to manipulate the response - after it is returned by the AccountsService server but before - it is returned to user code. - """ - return response - - 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 - - Override in a subclass to manipulate the response - after it is returned by the AccountsService server but before - it is returned to user code. - """ - return response - - 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 - - Override in a subclass to manipulate the response - after it is returned by the AccountsService server but before - it is returned to user code. - """ - return response - - 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 - - Override in a subclass to manipulate the response - after it is returned by the AccountsService server but before - it is returned to user code. - """ - return response - - -@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) - 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) - 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) - 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) - 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) - 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 8a547efca106..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 deleted file mode 100644 index 079803161c63..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 deleted file mode 100644 index af945a48f410..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,487 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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. - has_flattened_params = any([autofeed_settings, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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__) - - -__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 18ea9e4ac96a..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/client.py +++ /dev/null @@ -1,821 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -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 - -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 - - @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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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. - has_flattened_params = any([autofeed_settings, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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__) - - -__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/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/__init__.py deleted file mode 100644 index f77c8df5619d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 deleted file mode 100644 index 79fd8e040bd9..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,168 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -from google.shopping.merchant_accounts_v1beta.types import autofeedsettings - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__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 a0358f56213b..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,375 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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": 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 705eacb0c8d5..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 8236dac96ef3..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,488 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -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}", -) - - -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 - - Override in a subclass to manipulate the response - after it is returned by the AutofeedSettingsService server but before - it is returned to user code. - """ - return response - - 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 - - Override in a subclass to manipulate the response - after it is returned by the AutofeedSettingsService server but before - it is returned to user code. - """ - return response - - -@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) - 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) - 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 243dd3a73556..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/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 c720f6ef6465..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 3fc16718c2dc..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,482 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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. - has_flattened_params = any([business_identity, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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__) - - -__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 8c285b247d01..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/client.py +++ /dev/null @@ -1,816 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -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 - -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 - - @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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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. - has_flattened_params = any([business_identity, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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__) - - -__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 331360c90e76..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 04147a3cf376..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,168 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -from google.shopping.merchant_accounts_v1beta.types import businessidentity - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__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 b842c052ef2f..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,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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": 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 0494ae9d2304..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 449743d9e404..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,486 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -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}", -) - - -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 - - Override in a subclass to manipulate the response - after it is returned by the BusinessIdentityService server but before - it is returned to user code. - """ - return response - - 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 - - Override in a subclass to manipulate the response - after it is returned by the BusinessIdentityService server but before - it is returned to user code. - """ - return response - - -@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) - 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) - 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 dd2ca0b66710..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 deleted file mode 100644 index ceb79842fbe1..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 deleted file mode 100644 index 101f2e6168bd..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,482 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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. - has_flattened_params = any([business_info, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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__) - - -__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 a0f87fdc71e7..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/client.py +++ /dev/null @@ -1,816 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -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 - -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 - - @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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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. - has_flattened_params = any([business_info, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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__) - - -__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/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/__init__.py deleted file mode 100644 index 274100f41ddd..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 deleted file mode 100644 index 7e60c990d585..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,168 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -from google.shopping.merchant_accounts_v1beta.types import businessinfo - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__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 83df498315db..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,374 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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": 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 f5f481ad4dd3..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 bf369d8b06a5..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,483 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -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}", -) - - -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 - - Override in a subclass to manipulate the response - after it is returned by the BusinessInfoService server but before - it is returned to user code. - """ - return response - - 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 - - Override in a subclass to manipulate the response - after it is returned by the BusinessInfoService server but before - it is returned to user code. - """ - return response - - -@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) - 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) - 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 9dd05d0d0e84..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/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 3b89b734458b..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 2025e9f6ab65..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,505 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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. - has_flattened_params = any([email_preferences, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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__) - - -__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 9af5ad2142ad..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/client.py +++ /dev/null @@ -1,839 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -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 - -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 - - @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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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. - has_flattened_params = any([email_preferences, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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__) - - -__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/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/__init__.py deleted file mode 100644 index bfac5d58e755..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 deleted file mode 100644 index ec960b5edb80..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,168 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -from google.shopping.merchant_accounts_v1beta.types import emailpreferences - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__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 437d3cfdfa0e..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,391 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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": 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 9f1da19e5162..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 e92910584cb3..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,494 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -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}", -) - - -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 - - Override in a subclass to manipulate the response - after it is returned by the EmailPreferencesService server but before - it is returned to user code. - """ - return response - - 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 - - Override in a subclass to manipulate the response - after it is returned by the EmailPreferencesService server but before - it is returned to user code. - """ - return response - - -@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) - 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) - 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 68848b7d725f..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/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 7663facd372f..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 f32e8c0c1c55..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/async_client.py +++ /dev/null @@ -1,652 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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. - has_flattened_params = any([homepage, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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__) - - -__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 d08371ef6aa8..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/client.py +++ /dev/null @@ -1,986 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -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 - -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 - - @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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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. - has_flattened_params = any([homepage, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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__) - - -__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 95447852f5f7..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 54662840fef4..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/base.py +++ /dev/null @@ -1,197 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -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__) - - -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 a78f5f24bddd..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/grpc.py +++ /dev/null @@ -1,440 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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": 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 88fd8df21b64..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 dfe9e111d0a5..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/rest.py +++ /dev/null @@ -1,786 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -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}", -) - - -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 - - Override in a subclass to manipulate the response - after it is returned by the HomepageService server but before - it is returned to user code. - """ - return response - - 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 - - Override in a subclass to manipulate the response - after it is returned by the HomepageService server but before - it is returned to user code. - """ - return response - - 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 - - Override in a subclass to manipulate the response - after it is returned by the HomepageService server but before - it is returned to user code. - """ - return response - - 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 - - Override in a subclass to manipulate the response - after it is returned by the HomepageService server but before - it is returned to user code. - """ - return response - - -@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) - 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) - 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) - 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) - 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 7a2a3cda1a43..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/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 49d3ae985198..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 2f537ce3aec3..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,495 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -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.online_return_policy_service import pagers -from google.shopping.merchant_accounts_v1beta.types import 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][google.shopping.merchant.accounts.v1.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. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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 __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__) - - -__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 55ded2bab7e1..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,829 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -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 - -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.online_return_policy_service import pagers -from google.shopping.merchant_accounts_v1beta.types import 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][google.shopping.merchant.accounts.v1.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 - - @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. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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 __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__) - - -__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 03ddb28ea678..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 185a1b964bb8..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 a9cbe075a021..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,168 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -from google.shopping.merchant_accounts_v1beta.types import online_return_policy - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__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, - ), - } - - 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 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 0c232f858e54..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,380 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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": 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][google.shopping.merchant.accounts.v1.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. - - 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. - - 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'] - - 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 54ea1d39efee..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,405 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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][google.shopping.merchant.accounts.v1.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. - - 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. - - 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'] - - 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, - ), - } - - 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 ef4f8dd6fcc2..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,492 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -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 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}", -) - - -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_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_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 - - Override in a subclass to manipulate the response - after it is returned by the OnlineReturnPolicyService server but before - it is returned to user code. - """ - return response - - 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 - - Override in a subclass to manipulate the response - after it is returned by the OnlineReturnPolicyService server but before - it is returned to user code. - """ - return response - - -@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][google.shopping.merchant.accounts.v1.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 _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) - 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) - 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 - - @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/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 d34308a0f56e..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,165 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.shopping.merchant_accounts_v1beta.types import 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 _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 - - -__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 deleted file mode 100644 index 54ae601f5e5f..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 deleted file mode 100644 index ba66bd9b1c76..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/async_client.py +++ /dev/null @@ -1,732 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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__) - - -__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 43046d235b6e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/client.py +++ /dev/null @@ -1,1064 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -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 - -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 - - @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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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__) - - -__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 7e1cf40e5eb3..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/__init__.py deleted file mode 100644 index 5346fb704ec9..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 deleted file mode 100644 index d08a04b549f7..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/base.py +++ /dev/null @@ -1,196 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -from google.shopping.merchant_accounts_v1beta.types import programs - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__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 45c96b2f5d6d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/grpc.py +++ /dev/null @@ -1,438 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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": 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 05fb658e1ac8..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 6c37f016a260..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/rest.py +++ /dev/null @@ -1,825 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -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}", -) - - -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 - - Override in a subclass to manipulate the response - after it is returned by the ProgramsService server but before - it is returned to user code. - """ - return response - - 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 - - Override in a subclass to manipulate the response - after it is returned by the ProgramsService server but before - it is returned to user code. - """ - return response - - 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 - - Override in a subclass to manipulate the response - after it is returned by the ProgramsService server but before - it is returned to user code. - """ - return response - - 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 - - Override in a subclass to manipulate the response - after it is returned by the ProgramsService server but before - it is returned to user code. - """ - return response - - -@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) - 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) - 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) - 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) - 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 d655a4dd9c23..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 3a01b7c4e379..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 aab517b9c5be..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/async_client.py +++ /dev/null @@ -1,838 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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. - has_flattened_params = any([parent, region, region_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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. - has_flattened_params = any([region, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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__) - - -__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 c525551dbb89..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/client.py +++ /dev/null @@ -1,1178 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -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 - -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 - - @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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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. - has_flattened_params = any([parent, region, region_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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. - has_flattened_params = any([region, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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__) - - -__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 97a6b74f8db0..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/__init__.py deleted file mode 100644 index 2a572b340874..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 deleted file mode 100644 index 4f87d6c90f91..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/base.py +++ /dev/null @@ -1,211 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -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__) - - -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 8c66faf52e80..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/grpc.py +++ /dev/null @@ -1,460 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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": 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 4e9d5ca02979..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 515315bffc21..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/rest.py +++ /dev/null @@ -1,916 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -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}", -) - - -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 - - Override in a subclass to manipulate the response - after it is returned by the RegionsService server but before - it is returned to user code. - """ - return response - - 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 - - Override in a subclass to manipulate the response - after it is returned by the RegionsService server but before - it is returned to user code. - """ - return response - - 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 - - Override in a subclass to manipulate the response - after it is returned by the RegionsService server but before - it is returned to user code. - """ - return response - - 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 - - Override in a subclass to manipulate the response - after it is returned by the RegionsService server but before - it is returned to user code. - """ - return response - - -@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) - 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) - 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) - 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) - 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 5cc267d8dbfd..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 fa901053fc1c..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 1a45b3ddf30a..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,456 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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__) - - -__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 7d5c4d4a00c4..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/client.py +++ /dev/null @@ -1,791 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -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 - -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 - - @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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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__) - - -__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 8aeb06735a46..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 ebd259ebf3f0..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,168 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -from google.shopping.merchant_accounts_v1beta.types import shippingsettings - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__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 15c67b475038..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,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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": 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 86019f047c2b..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 5117048f626b..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,485 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -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}", -) - - -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 - - Override in a subclass to manipulate the response - after it is returned by the ShippingSettingsService server but before - it is returned to user code. - """ - return response - - 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 - - Override in a subclass to manipulate the response - after it is returned by the ShippingSettingsService server but before - it is returned to user code. - """ - return response - - -@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) - 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) - 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 0bbaf23e8edc..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 cfe172e0b198..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 fc9d58453ea2..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,530 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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__) - - -__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 12c15168100e..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,882 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -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 - -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 - - @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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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__) - - -__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 4393be637fb9..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 f809d493d988..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,168 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -from google.shopping.merchant_accounts_v1beta.types import termsofserviceagreementstate - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__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 27b8885f55d5..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,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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": 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 3acaed44b44a..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 9558c58cfc1b..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,537 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -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}", -) - - -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 - - Override in a subclass to manipulate the response - after it is returned by the TermsOfServiceAgreementStateService server but before - it is returned to user code. - """ - return response - - 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 - - Override in a subclass to manipulate the response - after it is returned by the TermsOfServiceAgreementStateService server but before - it is returned to user code. - """ - return response - - -@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) - 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) - 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 7406306d5a45..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 0cfe241dba09..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 030a3dab3ead..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,537 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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__) - - -__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 c15b6a74b682..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,880 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -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 - -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 - - @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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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__) - - -__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 1f834296e0ab..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 1af8eed547b8..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,183 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -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__) - - -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 43be17d82f5c..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,404 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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": 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 9b1c9d1a9baa..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 b401dd92c3b8..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,584 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -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}", -) - - -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 - - Override in a subclass to manipulate the response - after it is returned by the TermsOfServiceService server but before - it is returned to user code. - """ - return response - - 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 - - Override in a subclass to manipulate the response - after it is returned by the TermsOfServiceService server but before - it is returned to user code. - """ - return response - - -@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) - 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) - 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 d61a64f98e4b..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 5367640a86a5..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 cfd38f521157..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/async_client.py +++ /dev/null @@ -1,818 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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. - has_flattened_params = any([parent, user]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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. - has_flattened_params = any([user, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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__) - - -__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 c695f01ed825..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/client.py +++ /dev/null @@ -1,1158 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -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 - -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 - - @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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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. - has_flattened_params = any([parent, user]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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. - has_flattened_params = any([user, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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__) - - -__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 b9cddefd01aa..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 028705f02f0c..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 7da483265bab..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/base.py +++ /dev/null @@ -1,212 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -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__) - - -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 c85680b7e0ec..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/grpc.py +++ /dev/null @@ -1,456 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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": 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 a9a8b7ddf427..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 a49dbc0f998d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/rest.py +++ /dev/null @@ -1,895 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -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}", -) - - -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 - - Override in a subclass to manipulate the response - after it is returned by the UserService server but before - it is returned to user code. - """ - return response - - 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 - - Override in a subclass to manipulate the response - after it is returned by the UserService server but before - it is returned to user code. - """ - return response - - 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 - - Override in a subclass to manipulate the response - after it is returned by the UserService server but before - it is returned to user code. - """ - return response - - 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 - - Override in a subclass to manipulate the response - after it is returned by the UserService server but before - it is returned to user code. - """ - return response - - -@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) - 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) - 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) - 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) - 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 5e1474d1c78b..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 ea23eb6e2954..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/__init__.py +++ /dev/null @@ -1,248 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 .businessidentity import ( - BusinessIdentity, - GetBusinessIdentityRequest, - UpdateBusinessIdentityRequest, -) -from .businessinfo import ( - BusinessInfo, - GetBusinessInfoRequest, - UpdateBusinessInfoRequest, -) -from .customerservice import ( - CustomerService, -) -from .emailpreferences import ( - EmailPreferences, - GetEmailPreferencesRequest, - UpdateEmailPreferencesRequest, -) -from .homepage import ( - ClaimHomepageRequest, - GetHomepageRequest, - Homepage, - UnclaimHomepageRequest, - UpdateHomepageRequest, -) -from .online_return_policy import ( - 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 .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', - 'BusinessIdentity', - 'GetBusinessIdentityRequest', - 'UpdateBusinessIdentityRequest', - 'BusinessInfo', - 'GetBusinessInfoRequest', - 'UpdateBusinessInfoRequest', - 'CustomerService', - 'EmailPreferences', - 'GetEmailPreferencesRequest', - 'UpdateEmailPreferencesRequest', - 'ClaimHomepageRequest', - 'GetHomepageRequest', - 'Homepage', - 'UnclaimHomepageRequest', - 'UpdateHomepageRequest', - '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', - '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 754ebc65ee0e..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 94795715b3e8..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 5883b13df300..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 0b3a362e2bef..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 b14c5cfc61a1..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 4383692d8ccd..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/businessidentity.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/businessidentity.py deleted file mode 100644 index 3e590207367f..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 f7a342780cbf..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/customerservice.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/customerservice.py deleted file mode 100644 index 09c919f682c2..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 61fea52c8d1f..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/homepage.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/homepage.py deleted file mode 100644 index a8bfd8550b31..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/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 1cb4f330d0b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/online_return_policy.py +++ /dev/null @@ -1,405 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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={ - 'GetOnlineReturnPolicyRequest', - '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 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): - 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]): - 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): - The return policy. - restocking_fee (google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy.RestockingFee): - 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]): - 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]): - 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): - The return shipping fee. Should be set only - when customer need to download and print the - return label. - return_policy_uri (str): - 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): - This field specifies if merchant only accepts - defective products for returns, and this field - is required. - - This field is a member of `oneof`_ ``_accept_defective_only``. - process_refund_days (int): - The field specifies the number of days it - takes for merchants to process refunds, field is - optional. - - This field is a member of `oneof`_ ``_process_refund_days``. - accept_exchange (bool): - This field specifies if merchant allows - customers to exchange products, this field is - required. - - This field is a member of `oneof`_ ``_accept_exchange``. - """ - 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 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): - 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, - ) - - 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, - ) - 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, - ) - - -__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 65d576169d52..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 a4ff77a9cbd1..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 1d8c28848f9c..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 49cb31fe9c2b..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 28bee59aae61..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 99e929d02081..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 ca3a0d6ebb90..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 52f6fb1fa16a..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 b79f03472590..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 4263f2250023..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/noxfile.py +++ /dev/null @@ -1,280 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", - "3.12", - "3.13", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = 'google-shopping-merchant-accounts' - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.13" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "prerelease_deps", -] - -@nox.session(python=ALL_PYTHON) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def unit(session, protobuf_implementation): - """Run the unit test suite.""" - - 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+") - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") - - # 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") - - session.run( - 'py.test', - '--quiet', - '--cov=google/shopping/merchant_accounts_v1beta/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - -@nox.session(python=ALL_PYTHON[-1]) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def prerelease_deps(session, protobuf_implementation): - """Run the unit test suite against pre-release versions of dependencies.""" - - 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 test environment dependencies - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - - # Install the package without dependencies - session.install('-e', '.', '--no-deps') - - # We test the minimum dependency versions using the minimum Python - # version so the lowest python runtime that we test has a corresponding constraints - # file, located at `testing/constraints--.txt`, which contains all of the - # 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 - ) - ] - - session.install(*constraints_deps) - - prerel_deps = [ - "googleapis-common-protos", - "google-api-core", - "google-auth", - # Exclude grpcio!=1.67.0rc1 which does not support python 3.13 - "grpcio!=1.67.0rc1", - "grpcio-status", - "protobuf", - "proto-plus", - ] - - for dep in prerel_deps: - session.install("--pre", "--no-deps", "--upgrade", dep) - - # Remaining dependencies - other_deps = [ - "requests", - ] - session.install(*other_deps) - - # Print out prerelease package versions - - session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") - session.run("python", "-c", "import google.auth; print(google.auth.__version__)") - session.run("python", "-c", "import grpc; print(grpc.__version__)") - session.run( - "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" - ) - session.run( - "python", "-c", "import proto; print(proto.__version__)" - ) - - session.run( - 'py.test', - '--quiet', - '--cov=google/shopping/merchant_accounts_v1beta/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - - -@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=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 docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==7.0.1", "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=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", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) 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 5722ba346d36..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 65df4005dfdf..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 72f642dd82c3..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 06126d7f847f..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 a33b7617b4d6..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 c03510d4a8d0..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 9e0fa6b733f1..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 d0fc79fce477..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 0f317ab185f3..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 7fc130048baa..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 5325080df363..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 e22bf5b78853..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 7df8d70104f2..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 bb4d4006ad51..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 490f8a95ab51..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 61e728a1ec1d..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 64c1620e14b1..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 f0e31a111510..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 ad622e5013b6..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 9d9c51fc483b..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 d207adb015ce..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 d0cadcbcce63..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 68d50c7746e8..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 98f5f24a8c97..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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 8637e25620b7..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 235ce1598afa..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 089129c55615..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 b44f9ec5d2bf..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 15a59aa09700..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 0e27da028a6e..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 fdefa869c879..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 27702757d482..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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 9f26a449a0c3..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 30fb5c58c714..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 24812e4eca3a..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 12030b2c4e83..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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 17dc74c7d647..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 1ba1650aaccc..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 b098778ce5f9..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 f61ef0d4a6ec..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 e8a1f01c1c48..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 3f1b53762486..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 46218f36725d..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 4e43a500a08e..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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 cb00645bdc37..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 c9390dec8f0f..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 0e74c48947e7..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 26e715bdb847..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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 8a9d70bedb0e..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 6c2c98163a78..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 819600faa170..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 99292b26bd59..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 970c08050862..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 3e9f77650ab4..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 d0db1b835c94..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 9adaa3cdd367..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 7780f650a625..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 ab3f7a11f344..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 56093b2280b2..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 551e26a180d2..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 d62409ec8d9c..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 55d6dd0fc8d4..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 a3e8a1dfdb63..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 bbe022c4a0d4..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 f81c160ad52a..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 d280034963fd..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 46fc3d734b0b..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 2d5a2e5a10ab..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 a2c94110d1ab..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 59a1ff9da8d8..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 1dc53b7d9cca..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 b9f49f6bf873..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 6920a1e22519..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 acd3fb9382ba..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 f5cb63fabba4..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 12311a6c102d..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 e6038b8b6dbf..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 9bcf47546578..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 918d61da5083..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 afb5673b7735..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 5d4bf482dfc6..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 7c17505acc95..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 34e267d75fb7..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 6cae572837e2..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 c41cdd33e146..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 6075da0fd471..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 cf6db7d5238e..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 b9a963bd4995..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 e8d801d3ffcb..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 e66e4bcdc87e..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 c736f9d3c831..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.accounts.v1beta.json +++ /dev/null @@ -1,7284 +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.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.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.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.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.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 a7c0d0a5f668..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/scripts/fixup_merchant_accounts_v1beta_keywords.py +++ /dev/null @@ -1,220 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_region': ('parent', 'region_id', 'region', ), - 'create_user': ('parent', 'user_id', 'user', ), - 'delete_account': ('name', 'force', ), - 'delete_region': ('name', ), - 'delete_user': ('name', ), - 'disable_program': ('name', ), - 'enable_program': ('name', ), - 'get_account': ('name', ), - 'get_account_tax': ('name', ), - 'get_autofeed_settings': ('name', ), - 'get_business_identity': ('name', ), - 'get_business_info': ('name', ), - 'get_email_preferences': ('name', ), - 'get_homepage': ('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', ), - '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_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', ), - '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_business_identity': ('business_identity', 'update_mask', ), - 'update_business_info': ('business_info', 'update_mask', ), - 'update_email_preferences': ('email_preferences', 'update_mask', ), - 'update_homepage': ('homepage', '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 16452374d8e5..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/setup.py +++ /dev/null @@ -1,99 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.0dev,!=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.0dev,!=2.24.0,!=2.25.0", - "proto-plus >= 1.22.3, <2.0.0dev", - "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'", - "protobuf>=3.20.2,<6.0.0dev,!=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.0dev", -] -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 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/testing/constraints-3.13.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.7.txt b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/testing/constraints-3.7.txt deleted file mode 100644 index 130a0c0f80ab..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.0dev", -# 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 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 7b3de3117f38..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 7b3de3117f38..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 0613303422bb..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_account_issue_service.py +++ /dev/null @@ -1,2368 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -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("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, "pre_list_account_issues") as pre: - pre.assert_not_called() - post.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() - - client.list_account_issues(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.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 cdaf84a4908e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_account_tax_service.py +++ /dev/null @@ -1,3745 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -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("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, "pre_get_account_tax") as pre: - pre.assert_not_called() - post.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() - - client.get_account_tax(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.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, "pre_list_account_tax") as pre: - pre.assert_not_called() - post.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() - - client.list_account_tax(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.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, "pre_update_account_tax") as pre: - pre.assert_not_called() - post.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() - - client.update_account_tax(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.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 bf85eeb78b34..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_accounts_service.py +++ /dev/null @@ -1,5584 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -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("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, "pre_get_account") as pre: - pre.assert_not_called() - post.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() - - client.get_account(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.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, "pre_create_and_configure_account") as pre: - pre.assert_not_called() - post.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() - - client.create_and_configure_account(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.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, "pre_update_account") as pre: - pre.assert_not_called() - post.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() - - client.update_account(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.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, "pre_list_accounts") as pre: - pre.assert_not_called() - post.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() - - client.list_accounts(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.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, "pre_list_sub_accounts") as pre: - pre.assert_not_called() - post.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() - - client.list_sub_accounts(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.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 3b21d628d5b5..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_autofeed_settings_service.py +++ /dev/null @@ -1,2836 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -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("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, "pre_get_autofeed_settings") as pre: - pre.assert_not_called() - post.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() - - client.get_autofeed_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.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, "pre_update_autofeed_settings") as pre: - pre.assert_not_called() - post.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() - - client.update_autofeed_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.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_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 13d76968fa62..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_business_identity_service.py +++ /dev/null @@ -1,2822 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -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("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, "pre_get_business_identity") as pre: - pre.assert_not_called() - post.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() - - client.get_business_identity(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.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, "pre_update_business_identity") as pre: - pre.assert_not_called() - post.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() - - client.update_business_identity(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.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 77de09debf4e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_business_info_service.py +++ /dev/null @@ -1,2840 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -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("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, "pre_get_business_info") as pre: - pre.assert_not_called() - post.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() - - client.get_business_info(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.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, "pre_update_business_info") as pre: - pre.assert_not_called() - post.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() - - client.update_business_info(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.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_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 211d200f402e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_email_preferences_service.py +++ /dev/null @@ -1,2824 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -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("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, "pre_get_email_preferences") as pre: - pre.assert_not_called() - post.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() - - client.get_email_preferences(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.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, "pre_update_email_preferences") as pre: - pre.assert_not_called() - post.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() - - client.update_email_preferences(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.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_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 c5594a3ab51b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_homepage_service.py +++ /dev/null @@ -1,3903 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -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("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, "pre_get_homepage") as pre: - pre.assert_not_called() - post.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() - - client.get_homepage(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.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, "pre_update_homepage") as pre: - pre.assert_not_called() - post.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() - - client.update_homepage(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.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, "pre_claim_homepage") as pre: - pre.assert_not_called() - post.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() - - client.claim_homepage(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.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, "pre_unclaim_homepage") as pre: - pre.assert_not_called() - post.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() - - client.unclaim_homepage(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.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_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 a1577750c65b..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,3064 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.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 -import google.auth - - -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("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, - ) - 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 - - -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, - )) - 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 - - -@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 - - -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_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 - - -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, - )) - 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 - - -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, - ) - - # 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 - - -@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, "pre_get_online_return_policy") as pre: - pre.assert_not_called() - post.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() - - client.get_online_return_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.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, "pre_list_online_return_policies") as pre: - pre.assert_not_called() - post.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() - - client.list_online_return_policies(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.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 - - -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', - ) - 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 -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 fa7b0e226a28..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_programs_service.py +++ /dev/null @@ -1,4373 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -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("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, "pre_get_program") as pre: - pre.assert_not_called() - post.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() - - client.get_program(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.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, "pre_list_programs") as pre: - pre.assert_not_called() - post.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() - - client.list_programs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.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, "pre_enable_program") as pre: - pre.assert_not_called() - post.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() - - client.enable_program(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.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, "pre_disable_program") as pre: - pre.assert_not_called() - post.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() - - client.disable_program(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.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 34411b7adaa9..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_regions_service.py +++ /dev/null @@ -1,5154 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -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("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, "pre_get_region") as pre: - pre.assert_not_called() - post.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() - - client.get_region(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.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, "pre_create_region") as pre: - pre.assert_not_called() - post.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() - - client.create_region(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.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, "pre_update_region") as pre: - pre.assert_not_called() - post.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() - - client.update_region(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.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, "pre_list_regions") as pre: - pre.assert_not_called() - post.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() - - client.list_regions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.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 13390f0eef2e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_shipping_settings_service.py +++ /dev/null @@ -1,2679 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -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("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, "pre_get_shipping_settings") as pre: - pre.assert_not_called() - post.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() - - client.get_shipping_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.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, "pre_insert_shipping_settings") as pre: - pre.assert_not_called() - post.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() - - client.insert_shipping_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.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 71aded2117e2..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,2800 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -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("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, "pre_get_terms_of_service_agreement_state") as pre: - pre.assert_not_called() - post.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() - - client.get_terms_of_service_agreement_state(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.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, "pre_retrieve_for_application_terms_of_service_agreement_state") as pre: - pre.assert_not_called() - post.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() - - client.retrieve_for_application_terms_of_service_agreement_state(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.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 92972500297c..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,3277 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -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("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, "pre_get_terms_of_service") as pre: - pre.assert_not_called() - post.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() - - client.get_terms_of_service(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.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, "pre_retrieve_latest_terms_of_service") as pre: - pre.assert_not_called() - post.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() - - client.retrieve_latest_terms_of_service(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.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 a03be666c985..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_user_service.py +++ /dev/null @@ -1,5164 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -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("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, "pre_get_user") as pre: - pre.assert_not_called() - post.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() - - client.get_user(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.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, "pre_create_user") as pre: - pre.assert_not_called() - post.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() - - client.create_user(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.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, "pre_update_user") as pre: - pre.assert_not_called() - post.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() - - client.update_user(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.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, "pre_list_users") as pre: - pre.assert_not_called() - post.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() - - client.list_users(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.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/owl-bot-staging/google-shopping-merchant-conversions/v1beta/.coveragerc b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/.coveragerc deleted file mode 100644 index e78537d68443..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/shopping/merchant_conversions/__init__.py - google/shopping/merchant_conversions/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-conversions/v1beta/.flake8 b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/MANIFEST.in b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/MANIFEST.in deleted file mode 100644 index ef3463ac8c12..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/shopping/merchant_conversions *.py -recursive-include google/shopping/merchant_conversions_v1beta *.py diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/README.rst b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/README.rst deleted file mode 100644 index 66f641dd8095..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Shopping Merchant Conversions 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 Conversions 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 diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/_static/custom.css b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/_static/custom.css +++ /dev/null @@ -1,3 +0,0 @@ -dl.field-list > dt { - min-width: 100px -} diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/conf.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/conf.py deleted file mode 100644 index a0a048b37435..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-conversions 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("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# 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.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -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-conversions" -copyright = u"2023, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# 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 = 'en' - -# 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"] - -# 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 Python", - "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-conversions-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-conversions.tex", - u"google-shopping-merchant-conversions 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-conversions", - u"Google Shopping Merchant Conversions 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-conversions", - u"google-shopping-merchant-conversions Documentation", - author, - "google-shopping-merchant-conversions", - "GAPIC library for Google Shopping Merchant Conversions API", - "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": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", 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-conversions/v1beta/docs/index.rst b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/index.rst deleted file mode 100644 index 5a1068587e37..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - merchant_conversions_v1beta/services_ - merchant_conversions_v1beta/types_ diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/merchant_conversions_v1beta/conversion_sources_service.rst b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/merchant_conversions_v1beta/conversion_sources_service.rst deleted file mode 100644 index 150c70129c9d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/merchant_conversions_v1beta/conversion_sources_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -ConversionSourcesService ------------------------------------------- - -.. automodule:: google.shopping.merchant_conversions_v1beta.services.conversion_sources_service - :members: - :inherited-members: - -.. automodule:: google.shopping.merchant_conversions_v1beta.services.conversion_sources_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/merchant_conversions_v1beta/services_.rst b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/merchant_conversions_v1beta/services_.rst deleted file mode 100644 index 20f2386f1792..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/merchant_conversions_v1beta/services_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Shopping Merchant Conversions v1beta API -============================================================ -.. toctree:: - :maxdepth: 2 - - conversion_sources_service diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/merchant_conversions_v1beta/types_.rst b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/merchant_conversions_v1beta/types_.rst deleted file mode 100644 index 87217f29174d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/docs/merchant_conversions_v1beta/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Shopping Merchant Conversions v1beta API -========================================================= - -.. automodule:: google.shopping.merchant_conversions_v1beta.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions/__init__.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions/__init__.py deleted file mode 100644 index 74447f78c463..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions/__init__.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_conversions import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.shopping.merchant_conversions_v1beta.services.conversion_sources_service.client import ConversionSourcesServiceClient -from google.shopping.merchant_conversions_v1beta.services.conversion_sources_service.async_client import ConversionSourcesServiceAsyncClient - -from google.shopping.merchant_conversions_v1beta.types.conversionsources import AttributionSettings -from google.shopping.merchant_conversions_v1beta.types.conversionsources import ConversionSource -from google.shopping.merchant_conversions_v1beta.types.conversionsources import CreateConversionSourceRequest -from google.shopping.merchant_conversions_v1beta.types.conversionsources import DeleteConversionSourceRequest -from google.shopping.merchant_conversions_v1beta.types.conversionsources import GetConversionSourceRequest -from google.shopping.merchant_conversions_v1beta.types.conversionsources import GoogleAnalyticsLink -from google.shopping.merchant_conversions_v1beta.types.conversionsources import ListConversionSourcesRequest -from google.shopping.merchant_conversions_v1beta.types.conversionsources import ListConversionSourcesResponse -from google.shopping.merchant_conversions_v1beta.types.conversionsources import MerchantCenterDestination -from google.shopping.merchant_conversions_v1beta.types.conversionsources import UndeleteConversionSourceRequest -from google.shopping.merchant_conversions_v1beta.types.conversionsources import UpdateConversionSourceRequest - -__all__ = ('ConversionSourcesServiceClient', - 'ConversionSourcesServiceAsyncClient', - 'AttributionSettings', - 'ConversionSource', - 'CreateConversionSourceRequest', - 'DeleteConversionSourceRequest', - 'GetConversionSourceRequest', - 'GoogleAnalyticsLink', - 'ListConversionSourcesRequest', - 'ListConversionSourcesResponse', - 'MerchantCenterDestination', - 'UndeleteConversionSourceRequest', - 'UpdateConversionSourceRequest', -) diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions/gapic_version.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-conversions/v1beta/google/shopping/merchant_conversions/py.typed b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions/py.typed deleted file mode 100644 index 5298041b15c6..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-shopping-merchant-conversions package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/__init__.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/__init__.py deleted file mode 100644 index eb3146fd7511..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/__init__.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_conversions_v1beta import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.conversion_sources_service import ConversionSourcesServiceClient -from .services.conversion_sources_service import ConversionSourcesServiceAsyncClient - -from .types.conversionsources import AttributionSettings -from .types.conversionsources import ConversionSource -from .types.conversionsources import CreateConversionSourceRequest -from .types.conversionsources import DeleteConversionSourceRequest -from .types.conversionsources import GetConversionSourceRequest -from .types.conversionsources import GoogleAnalyticsLink -from .types.conversionsources import ListConversionSourcesRequest -from .types.conversionsources import ListConversionSourcesResponse -from .types.conversionsources import MerchantCenterDestination -from .types.conversionsources import UndeleteConversionSourceRequest -from .types.conversionsources import UpdateConversionSourceRequest - -__all__ = ( - 'ConversionSourcesServiceAsyncClient', -'AttributionSettings', -'ConversionSource', -'ConversionSourcesServiceClient', -'CreateConversionSourceRequest', -'DeleteConversionSourceRequest', -'GetConversionSourceRequest', -'GoogleAnalyticsLink', -'ListConversionSourcesRequest', -'ListConversionSourcesResponse', -'MerchantCenterDestination', -'UndeleteConversionSourceRequest', -'UpdateConversionSourceRequest', -) diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/gapic_metadata.json b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/gapic_metadata.json deleted file mode 100644 index 6f24b73d5d87..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/gapic_metadata.json +++ /dev/null @@ -1,118 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.shopping.merchant_conversions_v1beta", - "protoPackage": "google.shopping.merchant.conversions.v1beta", - "schema": "1.0", - "services": { - "ConversionSourcesService": { - "clients": { - "grpc": { - "libraryClient": "ConversionSourcesServiceClient", - "rpcs": { - "CreateConversionSource": { - "methods": [ - "create_conversion_source" - ] - }, - "DeleteConversionSource": { - "methods": [ - "delete_conversion_source" - ] - }, - "GetConversionSource": { - "methods": [ - "get_conversion_source" - ] - }, - "ListConversionSources": { - "methods": [ - "list_conversion_sources" - ] - }, - "UndeleteConversionSource": { - "methods": [ - "undelete_conversion_source" - ] - }, - "UpdateConversionSource": { - "methods": [ - "update_conversion_source" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ConversionSourcesServiceAsyncClient", - "rpcs": { - "CreateConversionSource": { - "methods": [ - "create_conversion_source" - ] - }, - "DeleteConversionSource": { - "methods": [ - "delete_conversion_source" - ] - }, - "GetConversionSource": { - "methods": [ - "get_conversion_source" - ] - }, - "ListConversionSources": { - "methods": [ - "list_conversion_sources" - ] - }, - "UndeleteConversionSource": { - "methods": [ - "undelete_conversion_source" - ] - }, - "UpdateConversionSource": { - "methods": [ - "update_conversion_source" - ] - } - } - }, - "rest": { - "libraryClient": "ConversionSourcesServiceClient", - "rpcs": { - "CreateConversionSource": { - "methods": [ - "create_conversion_source" - ] - }, - "DeleteConversionSource": { - "methods": [ - "delete_conversion_source" - ] - }, - "GetConversionSource": { - "methods": [ - "get_conversion_source" - ] - }, - "ListConversionSources": { - "methods": [ - "list_conversion_sources" - ] - }, - "UndeleteConversionSource": { - "methods": [ - "undelete_conversion_source" - ] - }, - "UpdateConversionSource": { - "methods": [ - "update_conversion_source" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/gapic_version.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-conversions/v1beta/google/shopping/merchant_conversions_v1beta/py.typed b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/py.typed deleted file mode 100644 index 5298041b15c6..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-shopping-merchant-conversions package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/__init__.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/__init__.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/__init__.py deleted file mode 100644 index 25d8d15c4cc5..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 ConversionSourcesServiceClient -from .async_client import ConversionSourcesServiceAsyncClient - -__all__ = ( - 'ConversionSourcesServiceClient', - 'ConversionSourcesServiceAsyncClient', -) diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/async_client.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/async_client.py deleted file mode 100644 index 6a1a53b2bd0c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/async_client.py +++ /dev/null @@ -1,928 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_conversions_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 - - -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 timestamp_pb2 # type: ignore -from google.shopping.merchant_conversions_v1beta.services.conversion_sources_service import pagers -from google.shopping.merchant_conversions_v1beta.types import conversionsources -from .transports.base import ConversionSourcesServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ConversionSourcesServiceGrpcAsyncIOTransport -from .client import ConversionSourcesServiceClient - -try: - from google.api_core import client_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 ConversionSourcesServiceAsyncClient: - """Service for managing conversion sources for a merchant - account. - """ - - _client: ConversionSourcesServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = ConversionSourcesServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ConversionSourcesServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = ConversionSourcesServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = ConversionSourcesServiceClient._DEFAULT_UNIVERSE - - conversion_source_path = staticmethod(ConversionSourcesServiceClient.conversion_source_path) - parse_conversion_source_path = staticmethod(ConversionSourcesServiceClient.parse_conversion_source_path) - common_billing_account_path = staticmethod(ConversionSourcesServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ConversionSourcesServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ConversionSourcesServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(ConversionSourcesServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(ConversionSourcesServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(ConversionSourcesServiceClient.parse_common_organization_path) - common_project_path = staticmethod(ConversionSourcesServiceClient.common_project_path) - parse_common_project_path = staticmethod(ConversionSourcesServiceClient.parse_common_project_path) - common_location_path = staticmethod(ConversionSourcesServiceClient.common_location_path) - parse_common_location_path = staticmethod(ConversionSourcesServiceClient.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: - ConversionSourcesServiceAsyncClient: The constructed client. - """ - return ConversionSourcesServiceClient.from_service_account_info.__func__(ConversionSourcesServiceAsyncClient, 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: - ConversionSourcesServiceAsyncClient: The constructed client. - """ - return ConversionSourcesServiceClient.from_service_account_file.__func__(ConversionSourcesServiceAsyncClient, 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 ConversionSourcesServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ConversionSourcesServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ConversionSourcesServiceTransport: 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 = ConversionSourcesServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, ConversionSourcesServiceTransport, Callable[..., ConversionSourcesServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the conversion sources 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,ConversionSourcesServiceTransport,Callable[..., ConversionSourcesServiceTransport]]]): - 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 ConversionSourcesServiceTransport 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 = ConversionSourcesServiceClient( - 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.conversions_v1beta.ConversionSourcesServiceAsyncClient`.", - extra = { - "serviceName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", - "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.conversions.v1beta.ConversionSourcesService", - "credentialsType": None, - } - ) - - async def create_conversion_source(self, - request: Optional[Union[conversionsources.CreateConversionSourceRequest, dict]] = None, - *, - parent: Optional[str] = None, - conversion_source: Optional[conversionsources.ConversionSource] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> conversionsources.ConversionSource: - r"""Creates a new conversion source. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_conversions_v1beta - - async def sample_create_conversion_source(): - # Create a client - client = merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient() - - # Initialize request argument(s) - conversion_source = merchant_conversions_v1beta.ConversionSource() - conversion_source.google_analytics_link.property_id = 1201 - - request = merchant_conversions_v1beta.CreateConversionSourceRequest( - parent="parent_value", - conversion_source=conversion_source, - ) - - # Make the request - response = await client.create_conversion_source(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_conversions_v1beta.types.CreateConversionSourceRequest, dict]]): - The request object. Request message for the - CreateConversionSource method. - parent (:class:`str`): - Required. The merchant account that - will own the new conversion source. - Format: accounts/{account} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - conversion_source (:class:`google.shopping.merchant_conversions_v1beta.types.ConversionSource`): - Required. The conversion source - description. A new ID will be - automatically assigned to it upon - creation. - - This corresponds to the ``conversion_source`` 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_conversions_v1beta.types.ConversionSource: - Represents a conversion source owned - by a Merchant account. A merchant - account can have up to 200 conversion - sources. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, conversion_source]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, conversionsources.CreateConversionSourceRequest): - request = conversionsources.CreateConversionSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if conversion_source is not None: - request.conversion_source = conversion_source - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_conversion_source] - - # Certain 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_conversion_source(self, - request: Optional[Union[conversionsources.UpdateConversionSourceRequest, dict]] = None, - *, - conversion_source: Optional[conversionsources.ConversionSource] = 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]]] = (), - ) -> conversionsources.ConversionSource: - r"""Updates information of an existing conversion source. - Available only for Merchant Center Destination - conversion sources. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_conversions_v1beta - - async def sample_update_conversion_source(): - # Create a client - client = merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient() - - # Initialize request argument(s) - conversion_source = merchant_conversions_v1beta.ConversionSource() - conversion_source.google_analytics_link.property_id = 1201 - - request = merchant_conversions_v1beta.UpdateConversionSourceRequest( - conversion_source=conversion_source, - ) - - # Make the request - response = await client.update_conversion_source(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_conversions_v1beta.types.UpdateConversionSourceRequest, dict]]): - The request object. Request message for the - UpdateConversionSource method. - conversion_source (:class:`google.shopping.merchant_conversions_v1beta.types.ConversionSource`): - Required. The new version of the conversion source data. - Format: - accounts/{account}/conversionSources/{conversion_source} - - This corresponds to the ``conversion_source`` 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_conversions_v1beta.types.ConversionSource: - Represents a conversion source owned - by a Merchant account. A merchant - account can have up to 200 conversion - sources. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([conversion_source, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, conversionsources.UpdateConversionSourceRequest): - request = conversionsources.UpdateConversionSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if conversion_source is not None: - request.conversion_source = conversion_source - 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_conversion_source] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("conversion_source.name", request.conversion_source.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_conversion_source(self, - request: Optional[Union[conversionsources.DeleteConversionSourceRequest, dict]] = None, - *, - name: Optional[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"""Archives an existing conversion source. If the - conversion source is a Merchant Center Destination, it - will be recoverable for 30 days. If the conversion - source is a Google Analytics Link, it will be deleted - immediately and can be restored by creating a new one. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_conversions_v1beta - - async def sample_delete_conversion_source(): - # Create a client - client = merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_conversions_v1beta.DeleteConversionSourceRequest( - name="name_value", - ) - - # Make the request - await client.delete_conversion_source(request=request) - - Args: - request (Optional[Union[google.shopping.merchant_conversions_v1beta.types.DeleteConversionSourceRequest, dict]]): - The request object. Request message for the - DeleteConversionSource method. - name (:class:`str`): - Required. The name of the conversion source to be - deleted. Format: - accounts/{account}/conversionSources/{conversion_source} - - 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, conversionsources.DeleteConversionSourceRequest): - request = conversionsources.DeleteConversionSourceRequest(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_conversion_source] - - # Certain 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 undelete_conversion_source(self, - request: Optional[Union[conversionsources.UndeleteConversionSourceRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> conversionsources.ConversionSource: - r"""Re-enables an archived conversion source. Only - Available for Merchant Center Destination conversion - sources. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_conversions_v1beta - - async def sample_undelete_conversion_source(): - # Create a client - client = merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_conversions_v1beta.UndeleteConversionSourceRequest( - name="name_value", - ) - - # Make the request - response = await client.undelete_conversion_source(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_conversions_v1beta.types.UndeleteConversionSourceRequest, dict]]): - The request object. Request message for the - UndeleteConversionSource 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_conversions_v1beta.types.ConversionSource: - Represents a conversion source owned - by a Merchant account. A merchant - account can have up to 200 conversion - sources. - - """ - # 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, conversionsources.UndeleteConversionSourceRequest): - request = conversionsources.UndeleteConversionSourceRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.undelete_conversion_source] - - # Certain 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_conversion_source(self, - request: Optional[Union[conversionsources.GetConversionSourceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> conversionsources.ConversionSource: - r"""Fetches a conversion source. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_conversions_v1beta - - async def sample_get_conversion_source(): - # Create a client - client = merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_conversions_v1beta.GetConversionSourceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_conversion_source(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_conversions_v1beta.types.GetConversionSourceRequest, dict]]): - The request object. Request message for the - GetConversionSource method. - name (:class:`str`): - Required. The name of the conversion source to be - fetched. Format: - accounts/{account}/conversionsources/{conversion_source} - - 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_conversions_v1beta.types.ConversionSource: - Represents a conversion source owned - by a Merchant account. A merchant - account can have up to 200 conversion - sources. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, conversionsources.GetConversionSourceRequest): - request = conversionsources.GetConversionSourceRequest(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_conversion_source] - - # Certain 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_conversion_sources(self, - request: Optional[Union[conversionsources.ListConversionSourcesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListConversionSourcesAsyncPager: - r"""Retrieves the list of conversion sources the caller - has access 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_conversions_v1beta - - async def sample_list_conversion_sources(): - # Create a client - client = merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_conversions_v1beta.ListConversionSourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_conversion_sources(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_conversions_v1beta.types.ListConversionSourcesRequest, dict]]): - The request object. Request message for the - ListConversionSources method. - parent (:class:`str`): - Required. The merchant account who - owns the collection of conversion - sources. 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_conversions_v1beta.services.conversion_sources_service.pagers.ListConversionSourcesAsyncPager: - Response message for the - ListConversionSources 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, conversionsources.ListConversionSourcesRequest): - request = conversionsources.ListConversionSourcesRequest(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_conversion_sources] - - # Certain 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.ListConversionSourcesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self) -> "ConversionSourcesServiceAsyncClient": - 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__) - - -__all__ = ( - "ConversionSourcesServiceAsyncClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/client.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/client.py deleted file mode 100644 index c3e986575c99..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/client.py +++ /dev/null @@ -1,1259 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -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_conversions_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 - -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 timestamp_pb2 # type: ignore -from google.shopping.merchant_conversions_v1beta.services.conversion_sources_service import pagers -from google.shopping.merchant_conversions_v1beta.types import conversionsources -from .transports.base import ConversionSourcesServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ConversionSourcesServiceGrpcTransport -from .transports.grpc_asyncio import ConversionSourcesServiceGrpcAsyncIOTransport -from .transports.rest import ConversionSourcesServiceRestTransport - - -class ConversionSourcesServiceClientMeta(type): - """Metaclass for the ConversionSourcesService 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[ConversionSourcesServiceTransport]] - _transport_registry["grpc"] = ConversionSourcesServiceGrpcTransport - _transport_registry["grpc_asyncio"] = ConversionSourcesServiceGrpcAsyncIOTransport - _transport_registry["rest"] = ConversionSourcesServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[ConversionSourcesServiceTransport]: - """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 ConversionSourcesServiceClient(metaclass=ConversionSourcesServiceClientMeta): - """Service for managing conversion sources for a merchant - account. - """ - - @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: - ConversionSourcesServiceClient: 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: - ConversionSourcesServiceClient: 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) -> ConversionSourcesServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ConversionSourcesServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def conversion_source_path(account: str,conversion_source: str,) -> str: - """Returns a fully-qualified conversion_source string.""" - return "accounts/{account}/conversionSources/{conversion_source}".format(account=account, conversion_source=conversion_source, ) - - @staticmethod - def parse_conversion_source_path(path: str) -> Dict[str,str]: - """Parses a conversion_source path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/conversionSources/(?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 = ConversionSourcesServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = ConversionSourcesServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = ConversionSourcesServiceClient._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 = ConversionSourcesServiceClient._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 - - @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, ConversionSourcesServiceTransport, Callable[..., ConversionSourcesServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the conversion sources 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,ConversionSourcesServiceTransport,Callable[..., ConversionSourcesServiceTransport]]]): - 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 ConversionSourcesServiceTransport 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 = ConversionSourcesServiceClient._read_environment_variables() - self._client_cert_source = ConversionSourcesServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = ConversionSourcesServiceClient._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, ConversionSourcesServiceTransport) - if transport_provided: - # transport is a ConversionSourcesServiceTransport 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(ConversionSourcesServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - ConversionSourcesServiceClient._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[ConversionSourcesServiceTransport], Callable[..., ConversionSourcesServiceTransport]] = ( - ConversionSourcesServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., ConversionSourcesServiceTransport], 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.conversions_v1beta.ConversionSourcesServiceClient`.", - extra = { - "serviceName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", - "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.conversions.v1beta.ConversionSourcesService", - "credentialsType": None, - } - ) - - def create_conversion_source(self, - request: Optional[Union[conversionsources.CreateConversionSourceRequest, dict]] = None, - *, - parent: Optional[str] = None, - conversion_source: Optional[conversionsources.ConversionSource] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> conversionsources.ConversionSource: - r"""Creates a new conversion source. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_conversions_v1beta - - def sample_create_conversion_source(): - # Create a client - client = merchant_conversions_v1beta.ConversionSourcesServiceClient() - - # Initialize request argument(s) - conversion_source = merchant_conversions_v1beta.ConversionSource() - conversion_source.google_analytics_link.property_id = 1201 - - request = merchant_conversions_v1beta.CreateConversionSourceRequest( - parent="parent_value", - conversion_source=conversion_source, - ) - - # Make the request - response = client.create_conversion_source(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_conversions_v1beta.types.CreateConversionSourceRequest, dict]): - The request object. Request message for the - CreateConversionSource method. - parent (str): - Required. The merchant account that - will own the new conversion source. - Format: accounts/{account} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - conversion_source (google.shopping.merchant_conversions_v1beta.types.ConversionSource): - Required. The conversion source - description. A new ID will be - automatically assigned to it upon - creation. - - This corresponds to the ``conversion_source`` 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_conversions_v1beta.types.ConversionSource: - Represents a conversion source owned - by a Merchant account. A merchant - account can have up to 200 conversion - sources. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, conversion_source]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, conversionsources.CreateConversionSourceRequest): - request = conversionsources.CreateConversionSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if conversion_source is not None: - request.conversion_source = conversion_source - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_conversion_source] - - # Certain 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_conversion_source(self, - request: Optional[Union[conversionsources.UpdateConversionSourceRequest, dict]] = None, - *, - conversion_source: Optional[conversionsources.ConversionSource] = 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]]] = (), - ) -> conversionsources.ConversionSource: - r"""Updates information of an existing conversion source. - Available only for Merchant Center Destination - conversion sources. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_conversions_v1beta - - def sample_update_conversion_source(): - # Create a client - client = merchant_conversions_v1beta.ConversionSourcesServiceClient() - - # Initialize request argument(s) - conversion_source = merchant_conversions_v1beta.ConversionSource() - conversion_source.google_analytics_link.property_id = 1201 - - request = merchant_conversions_v1beta.UpdateConversionSourceRequest( - conversion_source=conversion_source, - ) - - # Make the request - response = client.update_conversion_source(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_conversions_v1beta.types.UpdateConversionSourceRequest, dict]): - The request object. Request message for the - UpdateConversionSource method. - conversion_source (google.shopping.merchant_conversions_v1beta.types.ConversionSource): - Required. The new version of the conversion source data. - Format: - accounts/{account}/conversionSources/{conversion_source} - - This corresponds to the ``conversion_source`` 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_conversions_v1beta.types.ConversionSource: - Represents a conversion source owned - by a Merchant account. A merchant - account can have up to 200 conversion - sources. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([conversion_source, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, conversionsources.UpdateConversionSourceRequest): - request = conversionsources.UpdateConversionSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if conversion_source is not None: - request.conversion_source = conversion_source - 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_conversion_source] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("conversion_source.name", request.conversion_source.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_conversion_source(self, - request: Optional[Union[conversionsources.DeleteConversionSourceRequest, dict]] = None, - *, - name: Optional[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"""Archives an existing conversion source. If the - conversion source is a Merchant Center Destination, it - will be recoverable for 30 days. If the conversion - source is a Google Analytics Link, it will be deleted - immediately and can be restored by creating a new one. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_conversions_v1beta - - def sample_delete_conversion_source(): - # Create a client - client = merchant_conversions_v1beta.ConversionSourcesServiceClient() - - # Initialize request argument(s) - request = merchant_conversions_v1beta.DeleteConversionSourceRequest( - name="name_value", - ) - - # Make the request - client.delete_conversion_source(request=request) - - Args: - request (Union[google.shopping.merchant_conversions_v1beta.types.DeleteConversionSourceRequest, dict]): - The request object. Request message for the - DeleteConversionSource method. - name (str): - Required. The name of the conversion source to be - deleted. Format: - accounts/{account}/conversionSources/{conversion_source} - - 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, conversionsources.DeleteConversionSourceRequest): - request = conversionsources.DeleteConversionSourceRequest(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_conversion_source] - - # Certain 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 undelete_conversion_source(self, - request: Optional[Union[conversionsources.UndeleteConversionSourceRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> conversionsources.ConversionSource: - r"""Re-enables an archived conversion source. Only - Available for Merchant Center Destination conversion - sources. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_conversions_v1beta - - def sample_undelete_conversion_source(): - # Create a client - client = merchant_conversions_v1beta.ConversionSourcesServiceClient() - - # Initialize request argument(s) - request = merchant_conversions_v1beta.UndeleteConversionSourceRequest( - name="name_value", - ) - - # Make the request - response = client.undelete_conversion_source(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_conversions_v1beta.types.UndeleteConversionSourceRequest, dict]): - The request object. Request message for the - UndeleteConversionSource method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.shopping.merchant_conversions_v1beta.types.ConversionSource: - Represents a conversion source owned - by a Merchant account. A merchant - account can have up to 200 conversion - sources. - - """ - # 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, conversionsources.UndeleteConversionSourceRequest): - request = conversionsources.UndeleteConversionSourceRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.undelete_conversion_source] - - # Certain 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_conversion_source(self, - request: Optional[Union[conversionsources.GetConversionSourceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> conversionsources.ConversionSource: - r"""Fetches a conversion source. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_conversions_v1beta - - def sample_get_conversion_source(): - # Create a client - client = merchant_conversions_v1beta.ConversionSourcesServiceClient() - - # Initialize request argument(s) - request = merchant_conversions_v1beta.GetConversionSourceRequest( - name="name_value", - ) - - # Make the request - response = client.get_conversion_source(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_conversions_v1beta.types.GetConversionSourceRequest, dict]): - The request object. Request message for the - GetConversionSource method. - name (str): - Required. The name of the conversion source to be - fetched. Format: - accounts/{account}/conversionsources/{conversion_source} - - 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_conversions_v1beta.types.ConversionSource: - Represents a conversion source owned - by a Merchant account. A merchant - account can have up to 200 conversion - sources. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, conversionsources.GetConversionSourceRequest): - request = conversionsources.GetConversionSourceRequest(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_conversion_source] - - # Certain 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_conversion_sources(self, - request: Optional[Union[conversionsources.ListConversionSourcesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListConversionSourcesPager: - r"""Retrieves the list of conversion sources the caller - has access 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_conversions_v1beta - - def sample_list_conversion_sources(): - # Create a client - client = merchant_conversions_v1beta.ConversionSourcesServiceClient() - - # Initialize request argument(s) - request = merchant_conversions_v1beta.ListConversionSourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_conversion_sources(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.shopping.merchant_conversions_v1beta.types.ListConversionSourcesRequest, dict]): - The request object. Request message for the - ListConversionSources method. - parent (str): - Required. The merchant account who - owns the collection of conversion - sources. 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_conversions_v1beta.services.conversion_sources_service.pagers.ListConversionSourcesPager: - Response message for the - ListConversionSources 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, conversionsources.ListConversionSourcesRequest): - request = conversionsources.ListConversionSourcesRequest(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_conversion_sources] - - # Certain 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.ListConversionSourcesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "ConversionSourcesServiceClient": - 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__) - - -__all__ = ( - "ConversionSourcesServiceClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/pagers.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/pagers.py deleted file mode 100644 index 13496d2bfaca..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/pagers.py +++ /dev/null @@ -1,166 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_conversions_v1beta.types import conversionsources - - -class ListConversionSourcesPager: - """A pager for iterating through ``list_conversion_sources`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_conversions_v1beta.types.ListConversionSourcesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``conversion_sources`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListConversionSources`` requests and continue to iterate - through the ``conversion_sources`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_conversions_v1beta.types.ListConversionSourcesResponse` - 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[..., conversionsources.ListConversionSourcesResponse], - request: conversionsources.ListConversionSourcesRequest, - response: conversionsources.ListConversionSourcesResponse, - *, - 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_conversions_v1beta.types.ListConversionSourcesRequest): - The initial request object. - response (google.shopping.merchant_conversions_v1beta.types.ListConversionSourcesResponse): - 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 = conversionsources.ListConversionSourcesRequest(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[conversionsources.ListConversionSourcesResponse]: - 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[conversionsources.ConversionSource]: - for page in self.pages: - yield from page.conversion_sources - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListConversionSourcesAsyncPager: - """A pager for iterating through ``list_conversion_sources`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_conversions_v1beta.types.ListConversionSourcesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``conversion_sources`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListConversionSources`` requests and continue to iterate - through the ``conversion_sources`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_conversions_v1beta.types.ListConversionSourcesResponse` - 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[conversionsources.ListConversionSourcesResponse]], - request: conversionsources.ListConversionSourcesRequest, - response: conversionsources.ListConversionSourcesResponse, - *, - 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_conversions_v1beta.types.ListConversionSourcesRequest): - The initial request object. - response (google.shopping.merchant_conversions_v1beta.types.ListConversionSourcesResponse): - 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 = conversionsources.ListConversionSourcesRequest(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[conversionsources.ListConversionSourcesResponse]: - 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[conversionsources.ConversionSource]: - async def async_generator(): - async for page in self.pages: - for response in page.conversion_sources: - 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-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/README.rst deleted file mode 100644 index 3ffc61f2806b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`ConversionSourcesServiceTransport` is the ABC for all transports. -- public child `ConversionSourcesServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `ConversionSourcesServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseConversionSourcesServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `ConversionSourcesServiceRestTransport` 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-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/__init__.py deleted file mode 100644 index fafe5db74b55..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 ConversionSourcesServiceTransport -from .grpc import ConversionSourcesServiceGrpcTransport -from .grpc_asyncio import ConversionSourcesServiceGrpcAsyncIOTransport -from .rest import ConversionSourcesServiceRestTransport -from .rest import ConversionSourcesServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ConversionSourcesServiceTransport]] -_transport_registry['grpc'] = ConversionSourcesServiceGrpcTransport -_transport_registry['grpc_asyncio'] = ConversionSourcesServiceGrpcAsyncIOTransport -_transport_registry['rest'] = ConversionSourcesServiceRestTransport - -__all__ = ( - 'ConversionSourcesServiceTransport', - 'ConversionSourcesServiceGrpcTransport', - 'ConversionSourcesServiceGrpcAsyncIOTransport', - 'ConversionSourcesServiceRestTransport', - 'ConversionSourcesServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/base.py deleted file mode 100644 index aab7dedcf3a7..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/base.py +++ /dev/null @@ -1,225 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_conversions_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 - -from google.protobuf import empty_pb2 # type: ignore -from google.shopping.merchant_conversions_v1beta.types import conversionsources - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class ConversionSourcesServiceTransport(abc.ABC): - """Abstract transport class for ConversionSourcesService.""" - - 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.create_conversion_source: gapic_v1.method.wrap_method( - self.create_conversion_source, - default_timeout=None, - client_info=client_info, - ), - self.update_conversion_source: gapic_v1.method.wrap_method( - self.update_conversion_source, - default_timeout=None, - client_info=client_info, - ), - self.delete_conversion_source: gapic_v1.method.wrap_method( - self.delete_conversion_source, - default_timeout=None, - client_info=client_info, - ), - self.undelete_conversion_source: gapic_v1.method.wrap_method( - self.undelete_conversion_source, - default_timeout=None, - client_info=client_info, - ), - self.get_conversion_source: gapic_v1.method.wrap_method( - self.get_conversion_source, - default_timeout=None, - client_info=client_info, - ), - self.list_conversion_sources: gapic_v1.method.wrap_method( - self.list_conversion_sources, - 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 create_conversion_source(self) -> Callable[ - [conversionsources.CreateConversionSourceRequest], - Union[ - conversionsources.ConversionSource, - Awaitable[conversionsources.ConversionSource] - ]]: - raise NotImplementedError() - - @property - def update_conversion_source(self) -> Callable[ - [conversionsources.UpdateConversionSourceRequest], - Union[ - conversionsources.ConversionSource, - Awaitable[conversionsources.ConversionSource] - ]]: - raise NotImplementedError() - - @property - def delete_conversion_source(self) -> Callable[ - [conversionsources.DeleteConversionSourceRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def undelete_conversion_source(self) -> Callable[ - [conversionsources.UndeleteConversionSourceRequest], - Union[ - conversionsources.ConversionSource, - Awaitable[conversionsources.ConversionSource] - ]]: - raise NotImplementedError() - - @property - def get_conversion_source(self) -> Callable[ - [conversionsources.GetConversionSourceRequest], - Union[ - conversionsources.ConversionSource, - Awaitable[conversionsources.ConversionSource] - ]]: - raise NotImplementedError() - - @property - def list_conversion_sources(self) -> Callable[ - [conversionsources.ListConversionSourcesRequest], - Union[ - conversionsources.ListConversionSourcesResponse, - Awaitable[conversionsources.ListConversionSourcesResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ConversionSourcesServiceTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/grpc.py deleted file mode 100644 index 257d0661419f..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/grpc.py +++ /dev/null @@ -1,488 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_conversions_v1beta.types import conversionsources -from .base import ConversionSourcesServiceTransport, 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.conversions.v1beta.ConversionSourcesService", - "rpcName": 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.conversions.v1beta.ConversionSourcesService", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class ConversionSourcesServiceGrpcTransport(ConversionSourcesServiceTransport): - """gRPC backend transport for ConversionSourcesService. - - Service for managing conversion sources for a merchant - account. - - This 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 create_conversion_source(self) -> Callable[ - [conversionsources.CreateConversionSourceRequest], - conversionsources.ConversionSource]: - r"""Return a callable for the create conversion source method over gRPC. - - Creates a new conversion source. - - Returns: - Callable[[~.CreateConversionSourceRequest], - ~.ConversionSource]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_conversion_source' not in self._stubs: - self._stubs['create_conversion_source'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.conversions.v1beta.ConversionSourcesService/CreateConversionSource', - request_serializer=conversionsources.CreateConversionSourceRequest.serialize, - response_deserializer=conversionsources.ConversionSource.deserialize, - ) - return self._stubs['create_conversion_source'] - - @property - def update_conversion_source(self) -> Callable[ - [conversionsources.UpdateConversionSourceRequest], - conversionsources.ConversionSource]: - r"""Return a callable for the update conversion source method over gRPC. - - Updates information of an existing conversion source. - Available only for Merchant Center Destination - conversion sources. - - Returns: - Callable[[~.UpdateConversionSourceRequest], - ~.ConversionSource]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_conversion_source' not in self._stubs: - self._stubs['update_conversion_source'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.conversions.v1beta.ConversionSourcesService/UpdateConversionSource', - request_serializer=conversionsources.UpdateConversionSourceRequest.serialize, - response_deserializer=conversionsources.ConversionSource.deserialize, - ) - return self._stubs['update_conversion_source'] - - @property - def delete_conversion_source(self) -> Callable[ - [conversionsources.DeleteConversionSourceRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete conversion source method over gRPC. - - Archives an existing conversion source. If the - conversion source is a Merchant Center Destination, it - will be recoverable for 30 days. If the conversion - source is a Google Analytics Link, it will be deleted - immediately and can be restored by creating a new one. - - Returns: - Callable[[~.DeleteConversionSourceRequest], - ~.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_conversion_source' not in self._stubs: - self._stubs['delete_conversion_source'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.conversions.v1beta.ConversionSourcesService/DeleteConversionSource', - request_serializer=conversionsources.DeleteConversionSourceRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_conversion_source'] - - @property - def undelete_conversion_source(self) -> Callable[ - [conversionsources.UndeleteConversionSourceRequest], - conversionsources.ConversionSource]: - r"""Return a callable for the undelete conversion source method over gRPC. - - Re-enables an archived conversion source. Only - Available for Merchant Center Destination conversion - sources. - - Returns: - Callable[[~.UndeleteConversionSourceRequest], - ~.ConversionSource]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'undelete_conversion_source' not in self._stubs: - self._stubs['undelete_conversion_source'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.conversions.v1beta.ConversionSourcesService/UndeleteConversionSource', - request_serializer=conversionsources.UndeleteConversionSourceRequest.serialize, - response_deserializer=conversionsources.ConversionSource.deserialize, - ) - return self._stubs['undelete_conversion_source'] - - @property - def get_conversion_source(self) -> Callable[ - [conversionsources.GetConversionSourceRequest], - conversionsources.ConversionSource]: - r"""Return a callable for the get conversion source method over gRPC. - - Fetches a conversion source. - - Returns: - Callable[[~.GetConversionSourceRequest], - ~.ConversionSource]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_conversion_source' not in self._stubs: - self._stubs['get_conversion_source'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.conversions.v1beta.ConversionSourcesService/GetConversionSource', - request_serializer=conversionsources.GetConversionSourceRequest.serialize, - response_deserializer=conversionsources.ConversionSource.deserialize, - ) - return self._stubs['get_conversion_source'] - - @property - def list_conversion_sources(self) -> Callable[ - [conversionsources.ListConversionSourcesRequest], - conversionsources.ListConversionSourcesResponse]: - r"""Return a callable for the list conversion sources method over gRPC. - - Retrieves the list of conversion sources the caller - has access to. - - Returns: - Callable[[~.ListConversionSourcesRequest], - ~.ListConversionSourcesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_conversion_sources' not in self._stubs: - self._stubs['list_conversion_sources'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.conversions.v1beta.ConversionSourcesService/ListConversionSources', - request_serializer=conversionsources.ListConversionSourcesRequest.serialize, - response_deserializer=conversionsources.ListConversionSourcesResponse.deserialize, - ) - return self._stubs['list_conversion_sources'] - - def close(self): - self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ConversionSourcesServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/grpc_asyncio.py deleted file mode 100644 index 64d901f88111..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,533 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_conversions_v1beta.types import conversionsources -from .base import ConversionSourcesServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import ConversionSourcesServiceGrpcTransport - -try: - from google.api_core import client_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.conversions.v1beta.ConversionSourcesService", - "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.conversions.v1beta.ConversionSourcesService", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class ConversionSourcesServiceGrpcAsyncIOTransport(ConversionSourcesServiceTransport): - """gRPC AsyncIO backend transport for ConversionSourcesService. - - Service for managing conversion sources for a merchant - account. - - This 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 create_conversion_source(self) -> Callable[ - [conversionsources.CreateConversionSourceRequest], - Awaitable[conversionsources.ConversionSource]]: - r"""Return a callable for the create conversion source method over gRPC. - - Creates a new conversion source. - - Returns: - Callable[[~.CreateConversionSourceRequest], - Awaitable[~.ConversionSource]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_conversion_source' not in self._stubs: - self._stubs['create_conversion_source'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.conversions.v1beta.ConversionSourcesService/CreateConversionSource', - request_serializer=conversionsources.CreateConversionSourceRequest.serialize, - response_deserializer=conversionsources.ConversionSource.deserialize, - ) - return self._stubs['create_conversion_source'] - - @property - def update_conversion_source(self) -> Callable[ - [conversionsources.UpdateConversionSourceRequest], - Awaitable[conversionsources.ConversionSource]]: - r"""Return a callable for the update conversion source method over gRPC. - - Updates information of an existing conversion source. - Available only for Merchant Center Destination - conversion sources. - - Returns: - Callable[[~.UpdateConversionSourceRequest], - Awaitable[~.ConversionSource]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_conversion_source' not in self._stubs: - self._stubs['update_conversion_source'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.conversions.v1beta.ConversionSourcesService/UpdateConversionSource', - request_serializer=conversionsources.UpdateConversionSourceRequest.serialize, - response_deserializer=conversionsources.ConversionSource.deserialize, - ) - return self._stubs['update_conversion_source'] - - @property - def delete_conversion_source(self) -> Callable[ - [conversionsources.DeleteConversionSourceRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete conversion source method over gRPC. - - Archives an existing conversion source. If the - conversion source is a Merchant Center Destination, it - will be recoverable for 30 days. If the conversion - source is a Google Analytics Link, it will be deleted - immediately and can be restored by creating a new one. - - Returns: - Callable[[~.DeleteConversionSourceRequest], - 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_conversion_source' not in self._stubs: - self._stubs['delete_conversion_source'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.conversions.v1beta.ConversionSourcesService/DeleteConversionSource', - request_serializer=conversionsources.DeleteConversionSourceRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_conversion_source'] - - @property - def undelete_conversion_source(self) -> Callable[ - [conversionsources.UndeleteConversionSourceRequest], - Awaitable[conversionsources.ConversionSource]]: - r"""Return a callable for the undelete conversion source method over gRPC. - - Re-enables an archived conversion source. Only - Available for Merchant Center Destination conversion - sources. - - Returns: - Callable[[~.UndeleteConversionSourceRequest], - Awaitable[~.ConversionSource]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'undelete_conversion_source' not in self._stubs: - self._stubs['undelete_conversion_source'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.conversions.v1beta.ConversionSourcesService/UndeleteConversionSource', - request_serializer=conversionsources.UndeleteConversionSourceRequest.serialize, - response_deserializer=conversionsources.ConversionSource.deserialize, - ) - return self._stubs['undelete_conversion_source'] - - @property - def get_conversion_source(self) -> Callable[ - [conversionsources.GetConversionSourceRequest], - Awaitable[conversionsources.ConversionSource]]: - r"""Return a callable for the get conversion source method over gRPC. - - Fetches a conversion source. - - Returns: - Callable[[~.GetConversionSourceRequest], - Awaitable[~.ConversionSource]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_conversion_source' not in self._stubs: - self._stubs['get_conversion_source'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.conversions.v1beta.ConversionSourcesService/GetConversionSource', - request_serializer=conversionsources.GetConversionSourceRequest.serialize, - response_deserializer=conversionsources.ConversionSource.deserialize, - ) - return self._stubs['get_conversion_source'] - - @property - def list_conversion_sources(self) -> Callable[ - [conversionsources.ListConversionSourcesRequest], - Awaitable[conversionsources.ListConversionSourcesResponse]]: - r"""Return a callable for the list conversion sources method over gRPC. - - Retrieves the list of conversion sources the caller - has access to. - - Returns: - Callable[[~.ListConversionSourcesRequest], - Awaitable[~.ListConversionSourcesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_conversion_sources' not in self._stubs: - self._stubs['list_conversion_sources'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.conversions.v1beta.ConversionSourcesService/ListConversionSources', - request_serializer=conversionsources.ListConversionSourcesRequest.serialize, - response_deserializer=conversionsources.ListConversionSourcesResponse.deserialize, - ) - return self._stubs['list_conversion_sources'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.create_conversion_source: self._wrap_method( - self.create_conversion_source, - default_timeout=None, - client_info=client_info, - ), - self.update_conversion_source: self._wrap_method( - self.update_conversion_source, - default_timeout=None, - client_info=client_info, - ), - self.delete_conversion_source: self._wrap_method( - self.delete_conversion_source, - default_timeout=None, - client_info=client_info, - ), - self.undelete_conversion_source: self._wrap_method( - self.undelete_conversion_source, - default_timeout=None, - client_info=client_info, - ), - self.get_conversion_source: self._wrap_method( - self.get_conversion_source, - default_timeout=None, - client_info=client_info, - ), - self.list_conversion_sources: self._wrap_method( - self.list_conversion_sources, - 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__ = ( - 'ConversionSourcesServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/rest.py deleted file mode 100644 index 5331d5dab5af..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/rest.py +++ /dev/null @@ -1,1067 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -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_conversions_v1beta.types import conversionsources - - -from .rest_base import _BaseConversionSourcesServiceRestTransport -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}", -) - - -class ConversionSourcesServiceRestInterceptor: - """Interceptor for ConversionSourcesService. - - 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 ConversionSourcesServiceRestTransport. - - .. code-block:: python - class MyCustomConversionSourcesServiceInterceptor(ConversionSourcesServiceRestInterceptor): - def pre_create_conversion_source(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_conversion_source(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_conversion_source(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_conversion_source(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_conversion_source(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_conversion_sources(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_conversion_sources(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_undelete_conversion_source(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_undelete_conversion_source(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_conversion_source(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_conversion_source(self, response): - logging.log(f"Received response: {response}") - return response - - transport = ConversionSourcesServiceRestTransport(interceptor=MyCustomConversionSourcesServiceInterceptor()) - client = ConversionSourcesServiceClient(transport=transport) - - - """ - def pre_create_conversion_source(self, request: conversionsources.CreateConversionSourceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[conversionsources.CreateConversionSourceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for create_conversion_source - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversionSourcesService server. - """ - return request, metadata - - def post_create_conversion_source(self, response: conversionsources.ConversionSource) -> conversionsources.ConversionSource: - """Post-rpc interceptor for create_conversion_source - - Override in a subclass to manipulate the response - after it is returned by the ConversionSourcesService server but before - it is returned to user code. - """ - return response - - def pre_delete_conversion_source(self, request: conversionsources.DeleteConversionSourceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[conversionsources.DeleteConversionSourceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_conversion_source - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversionSourcesService server. - """ - return request, metadata - - def pre_get_conversion_source(self, request: conversionsources.GetConversionSourceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[conversionsources.GetConversionSourceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_conversion_source - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversionSourcesService server. - """ - return request, metadata - - def post_get_conversion_source(self, response: conversionsources.ConversionSource) -> conversionsources.ConversionSource: - """Post-rpc interceptor for get_conversion_source - - Override in a subclass to manipulate the response - after it is returned by the ConversionSourcesService server but before - it is returned to user code. - """ - return response - - def pre_list_conversion_sources(self, request: conversionsources.ListConversionSourcesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[conversionsources.ListConversionSourcesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_conversion_sources - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversionSourcesService server. - """ - return request, metadata - - def post_list_conversion_sources(self, response: conversionsources.ListConversionSourcesResponse) -> conversionsources.ListConversionSourcesResponse: - """Post-rpc interceptor for list_conversion_sources - - Override in a subclass to manipulate the response - after it is returned by the ConversionSourcesService server but before - it is returned to user code. - """ - return response - - def pre_undelete_conversion_source(self, request: conversionsources.UndeleteConversionSourceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[conversionsources.UndeleteConversionSourceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for undelete_conversion_source - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversionSourcesService server. - """ - return request, metadata - - def post_undelete_conversion_source(self, response: conversionsources.ConversionSource) -> conversionsources.ConversionSource: - """Post-rpc interceptor for undelete_conversion_source - - Override in a subclass to manipulate the response - after it is returned by the ConversionSourcesService server but before - it is returned to user code. - """ - return response - - def pre_update_conversion_source(self, request: conversionsources.UpdateConversionSourceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[conversionsources.UpdateConversionSourceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for update_conversion_source - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversionSourcesService server. - """ - return request, metadata - - def post_update_conversion_source(self, response: conversionsources.ConversionSource) -> conversionsources.ConversionSource: - """Post-rpc interceptor for update_conversion_source - - Override in a subclass to manipulate the response - after it is returned by the ConversionSourcesService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class ConversionSourcesServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: ConversionSourcesServiceRestInterceptor - - -class ConversionSourcesServiceRestTransport(_BaseConversionSourcesServiceRestTransport): - """REST backend synchronous transport for ConversionSourcesService. - - Service for managing conversion sources for a merchant - account. - - This 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[ConversionSourcesServiceRestInterceptor] = 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 ConversionSourcesServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _CreateConversionSource(_BaseConversionSourcesServiceRestTransport._BaseCreateConversionSource, ConversionSourcesServiceRestStub): - def __hash__(self): - return hash("ConversionSourcesServiceRestTransport.CreateConversionSource") - - @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: conversionsources.CreateConversionSourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> conversionsources.ConversionSource: - r"""Call the create conversion source method over HTTP. - - Args: - request (~.conversionsources.CreateConversionSourceRequest): - The request object. Request message for the - CreateConversionSource method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.conversionsources.ConversionSource: - Represents a conversion source owned - by a Merchant account. A merchant - account can have up to 200 conversion - sources. - - """ - - http_options = _BaseConversionSourcesServiceRestTransport._BaseCreateConversionSource._get_http_options() - - request, metadata = self._interceptor.pre_create_conversion_source(request, metadata) - transcoded_request = _BaseConversionSourcesServiceRestTransport._BaseCreateConversionSource._get_transcoded_request(http_options, request) - - body = _BaseConversionSourcesServiceRestTransport._BaseCreateConversionSource._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseConversionSourcesServiceRestTransport._BaseCreateConversionSource._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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.conversions_v1beta.ConversionSourcesServiceClient.CreateConversionSource", - extra = { - "serviceName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", - "rpcName": "CreateConversionSource", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ConversionSourcesServiceRestTransport._CreateConversionSource._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 = conversionsources.ConversionSource() - pb_resp = conversionsources.ConversionSource.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_create_conversion_source(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = conversionsources.ConversionSource.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.conversions_v1beta.ConversionSourcesServiceClient.create_conversion_source", - extra = { - "serviceName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", - "rpcName": "CreateConversionSource", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _DeleteConversionSource(_BaseConversionSourcesServiceRestTransport._BaseDeleteConversionSource, ConversionSourcesServiceRestStub): - def __hash__(self): - return hash("ConversionSourcesServiceRestTransport.DeleteConversionSource") - - @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: conversionsources.DeleteConversionSourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ): - r"""Call the delete conversion source method over HTTP. - - Args: - request (~.conversionsources.DeleteConversionSourceRequest): - The request object. Request message for the - DeleteConversionSource method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, 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 = _BaseConversionSourcesServiceRestTransport._BaseDeleteConversionSource._get_http_options() - - request, metadata = self._interceptor.pre_delete_conversion_source(request, metadata) - transcoded_request = _BaseConversionSourcesServiceRestTransport._BaseDeleteConversionSource._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseConversionSourcesServiceRestTransport._BaseDeleteConversionSource._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(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.conversions_v1beta.ConversionSourcesServiceClient.DeleteConversionSource", - extra = { - "serviceName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", - "rpcName": "DeleteConversionSource", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ConversionSourcesServiceRestTransport._DeleteConversionSource._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 _GetConversionSource(_BaseConversionSourcesServiceRestTransport._BaseGetConversionSource, ConversionSourcesServiceRestStub): - def __hash__(self): - return hash("ConversionSourcesServiceRestTransport.GetConversionSource") - - @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: conversionsources.GetConversionSourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> conversionsources.ConversionSource: - r"""Call the get conversion source method over HTTP. - - Args: - request (~.conversionsources.GetConversionSourceRequest): - The request object. Request message for the - GetConversionSource method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.conversionsources.ConversionSource: - Represents a conversion source owned - by a Merchant account. A merchant - account can have up to 200 conversion - sources. - - """ - - http_options = _BaseConversionSourcesServiceRestTransport._BaseGetConversionSource._get_http_options() - - request, metadata = self._interceptor.pre_get_conversion_source(request, metadata) - transcoded_request = _BaseConversionSourcesServiceRestTransport._BaseGetConversionSource._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseConversionSourcesServiceRestTransport._BaseGetConversionSource._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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.conversions_v1beta.ConversionSourcesServiceClient.GetConversionSource", - extra = { - "serviceName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", - "rpcName": "GetConversionSource", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ConversionSourcesServiceRestTransport._GetConversionSource._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 = conversionsources.ConversionSource() - pb_resp = conversionsources.ConversionSource.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_conversion_source(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = conversionsources.ConversionSource.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.conversions_v1beta.ConversionSourcesServiceClient.get_conversion_source", - extra = { - "serviceName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", - "rpcName": "GetConversionSource", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListConversionSources(_BaseConversionSourcesServiceRestTransport._BaseListConversionSources, ConversionSourcesServiceRestStub): - def __hash__(self): - return hash("ConversionSourcesServiceRestTransport.ListConversionSources") - - @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: conversionsources.ListConversionSourcesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> conversionsources.ListConversionSourcesResponse: - r"""Call the list conversion sources method over HTTP. - - Args: - request (~.conversionsources.ListConversionSourcesRequest): - The request object. Request message for the - ListConversionSources method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.conversionsources.ListConversionSourcesResponse: - Response message for the - ListConversionSources method. - - """ - - http_options = _BaseConversionSourcesServiceRestTransport._BaseListConversionSources._get_http_options() - - request, metadata = self._interceptor.pre_list_conversion_sources(request, metadata) - transcoded_request = _BaseConversionSourcesServiceRestTransport._BaseListConversionSources._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseConversionSourcesServiceRestTransport._BaseListConversionSources._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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.conversions_v1beta.ConversionSourcesServiceClient.ListConversionSources", - extra = { - "serviceName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", - "rpcName": "ListConversionSources", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ConversionSourcesServiceRestTransport._ListConversionSources._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 = conversionsources.ListConversionSourcesResponse() - pb_resp = conversionsources.ListConversionSourcesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_conversion_sources(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = conversionsources.ListConversionSourcesResponse.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.conversions_v1beta.ConversionSourcesServiceClient.list_conversion_sources", - extra = { - "serviceName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", - "rpcName": "ListConversionSources", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UndeleteConversionSource(_BaseConversionSourcesServiceRestTransport._BaseUndeleteConversionSource, ConversionSourcesServiceRestStub): - def __hash__(self): - return hash("ConversionSourcesServiceRestTransport.UndeleteConversionSource") - - @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: conversionsources.UndeleteConversionSourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> conversionsources.ConversionSource: - r"""Call the undelete conversion - source method over HTTP. - - Args: - request (~.conversionsources.UndeleteConversionSourceRequest): - The request object. Request message for the - UndeleteConversionSource method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.conversionsources.ConversionSource: - Represents a conversion source owned - by a Merchant account. A merchant - account can have up to 200 conversion - sources. - - """ - - http_options = _BaseConversionSourcesServiceRestTransport._BaseUndeleteConversionSource._get_http_options() - - request, metadata = self._interceptor.pre_undelete_conversion_source(request, metadata) - transcoded_request = _BaseConversionSourcesServiceRestTransport._BaseUndeleteConversionSource._get_transcoded_request(http_options, request) - - body = _BaseConversionSourcesServiceRestTransport._BaseUndeleteConversionSource._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseConversionSourcesServiceRestTransport._BaseUndeleteConversionSource._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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.conversions_v1beta.ConversionSourcesServiceClient.UndeleteConversionSource", - extra = { - "serviceName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", - "rpcName": "UndeleteConversionSource", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ConversionSourcesServiceRestTransport._UndeleteConversionSource._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 = conversionsources.ConversionSource() - pb_resp = conversionsources.ConversionSource.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_undelete_conversion_source(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = conversionsources.ConversionSource.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.conversions_v1beta.ConversionSourcesServiceClient.undelete_conversion_source", - extra = { - "serviceName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", - "rpcName": "UndeleteConversionSource", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UpdateConversionSource(_BaseConversionSourcesServiceRestTransport._BaseUpdateConversionSource, ConversionSourcesServiceRestStub): - def __hash__(self): - return hash("ConversionSourcesServiceRestTransport.UpdateConversionSource") - - @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: conversionsources.UpdateConversionSourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> conversionsources.ConversionSource: - r"""Call the update conversion source method over HTTP. - - Args: - request (~.conversionsources.UpdateConversionSourceRequest): - The request object. Request message for the - UpdateConversionSource method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.conversionsources.ConversionSource: - Represents a conversion source owned - by a Merchant account. A merchant - account can have up to 200 conversion - sources. - - """ - - http_options = _BaseConversionSourcesServiceRestTransport._BaseUpdateConversionSource._get_http_options() - - request, metadata = self._interceptor.pre_update_conversion_source(request, metadata) - transcoded_request = _BaseConversionSourcesServiceRestTransport._BaseUpdateConversionSource._get_transcoded_request(http_options, request) - - body = _BaseConversionSourcesServiceRestTransport._BaseUpdateConversionSource._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseConversionSourcesServiceRestTransport._BaseUpdateConversionSource._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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.conversions_v1beta.ConversionSourcesServiceClient.UpdateConversionSource", - extra = { - "serviceName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", - "rpcName": "UpdateConversionSource", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ConversionSourcesServiceRestTransport._UpdateConversionSource._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 = conversionsources.ConversionSource() - pb_resp = conversionsources.ConversionSource.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_update_conversion_source(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = conversionsources.ConversionSource.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.conversions_v1beta.ConversionSourcesServiceClient.update_conversion_source", - extra = { - "serviceName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", - "rpcName": "UpdateConversionSource", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def create_conversion_source(self) -> Callable[ - [conversionsources.CreateConversionSourceRequest], - conversionsources.ConversionSource]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateConversionSource(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_conversion_source(self) -> Callable[ - [conversionsources.DeleteConversionSourceRequest], - 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._DeleteConversionSource(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_conversion_source(self) -> Callable[ - [conversionsources.GetConversionSourceRequest], - conversionsources.ConversionSource]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetConversionSource(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_conversion_sources(self) -> Callable[ - [conversionsources.ListConversionSourcesRequest], - conversionsources.ListConversionSourcesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListConversionSources(self._session, self._host, self._interceptor) # type: ignore - - @property - def undelete_conversion_source(self) -> Callable[ - [conversionsources.UndeleteConversionSourceRequest], - conversionsources.ConversionSource]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UndeleteConversionSource(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_conversion_source(self) -> Callable[ - [conversionsources.UpdateConversionSourceRequest], - conversionsources.ConversionSource]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateConversionSource(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'ConversionSourcesServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/rest_base.py deleted file mode 100644 index cbb98c1531ce..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/rest_base.py +++ /dev/null @@ -1,344 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 ConversionSourcesServiceTransport, 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_conversions_v1beta.types import conversionsources - - -class _BaseConversionSourcesServiceRestTransport(ConversionSourcesServiceTransport): - """Base REST backend transport for ConversionSourcesService. - - 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 _BaseCreateConversionSource: - 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': '/conversions/v1beta/{parent=accounts/*}/conversionSources', - 'body': 'conversion_source', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = conversionsources.CreateConversionSourceRequest.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(_BaseConversionSourcesServiceRestTransport._BaseCreateConversionSource._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteConversionSource: - 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': '/conversions/v1beta/{name=accounts/*/conversionSources/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = conversionsources.DeleteConversionSourceRequest.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(_BaseConversionSourcesServiceRestTransport._BaseDeleteConversionSource._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetConversionSource: - 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': '/conversions/v1beta/{name=accounts/*/conversionSources/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = conversionsources.GetConversionSourceRequest.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(_BaseConversionSourcesServiceRestTransport._BaseGetConversionSource._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListConversionSources: - 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': '/conversions/v1beta/{parent=accounts/*}/conversionSources', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = conversionsources.ListConversionSourcesRequest.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(_BaseConversionSourcesServiceRestTransport._BaseListConversionSources._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUndeleteConversionSource: - 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': '/conversions/v1beta/{name=accounts/*/conversionSources/*}:undelete', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = conversionsources.UndeleteConversionSourceRequest.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(_BaseConversionSourcesServiceRestTransport._BaseUndeleteConversionSource._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateConversionSource: - 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': '/conversions/v1beta/{conversion_source.name=accounts/*/conversionSources/*}', - 'body': 'conversion_source', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = conversionsources.UpdateConversionSourceRequest.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(_BaseConversionSourcesServiceRestTransport._BaseUpdateConversionSource._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseConversionSourcesServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/types/__init__.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/types/__init__.py deleted file mode 100644 index c14c1e980fae..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/types/__init__.py +++ /dev/null @@ -1,42 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .conversionsources import ( - AttributionSettings, - ConversionSource, - CreateConversionSourceRequest, - DeleteConversionSourceRequest, - GetConversionSourceRequest, - GoogleAnalyticsLink, - ListConversionSourcesRequest, - ListConversionSourcesResponse, - MerchantCenterDestination, - UndeleteConversionSourceRequest, - UpdateConversionSourceRequest, -) - -__all__ = ( - 'AttributionSettings', - 'ConversionSource', - 'CreateConversionSourceRequest', - 'DeleteConversionSourceRequest', - 'GetConversionSourceRequest', - 'GoogleAnalyticsLink', - 'ListConversionSourcesRequest', - 'ListConversionSourcesResponse', - 'MerchantCenterDestination', - 'UndeleteConversionSourceRequest', - 'UpdateConversionSourceRequest', -) diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/types/conversionsources.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/types/conversionsources.py deleted file mode 100644 index f735abe384fe..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/types/conversionsources.py +++ /dev/null @@ -1,484 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.shopping.merchant.conversions.v1beta', - manifest={ - 'ConversionSource', - 'AttributionSettings', - 'GoogleAnalyticsLink', - 'MerchantCenterDestination', - 'CreateConversionSourceRequest', - 'UpdateConversionSourceRequest', - 'DeleteConversionSourceRequest', - 'UndeleteConversionSourceRequest', - 'GetConversionSourceRequest', - 'ListConversionSourcesRequest', - 'ListConversionSourcesResponse', - }, -) - - -class ConversionSource(proto.Message): - r"""Represents a conversion source owned by a Merchant account. A - merchant account can have up to 200 conversion sources. - - 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: - google_analytics_link (google.shopping.merchant_conversions_v1beta.types.GoogleAnalyticsLink): - Immutable. Conversion Source of type "Link to - Google Analytics Property". - - This field is a member of `oneof`_ ``source_data``. - merchant_center_destination (google.shopping.merchant_conversions_v1beta.types.MerchantCenterDestination): - Conversion Source of type "Merchant Center - Tag Destination". - - This field is a member of `oneof`_ ``source_data``. - name (str): - Output only. Identifier. Generated by the Content API upon - creation of a new ``ConversionSource``. Format: [a-z]{4}:.+ - The four characters before the colon represent the type of - conversio source. Content after the colon represents the ID - of the conversion source within that type. The ID of two - different conversion sources might be the same across - different types. The following type prefixes are supported: - - - galk: For GoogleAnalyticsLink sources. - - mcdn: For MerchantCenterDestination sources. - state (google.shopping.merchant_conversions_v1beta.types.ConversionSource.State): - Output only. Current state of this conversion - source. Can't be edited through the API. - expire_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time when an archived - conversion source becomes permanently deleted - and is no longer available to undelete. - controller (google.shopping.merchant_conversions_v1beta.types.ConversionSource.Controller): - Output only. Controller of the conversion - source. - """ - class State(proto.Enum): - r"""Represents state of the conversion source. - - Values: - STATE_UNSPECIFIED (0): - Conversion source has unspecified state. - ACTIVE (1): - Conversion source is fully functional. - ARCHIVED (2): - Conversion source has been archived in the - last 30 days and not currently functional. Can - be restored using the undelete method. - PENDING (3): - Conversion source creation has started but - not fully finished yet. - """ - STATE_UNSPECIFIED = 0 - ACTIVE = 1 - ARCHIVED = 2 - PENDING = 3 - - class Controller(proto.Enum): - r"""Entity controlling the conversion source. - - Values: - CONTROLLER_UNSPECIFIED (0): - Default value. This value is unused. - MERCHANT (1): - Controlled by the Merchant who owns the - Conversion Source. - YOUTUBE_AFFILIATES (2): - Controlled by the YT Affiliates program. - """ - CONTROLLER_UNSPECIFIED = 0 - MERCHANT = 1 - YOUTUBE_AFFILIATES = 2 - - google_analytics_link: 'GoogleAnalyticsLink' = proto.Field( - proto.MESSAGE, - number=3, - oneof='source_data', - message='GoogleAnalyticsLink', - ) - merchant_center_destination: 'MerchantCenterDestination' = proto.Field( - proto.MESSAGE, - number=4, - oneof='source_data', - message='MerchantCenterDestination', - ) - name: str = proto.Field( - proto.STRING, - number=1, - ) - state: State = proto.Field( - proto.ENUM, - number=5, - enum=State, - ) - expire_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - controller: Controller = proto.Field( - proto.ENUM, - number=7, - enum=Controller, - ) - - -class AttributionSettings(proto.Message): - r"""Represents attribution settings for conversion sources - receiving pre-attribution data. - - Attributes: - attribution_lookback_window_days (int): - Required. Lookback windows (in days) used for - attribution in this source. Supported values are - 7, 30, 40. - attribution_model (google.shopping.merchant_conversions_v1beta.types.AttributionSettings.AttributionModel): - Required. Attribution model. - conversion_type (MutableSequence[google.shopping.merchant_conversions_v1beta.types.AttributionSettings.ConversionType]): - Immutable. Unordered list. List of different - conversion types a conversion event can be - classified as. A standard "purchase" type will - be automatically created if this list is empty - at creation time. - """ - class AttributionModel(proto.Enum): - r"""The attribution model used for this source. We support the - same set of models offered by Google Analytics 4, as described - in: - - https://support.google.com/analytics/answer/10596866. - - Values: - ATTRIBUTION_MODEL_UNSPECIFIED (0): - Unspecified model. - CROSS_CHANNEL_LAST_CLICK (1): - Cross-channel Last Click model. - ADS_PREFERRED_LAST_CLICK (2): - Ads-preferred Last Click model. - CROSS_CHANNEL_DATA_DRIVEN (5): - Cross-channel Data Driven model. - CROSS_CHANNEL_FIRST_CLICK (6): - Cross-channel First Click model. - CROSS_CHANNEL_LINEAR (7): - Cross-channel Linear model. - CROSS_CHANNEL_POSITION_BASED (8): - Cross-channel Position Based model. - CROSS_CHANNEL_TIME_DECAY (9): - Cross-channel Time Decay model. - """ - ATTRIBUTION_MODEL_UNSPECIFIED = 0 - CROSS_CHANNEL_LAST_CLICK = 1 - ADS_PREFERRED_LAST_CLICK = 2 - CROSS_CHANNEL_DATA_DRIVEN = 5 - CROSS_CHANNEL_FIRST_CLICK = 6 - CROSS_CHANNEL_LINEAR = 7 - CROSS_CHANNEL_POSITION_BASED = 8 - CROSS_CHANNEL_TIME_DECAY = 9 - - class ConversionType(proto.Message): - r"""Message representing a types of conversion events - - Attributes: - name (str): - Output only. Conversion event name, as it'll - be reported by the client. - report (bool): - Output only. Option indicating if the type - should be included in Merchant Center reporting. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - report: bool = proto.Field( - proto.BOOL, - number=2, - ) - - attribution_lookback_window_days: int = proto.Field( - proto.INT32, - number=1, - ) - attribution_model: AttributionModel = proto.Field( - proto.ENUM, - number=2, - enum=AttributionModel, - ) - conversion_type: MutableSequence[ConversionType] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=ConversionType, - ) - - -class GoogleAnalyticsLink(proto.Message): - r""""Google Analytics Link" sources can be used to get conversion - data from an existing Google Analytics property into the linked - Merchant Center account. - - Attributes: - property_id (int): - Required. Immutable. ID of the Google - Analytics property the merchant is linked to. - attribution_settings (google.shopping.merchant_conversions_v1beta.types.AttributionSettings): - Output only. Attribution settings for the - linked Google Analytics property. - property (str): - Output only. Name of the Google Analytics - property the merchant is linked to. - """ - - property_id: int = proto.Field( - proto.INT64, - number=1, - ) - attribution_settings: 'AttributionSettings' = proto.Field( - proto.MESSAGE, - number=2, - message='AttributionSettings', - ) - property: str = proto.Field( - proto.STRING, - number=3, - ) - - -class MerchantCenterDestination(proto.Message): - r""""Merchant Center Destination" sources can be used to send - conversion events from an online store using a Google tag - directly to a Merchant Center account where the source is - created. - - Attributes: - destination (str): - Output only. Merchant Center Destination ID. - attribution_settings (google.shopping.merchant_conversions_v1beta.types.AttributionSettings): - Required. Attribution settings being used for - the Merchant Center Destination. - display_name (str): - Required. Merchant-specified display name for - the destination. This is the name that - identifies the conversion source within the - Merchant Center UI. Limited to 64 characters. - currency_code (str): - Required. Three-letter currency code (ISO - 4217). The currency code defines in which - currency the conversions sent to this - destination will be reported in Merchant Center. - """ - - destination: str = proto.Field( - proto.STRING, - number=1, - ) - attribution_settings: 'AttributionSettings' = proto.Field( - proto.MESSAGE, - number=2, - message='AttributionSettings', - ) - display_name: str = proto.Field( - proto.STRING, - number=3, - ) - currency_code: str = proto.Field( - proto.STRING, - number=4, - ) - - -class CreateConversionSourceRequest(proto.Message): - r"""Request message for the CreateConversionSource method. - - Attributes: - parent (str): - Required. The merchant account that will own - the new conversion source. Format: - accounts/{account} - conversion_source (google.shopping.merchant_conversions_v1beta.types.ConversionSource): - Required. The conversion source description. - A new ID will be automatically assigned to it - upon creation. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - conversion_source: 'ConversionSource' = proto.Field( - proto.MESSAGE, - number=2, - message='ConversionSource', - ) - - -class UpdateConversionSourceRequest(proto.Message): - r"""Request message for the UpdateConversionSource method. - - Attributes: - conversion_source (google.shopping.merchant_conversions_v1beta.types.ConversionSource): - Required. The new version of the conversion source data. - Format: - accounts/{account}/conversionSources/{conversion_source} - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. List of fields being updated. - """ - - conversion_source: 'ConversionSource' = proto.Field( - proto.MESSAGE, - number=1, - message='ConversionSource', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteConversionSourceRequest(proto.Message): - r"""Request message for the DeleteConversionSource method. - - Attributes: - name (str): - Required. The name of the conversion source to be deleted. - Format: - accounts/{account}/conversionSources/{conversion_source} - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class UndeleteConversionSourceRequest(proto.Message): - r"""Request message for the UndeleteConversionSource method. - - Attributes: - name (str): - Required. The name of the conversion source to be undeleted. - Format: - accounts/{account}/conversionSources/{conversion_source} - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetConversionSourceRequest(proto.Message): - r"""Request message for the GetConversionSource method. - - Attributes: - name (str): - Required. The name of the conversion source to be fetched. - Format: - accounts/{account}/conversionsources/{conversion_source} - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListConversionSourcesRequest(proto.Message): - r"""Request message for the ListConversionSources method. - - Attributes: - parent (str): - Required. The merchant account who owns the - collection of conversion sources. Format: - accounts/{account} - page_size (int): - Optional. The maximum number of conversion sources to return - in a page. If no ``page_size`` is specified, ``100`` is used - as the default value. The maximum value is ``200``. Values - above ``200`` will be coerced to ``200``. Regardless of - pagination, at most ``200`` conversion sources are returned - in total. - page_token (str): - Optional. Page token. - show_deleted (bool): - Optional. Show deleted (archived) option. - """ - - 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, - ) - show_deleted: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class ListConversionSourcesResponse(proto.Message): - r"""Response message for the ListConversionSources method. - - Attributes: - conversion_sources (MutableSequence[google.shopping.merchant_conversions_v1beta.types.ConversionSource]): - List of conversion sources. - next_page_token (str): - Token to be used to fetch the next results - page. - """ - - @property - def raw_page(self): - return self - - conversion_sources: MutableSequence['ConversionSource'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ConversionSource', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/mypy.ini b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/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-conversions/v1beta/noxfile.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/noxfile.py deleted file mode 100644 index db4facae0620..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/noxfile.py +++ /dev/null @@ -1,280 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", - "3.12", - "3.13", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = 'google-shopping-merchant-conversions' - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.13" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "prerelease_deps", -] - -@nox.session(python=ALL_PYTHON) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def unit(session, protobuf_implementation): - """Run the unit test suite.""" - - 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+") - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") - - # 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") - - session.run( - 'py.test', - '--quiet', - '--cov=google/shopping/merchant_conversions_v1beta/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - -@nox.session(python=ALL_PYTHON[-1]) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def prerelease_deps(session, protobuf_implementation): - """Run the unit test suite against pre-release versions of dependencies.""" - - 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 test environment dependencies - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - - # Install the package without dependencies - session.install('-e', '.', '--no-deps') - - # We test the minimum dependency versions using the minimum Python - # version so the lowest python runtime that we test has a corresponding constraints - # file, located at `testing/constraints--.txt`, which contains all of the - # 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 - ) - ] - - session.install(*constraints_deps) - - prerel_deps = [ - "googleapis-common-protos", - "google-api-core", - "google-auth", - # Exclude grpcio!=1.67.0rc1 which does not support python 3.13 - "grpcio!=1.67.0rc1", - "grpcio-status", - "protobuf", - "proto-plus", - ] - - for dep in prerel_deps: - session.install("--pre", "--no-deps", "--upgrade", dep) - - # Remaining dependencies - other_deps = [ - "requests", - ] - session.install(*other_deps) - - # Print out prerelease package versions - - session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") - session.run("python", "-c", "import google.auth; print(google.auth.__version__)") - session.run("python", "-c", "import grpc; print(grpc.__version__)") - session.run( - "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" - ) - session.run( - "python", "-c", "import proto; print(proto.__version__)" - ) - - session.run( - 'py.test', - '--quiet', - '--cov=google/shopping/merchant_conversions_v1beta/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - - -@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=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 docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==7.0.1", "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=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", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_create_conversion_source_async.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_create_conversion_source_async.py deleted file mode 100644 index a05ae178289a..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_create_conversion_source_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateConversionSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-conversions - - -# [START merchantapi_v1beta_generated_ConversionSourcesService_CreateConversionSource_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_conversions_v1beta - - -async def sample_create_conversion_source(): - # Create a client - client = merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient() - - # Initialize request argument(s) - conversion_source = merchant_conversions_v1beta.ConversionSource() - conversion_source.google_analytics_link.property_id = 1201 - - request = merchant_conversions_v1beta.CreateConversionSourceRequest( - parent="parent_value", - conversion_source=conversion_source, - ) - - # Make the request - response = await client.create_conversion_source(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_ConversionSourcesService_CreateConversionSource_async] diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_create_conversion_source_sync.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_create_conversion_source_sync.py deleted file mode 100644 index dfb2495b2546..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_create_conversion_source_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateConversionSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-conversions - - -# [START merchantapi_v1beta_generated_ConversionSourcesService_CreateConversionSource_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_conversions_v1beta - - -def sample_create_conversion_source(): - # Create a client - client = merchant_conversions_v1beta.ConversionSourcesServiceClient() - - # Initialize request argument(s) - conversion_source = merchant_conversions_v1beta.ConversionSource() - conversion_source.google_analytics_link.property_id = 1201 - - request = merchant_conversions_v1beta.CreateConversionSourceRequest( - parent="parent_value", - conversion_source=conversion_source, - ) - - # Make the request - response = client.create_conversion_source(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_ConversionSourcesService_CreateConversionSource_sync] diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_delete_conversion_source_async.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_delete_conversion_source_async.py deleted file mode 100644 index 784b513a30d4..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_delete_conversion_source_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteConversionSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-conversions - - -# [START merchantapi_v1beta_generated_ConversionSourcesService_DeleteConversionSource_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_conversions_v1beta - - -async def sample_delete_conversion_source(): - # Create a client - client = merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_conversions_v1beta.DeleteConversionSourceRequest( - name="name_value", - ) - - # Make the request - await client.delete_conversion_source(request=request) - - -# [END merchantapi_v1beta_generated_ConversionSourcesService_DeleteConversionSource_async] diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_delete_conversion_source_sync.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_delete_conversion_source_sync.py deleted file mode 100644 index b6b63cffc119..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_delete_conversion_source_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteConversionSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-conversions - - -# [START merchantapi_v1beta_generated_ConversionSourcesService_DeleteConversionSource_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_conversions_v1beta - - -def sample_delete_conversion_source(): - # Create a client - client = merchant_conversions_v1beta.ConversionSourcesServiceClient() - - # Initialize request argument(s) - request = merchant_conversions_v1beta.DeleteConversionSourceRequest( - name="name_value", - ) - - # Make the request - client.delete_conversion_source(request=request) - - -# [END merchantapi_v1beta_generated_ConversionSourcesService_DeleteConversionSource_sync] diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_get_conversion_source_async.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_get_conversion_source_async.py deleted file mode 100644 index b17fdeea8f22..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_get_conversion_source_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetConversionSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-conversions - - -# [START merchantapi_v1beta_generated_ConversionSourcesService_GetConversionSource_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_conversions_v1beta - - -async def sample_get_conversion_source(): - # Create a client - client = merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_conversions_v1beta.GetConversionSourceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_conversion_source(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_ConversionSourcesService_GetConversionSource_async] diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_get_conversion_source_sync.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_get_conversion_source_sync.py deleted file mode 100644 index b0d0a159fb04..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_get_conversion_source_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetConversionSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-conversions - - -# [START merchantapi_v1beta_generated_ConversionSourcesService_GetConversionSource_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_conversions_v1beta - - -def sample_get_conversion_source(): - # Create a client - client = merchant_conversions_v1beta.ConversionSourcesServiceClient() - - # Initialize request argument(s) - request = merchant_conversions_v1beta.GetConversionSourceRequest( - name="name_value", - ) - - # Make the request - response = client.get_conversion_source(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_ConversionSourcesService_GetConversionSource_sync] diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_list_conversion_sources_async.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_list_conversion_sources_async.py deleted file mode 100644 index 9f9a8edd1630..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_list_conversion_sources_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListConversionSources -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-conversions - - -# [START merchantapi_v1beta_generated_ConversionSourcesService_ListConversionSources_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_conversions_v1beta - - -async def sample_list_conversion_sources(): - # Create a client - client = merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_conversions_v1beta.ListConversionSourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_conversion_sources(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_ConversionSourcesService_ListConversionSources_async] diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_list_conversion_sources_sync.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_list_conversion_sources_sync.py deleted file mode 100644 index 973a08726b22..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_list_conversion_sources_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListConversionSources -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-conversions - - -# [START merchantapi_v1beta_generated_ConversionSourcesService_ListConversionSources_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_conversions_v1beta - - -def sample_list_conversion_sources(): - # Create a client - client = merchant_conversions_v1beta.ConversionSourcesServiceClient() - - # Initialize request argument(s) - request = merchant_conversions_v1beta.ListConversionSourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_conversion_sources(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_ConversionSourcesService_ListConversionSources_sync] diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_undelete_conversion_source_async.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_undelete_conversion_source_async.py deleted file mode 100644 index d2dad07c2a0a..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_undelete_conversion_source_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UndeleteConversionSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-conversions - - -# [START merchantapi_v1beta_generated_ConversionSourcesService_UndeleteConversionSource_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_conversions_v1beta - - -async def sample_undelete_conversion_source(): - # Create a client - client = merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_conversions_v1beta.UndeleteConversionSourceRequest( - name="name_value", - ) - - # Make the request - response = await client.undelete_conversion_source(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_ConversionSourcesService_UndeleteConversionSource_async] diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_undelete_conversion_source_sync.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_undelete_conversion_source_sync.py deleted file mode 100644 index 18218f0303c1..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_undelete_conversion_source_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UndeleteConversionSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-conversions - - -# [START merchantapi_v1beta_generated_ConversionSourcesService_UndeleteConversionSource_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_conversions_v1beta - - -def sample_undelete_conversion_source(): - # Create a client - client = merchant_conversions_v1beta.ConversionSourcesServiceClient() - - # Initialize request argument(s) - request = merchant_conversions_v1beta.UndeleteConversionSourceRequest( - name="name_value", - ) - - # Make the request - response = client.undelete_conversion_source(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_ConversionSourcesService_UndeleteConversionSource_sync] diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_update_conversion_source_async.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_update_conversion_source_async.py deleted file mode 100644 index b60633a60c41..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_update_conversion_source_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateConversionSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-conversions - - -# [START merchantapi_v1beta_generated_ConversionSourcesService_UpdateConversionSource_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_conversions_v1beta - - -async def sample_update_conversion_source(): - # Create a client - client = merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient() - - # Initialize request argument(s) - conversion_source = merchant_conversions_v1beta.ConversionSource() - conversion_source.google_analytics_link.property_id = 1201 - - request = merchant_conversions_v1beta.UpdateConversionSourceRequest( - conversion_source=conversion_source, - ) - - # Make the request - response = await client.update_conversion_source(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_ConversionSourcesService_UpdateConversionSource_async] diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_update_conversion_source_sync.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_update_conversion_source_sync.py deleted file mode 100644 index 07cfe0bc26dd..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_conversion_sources_service_update_conversion_source_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateConversionSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-conversions - - -# [START merchantapi_v1beta_generated_ConversionSourcesService_UpdateConversionSource_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_conversions_v1beta - - -def sample_update_conversion_source(): - # Create a client - client = merchant_conversions_v1beta.ConversionSourcesServiceClient() - - # Initialize request argument(s) - conversion_source = merchant_conversions_v1beta.ConversionSource() - conversion_source.google_analytics_link.property_id = 1201 - - request = merchant_conversions_v1beta.UpdateConversionSourceRequest( - conversion_source=conversion_source, - ) - - # Make the request - response = client.update_conversion_source(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_ConversionSourcesService_UpdateConversionSource_sync] diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.conversions.v1beta.json b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.conversions.v1beta.json deleted file mode 100644 index 7b979a5c445b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.conversions.v1beta.json +++ /dev/null @@ -1,983 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.shopping.merchant.conversions.v1beta", - "version": "v1beta" - } - ], - "language": "PYTHON", - "name": "google-shopping-merchant-conversions", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient", - "shortName": "ConversionSourcesServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient.create_conversion_source", - "method": { - "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService.CreateConversionSource", - "service": { - "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", - "shortName": "ConversionSourcesService" - }, - "shortName": "CreateConversionSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_conversions_v1beta.types.CreateConversionSourceRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "conversion_source", - "type": "google.shopping.merchant_conversions_v1beta.types.ConversionSource" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.shopping.merchant_conversions_v1beta.types.ConversionSource", - "shortName": "create_conversion_source" - }, - "description": "Sample for CreateConversionSource", - "file": "merchantapi_v1beta_generated_conversion_sources_service_create_conversion_source_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_ConversionSourcesService_CreateConversionSource_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_conversion_sources_service_create_conversion_source_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceClient", - "shortName": "ConversionSourcesServiceClient" - }, - "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceClient.create_conversion_source", - "method": { - "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService.CreateConversionSource", - "service": { - "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", - "shortName": "ConversionSourcesService" - }, - "shortName": "CreateConversionSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_conversions_v1beta.types.CreateConversionSourceRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "conversion_source", - "type": "google.shopping.merchant_conversions_v1beta.types.ConversionSource" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.shopping.merchant_conversions_v1beta.types.ConversionSource", - "shortName": "create_conversion_source" - }, - "description": "Sample for CreateConversionSource", - "file": "merchantapi_v1beta_generated_conversion_sources_service_create_conversion_source_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_ConversionSourcesService_CreateConversionSource_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_conversion_sources_service_create_conversion_source_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient", - "shortName": "ConversionSourcesServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient.delete_conversion_source", - "method": { - "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService.DeleteConversionSource", - "service": { - "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", - "shortName": "ConversionSourcesService" - }, - "shortName": "DeleteConversionSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_conversions_v1beta.types.DeleteConversionSourceRequest" - }, - { - "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_conversion_source" - }, - "description": "Sample for DeleteConversionSource", - "file": "merchantapi_v1beta_generated_conversion_sources_service_delete_conversion_source_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_ConversionSourcesService_DeleteConversionSource_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_conversion_sources_service_delete_conversion_source_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceClient", - "shortName": "ConversionSourcesServiceClient" - }, - "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceClient.delete_conversion_source", - "method": { - "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService.DeleteConversionSource", - "service": { - "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", - "shortName": "ConversionSourcesService" - }, - "shortName": "DeleteConversionSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_conversions_v1beta.types.DeleteConversionSourceRequest" - }, - { - "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_conversion_source" - }, - "description": "Sample for DeleteConversionSource", - "file": "merchantapi_v1beta_generated_conversion_sources_service_delete_conversion_source_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_ConversionSourcesService_DeleteConversionSource_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_conversion_sources_service_delete_conversion_source_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient", - "shortName": "ConversionSourcesServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient.get_conversion_source", - "method": { - "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService.GetConversionSource", - "service": { - "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", - "shortName": "ConversionSourcesService" - }, - "shortName": "GetConversionSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_conversions_v1beta.types.GetConversionSourceRequest" - }, - { - "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_conversions_v1beta.types.ConversionSource", - "shortName": "get_conversion_source" - }, - "description": "Sample for GetConversionSource", - "file": "merchantapi_v1beta_generated_conversion_sources_service_get_conversion_source_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_ConversionSourcesService_GetConversionSource_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_conversion_sources_service_get_conversion_source_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceClient", - "shortName": "ConversionSourcesServiceClient" - }, - "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceClient.get_conversion_source", - "method": { - "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService.GetConversionSource", - "service": { - "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", - "shortName": "ConversionSourcesService" - }, - "shortName": "GetConversionSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_conversions_v1beta.types.GetConversionSourceRequest" - }, - { - "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_conversions_v1beta.types.ConversionSource", - "shortName": "get_conversion_source" - }, - "description": "Sample for GetConversionSource", - "file": "merchantapi_v1beta_generated_conversion_sources_service_get_conversion_source_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_ConversionSourcesService_GetConversionSource_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_conversion_sources_service_get_conversion_source_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient", - "shortName": "ConversionSourcesServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient.list_conversion_sources", - "method": { - "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService.ListConversionSources", - "service": { - "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", - "shortName": "ConversionSourcesService" - }, - "shortName": "ListConversionSources" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_conversions_v1beta.types.ListConversionSourcesRequest" - }, - { - "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_conversions_v1beta.services.conversion_sources_service.pagers.ListConversionSourcesAsyncPager", - "shortName": "list_conversion_sources" - }, - "description": "Sample for ListConversionSources", - "file": "merchantapi_v1beta_generated_conversion_sources_service_list_conversion_sources_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_ConversionSourcesService_ListConversionSources_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_conversion_sources_service_list_conversion_sources_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceClient", - "shortName": "ConversionSourcesServiceClient" - }, - "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceClient.list_conversion_sources", - "method": { - "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService.ListConversionSources", - "service": { - "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", - "shortName": "ConversionSourcesService" - }, - "shortName": "ListConversionSources" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_conversions_v1beta.types.ListConversionSourcesRequest" - }, - { - "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_conversions_v1beta.services.conversion_sources_service.pagers.ListConversionSourcesPager", - "shortName": "list_conversion_sources" - }, - "description": "Sample for ListConversionSources", - "file": "merchantapi_v1beta_generated_conversion_sources_service_list_conversion_sources_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_ConversionSourcesService_ListConversionSources_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_conversion_sources_service_list_conversion_sources_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient", - "shortName": "ConversionSourcesServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient.undelete_conversion_source", - "method": { - "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService.UndeleteConversionSource", - "service": { - "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", - "shortName": "ConversionSourcesService" - }, - "shortName": "UndeleteConversionSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_conversions_v1beta.types.UndeleteConversionSourceRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.shopping.merchant_conversions_v1beta.types.ConversionSource", - "shortName": "undelete_conversion_source" - }, - "description": "Sample for UndeleteConversionSource", - "file": "merchantapi_v1beta_generated_conversion_sources_service_undelete_conversion_source_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_ConversionSourcesService_UndeleteConversionSource_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_conversion_sources_service_undelete_conversion_source_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceClient", - "shortName": "ConversionSourcesServiceClient" - }, - "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceClient.undelete_conversion_source", - "method": { - "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService.UndeleteConversionSource", - "service": { - "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", - "shortName": "ConversionSourcesService" - }, - "shortName": "UndeleteConversionSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_conversions_v1beta.types.UndeleteConversionSourceRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.shopping.merchant_conversions_v1beta.types.ConversionSource", - "shortName": "undelete_conversion_source" - }, - "description": "Sample for UndeleteConversionSource", - "file": "merchantapi_v1beta_generated_conversion_sources_service_undelete_conversion_source_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_ConversionSourcesService_UndeleteConversionSource_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_conversion_sources_service_undelete_conversion_source_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient", - "shortName": "ConversionSourcesServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceAsyncClient.update_conversion_source", - "method": { - "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService.UpdateConversionSource", - "service": { - "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", - "shortName": "ConversionSourcesService" - }, - "shortName": "UpdateConversionSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_conversions_v1beta.types.UpdateConversionSourceRequest" - }, - { - "name": "conversion_source", - "type": "google.shopping.merchant_conversions_v1beta.types.ConversionSource" - }, - { - "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_conversions_v1beta.types.ConversionSource", - "shortName": "update_conversion_source" - }, - "description": "Sample for UpdateConversionSource", - "file": "merchantapi_v1beta_generated_conversion_sources_service_update_conversion_source_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_ConversionSourcesService_UpdateConversionSource_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_conversion_sources_service_update_conversion_source_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceClient", - "shortName": "ConversionSourcesServiceClient" - }, - "fullName": "google.shopping.merchant_conversions_v1beta.ConversionSourcesServiceClient.update_conversion_source", - "method": { - "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService.UpdateConversionSource", - "service": { - "fullName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", - "shortName": "ConversionSourcesService" - }, - "shortName": "UpdateConversionSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_conversions_v1beta.types.UpdateConversionSourceRequest" - }, - { - "name": "conversion_source", - "type": "google.shopping.merchant_conversions_v1beta.types.ConversionSource" - }, - { - "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_conversions_v1beta.types.ConversionSource", - "shortName": "update_conversion_source" - }, - "description": "Sample for UpdateConversionSource", - "file": "merchantapi_v1beta_generated_conversion_sources_service_update_conversion_source_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_ConversionSourcesService_UpdateConversionSource_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_conversion_sources_service_update_conversion_source_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/scripts/fixup_merchant_conversions_v1beta_keywords.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/scripts/fixup_merchant_conversions_v1beta_keywords.py deleted file mode 100644 index e0b3604e0ad3..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/scripts/fixup_merchant_conversions_v1beta_keywords.py +++ /dev/null @@ -1,181 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_conversionsCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_conversion_source': ('parent', 'conversion_source', ), - 'delete_conversion_source': ('name', ), - 'get_conversion_source': ('name', ), - 'list_conversion_sources': ('parent', 'page_size', 'page_token', 'show_deleted', ), - 'undelete_conversion_source': ('name', ), - 'update_conversion_source': ('conversion_source', '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_conversionsCallTransformer(), -): - """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_conversions 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-conversions/v1beta/setup.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/setup.py deleted file mode 100644 index f3c03c6e0f40..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/setup.py +++ /dev/null @@ -1,98 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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-conversions' - - -description = "Google Shopping Merchant Conversions API client library" - -version = None - -with open(os.path.join(package_root, 'google/shopping/merchant_conversions/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.0dev,!=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.0dev,!=2.24.0,!=2.25.0", - "proto-plus >= 1.22.3, <2.0.0dev", - "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'", - "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", -] -extras = { -} -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-conversions" - -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-conversions/v1beta/testing/constraints-3.10.txt b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.10.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.10.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.11.txt b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.11.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.11.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.12.txt b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.12.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.12.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.13.txt b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.13.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.13.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.7.txt b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.7.txt deleted file mode 100644 index fc812592b0ee..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.7.txt +++ /dev/null @@ -1,10 +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.0dev", -# 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 diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.8.txt b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.8.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.8.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.9.txt b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.9.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/testing/constraints-3.9.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/tests/__init__.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-conversions/v1beta/tests/unit/__init__.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-conversions/v1beta/tests/unit/gapic/__init__.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-conversions/v1beta/tests/unit/gapic/merchant_conversions_v1beta/__init__.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/tests/unit/gapic/merchant_conversions_v1beta/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/tests/unit/gapic/merchant_conversions_v1beta/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-conversions/v1beta/tests/unit/gapic/merchant_conversions_v1beta/test_conversion_sources_service.py b/owl-bot-staging/google-shopping-merchant-conversions/v1beta/tests/unit/gapic/merchant_conversions_v1beta/test_conversion_sources_service.py deleted file mode 100644 index 01083599d323..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/tests/unit/gapic/merchant_conversions_v1beta/test_conversion_sources_service.py +++ /dev/null @@ -1,5664 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_conversions_v1beta.services.conversion_sources_service import ConversionSourcesServiceAsyncClient -from google.shopping.merchant_conversions_v1beta.services.conversion_sources_service import ConversionSourcesServiceClient -from google.shopping.merchant_conversions_v1beta.services.conversion_sources_service import pagers -from google.shopping.merchant_conversions_v1beta.services.conversion_sources_service import transports -from google.shopping.merchant_conversions_v1beta.types import conversionsources -import google.auth - - -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 ConversionSourcesServiceClient._get_default_mtls_endpoint(None) is None - assert ConversionSourcesServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ConversionSourcesServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ConversionSourcesServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ConversionSourcesServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ConversionSourcesServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert ConversionSourcesServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert ConversionSourcesServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert ConversionSourcesServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - ConversionSourcesServiceClient._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 ConversionSourcesServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert ConversionSourcesServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert ConversionSourcesServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - ConversionSourcesServiceClient._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 ConversionSourcesServiceClient._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 ConversionSourcesServiceClient._get_client_cert_source(None, False) is None - assert ConversionSourcesServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert ConversionSourcesServiceClient._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 ConversionSourcesServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert ConversionSourcesServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(ConversionSourcesServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ConversionSourcesServiceClient)) -@mock.patch.object(ConversionSourcesServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ConversionSourcesServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = ConversionSourcesServiceClient._DEFAULT_UNIVERSE - default_endpoint = ConversionSourcesServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = ConversionSourcesServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert ConversionSourcesServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert ConversionSourcesServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == ConversionSourcesServiceClient.DEFAULT_MTLS_ENDPOINT - assert ConversionSourcesServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert ConversionSourcesServiceClient._get_api_endpoint(None, None, default_universe, "always") == ConversionSourcesServiceClient.DEFAULT_MTLS_ENDPOINT - assert ConversionSourcesServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == ConversionSourcesServiceClient.DEFAULT_MTLS_ENDPOINT - assert ConversionSourcesServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert ConversionSourcesServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - ConversionSourcesServiceClient._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 ConversionSourcesServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert ConversionSourcesServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert ConversionSourcesServiceClient._get_universe_domain(None, None) == ConversionSourcesServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - ConversionSourcesServiceClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ConversionSourcesServiceClient, "grpc"), - (ConversionSourcesServiceAsyncClient, "grpc_asyncio"), - (ConversionSourcesServiceClient, "rest"), -]) -def test_conversion_sources_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.ConversionSourcesServiceGrpcTransport, "grpc"), - (transports.ConversionSourcesServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.ConversionSourcesServiceRestTransport, "rest"), -]) -def test_conversion_sources_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", [ - (ConversionSourcesServiceClient, "grpc"), - (ConversionSourcesServiceAsyncClient, "grpc_asyncio"), - (ConversionSourcesServiceClient, "rest"), -]) -def test_conversion_sources_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_conversion_sources_service_client_get_transport_class(): - transport = ConversionSourcesServiceClient.get_transport_class() - available_transports = [ - transports.ConversionSourcesServiceGrpcTransport, - transports.ConversionSourcesServiceRestTransport, - ] - assert transport in available_transports - - transport = ConversionSourcesServiceClient.get_transport_class("grpc") - assert transport == transports.ConversionSourcesServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ConversionSourcesServiceClient, transports.ConversionSourcesServiceGrpcTransport, "grpc"), - (ConversionSourcesServiceAsyncClient, transports.ConversionSourcesServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (ConversionSourcesServiceClient, transports.ConversionSourcesServiceRestTransport, "rest"), -]) -@mock.patch.object(ConversionSourcesServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ConversionSourcesServiceClient)) -@mock.patch.object(ConversionSourcesServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ConversionSourcesServiceAsyncClient)) -def test_conversion_sources_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(ConversionSourcesServiceClient, '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(ConversionSourcesServiceClient, '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", [ - (ConversionSourcesServiceClient, transports.ConversionSourcesServiceGrpcTransport, "grpc", "true"), - (ConversionSourcesServiceAsyncClient, transports.ConversionSourcesServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ConversionSourcesServiceClient, transports.ConversionSourcesServiceGrpcTransport, "grpc", "false"), - (ConversionSourcesServiceAsyncClient, transports.ConversionSourcesServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (ConversionSourcesServiceClient, transports.ConversionSourcesServiceRestTransport, "rest", "true"), - (ConversionSourcesServiceClient, transports.ConversionSourcesServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(ConversionSourcesServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ConversionSourcesServiceClient)) -@mock.patch.object(ConversionSourcesServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ConversionSourcesServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_conversion_sources_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", [ - ConversionSourcesServiceClient, ConversionSourcesServiceAsyncClient -]) -@mock.patch.object(ConversionSourcesServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversionSourcesServiceClient)) -@mock.patch.object(ConversionSourcesServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversionSourcesServiceAsyncClient)) -def test_conversion_sources_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", [ - ConversionSourcesServiceClient, ConversionSourcesServiceAsyncClient -]) -@mock.patch.object(ConversionSourcesServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ConversionSourcesServiceClient)) -@mock.patch.object(ConversionSourcesServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ConversionSourcesServiceAsyncClient)) -def test_conversion_sources_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = ConversionSourcesServiceClient._DEFAULT_UNIVERSE - default_endpoint = ConversionSourcesServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = ConversionSourcesServiceClient._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", [ - (ConversionSourcesServiceClient, transports.ConversionSourcesServiceGrpcTransport, "grpc"), - (ConversionSourcesServiceAsyncClient, transports.ConversionSourcesServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (ConversionSourcesServiceClient, transports.ConversionSourcesServiceRestTransport, "rest"), -]) -def test_conversion_sources_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", [ - (ConversionSourcesServiceClient, transports.ConversionSourcesServiceGrpcTransport, "grpc", grpc_helpers), - (ConversionSourcesServiceAsyncClient, transports.ConversionSourcesServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (ConversionSourcesServiceClient, transports.ConversionSourcesServiceRestTransport, "rest", None), -]) -def test_conversion_sources_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_conversion_sources_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_conversions_v1beta.services.conversion_sources_service.transports.ConversionSourcesServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ConversionSourcesServiceClient( - 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", [ - (ConversionSourcesServiceClient, transports.ConversionSourcesServiceGrpcTransport, "grpc", grpc_helpers), - (ConversionSourcesServiceAsyncClient, transports.ConversionSourcesServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_conversion_sources_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", [ - conversionsources.CreateConversionSourceRequest, - dict, -]) -def test_create_conversion_source(request_type, transport: str = 'grpc'): - client = ConversionSourcesServiceClient( - 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_conversion_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversionsources.ConversionSource( - name='name_value', - state=conversionsources.ConversionSource.State.ACTIVE, - controller=conversionsources.ConversionSource.Controller.MERCHANT, - ) - response = client.create_conversion_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = conversionsources.CreateConversionSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, conversionsources.ConversionSource) - assert response.name == 'name_value' - assert response.state == conversionsources.ConversionSource.State.ACTIVE - assert response.controller == conversionsources.ConversionSource.Controller.MERCHANT - - -def test_create_conversion_source_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 = ConversionSourcesServiceClient( - 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 = conversionsources.CreateConversionSourceRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_conversion_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_conversion_source(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversionsources.CreateConversionSourceRequest( - parent='parent_value', - ) - -def test_create_conversion_source_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ConversionSourcesServiceClient( - 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_conversion_source in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_conversion_source] = mock_rpc - request = {} - client.create_conversion_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_conversion_source(request) - - # Establish that a new wrapper 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_conversion_source_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = ConversionSourcesServiceAsyncClient( - 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_conversion_source in client._client._transport._wrapped_methods - - # 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_conversion_source] = mock_rpc - - request = {} - await client.create_conversion_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.create_conversion_source(request) - - # Establish that a new wrapper 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_conversion_source_async(transport: str = 'grpc_asyncio', request_type=conversionsources.CreateConversionSourceRequest): - client = ConversionSourcesServiceAsyncClient( - 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_conversion_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversionsources.ConversionSource( - name='name_value', - state=conversionsources.ConversionSource.State.ACTIVE, - controller=conversionsources.ConversionSource.Controller.MERCHANT, - )) - response = await client.create_conversion_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = conversionsources.CreateConversionSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, conversionsources.ConversionSource) - assert response.name == 'name_value' - assert response.state == conversionsources.ConversionSource.State.ACTIVE - assert response.controller == conversionsources.ConversionSource.Controller.MERCHANT - - -@pytest.mark.asyncio -async def test_create_conversion_source_async_from_dict(): - await test_create_conversion_source_async(request_type=dict) - -def test_create_conversion_source_field_headers(): - client = ConversionSourcesServiceClient( - 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 = conversionsources.CreateConversionSourceRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_conversion_source), - '__call__') as call: - call.return_value = conversionsources.ConversionSource() - client.create_conversion_source(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_conversion_source_field_headers_async(): - client = ConversionSourcesServiceAsyncClient( - 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 = conversionsources.CreateConversionSourceRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_conversion_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversionsources.ConversionSource()) - await client.create_conversion_source(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_conversion_source_flattened(): - client = ConversionSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_conversion_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversionsources.ConversionSource() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_conversion_source( - parent='parent_value', - conversion_source=conversionsources.ConversionSource(google_analytics_link=conversionsources.GoogleAnalyticsLink(property_id=1201)), - ) - - # 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].conversion_source - mock_val = conversionsources.ConversionSource(google_analytics_link=conversionsources.GoogleAnalyticsLink(property_id=1201)) - assert arg == mock_val - - -def test_create_conversion_source_flattened_error(): - client = ConversionSourcesServiceClient( - 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_conversion_source( - conversionsources.CreateConversionSourceRequest(), - parent='parent_value', - conversion_source=conversionsources.ConversionSource(google_analytics_link=conversionsources.GoogleAnalyticsLink(property_id=1201)), - ) - -@pytest.mark.asyncio -async def test_create_conversion_source_flattened_async(): - client = ConversionSourcesServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_conversion_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversionsources.ConversionSource() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversionsources.ConversionSource()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_conversion_source( - parent='parent_value', - conversion_source=conversionsources.ConversionSource(google_analytics_link=conversionsources.GoogleAnalyticsLink(property_id=1201)), - ) - - # 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].conversion_source - mock_val = conversionsources.ConversionSource(google_analytics_link=conversionsources.GoogleAnalyticsLink(property_id=1201)) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_conversion_source_flattened_error_async(): - client = ConversionSourcesServiceAsyncClient( - 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_conversion_source( - conversionsources.CreateConversionSourceRequest(), - parent='parent_value', - conversion_source=conversionsources.ConversionSource(google_analytics_link=conversionsources.GoogleAnalyticsLink(property_id=1201)), - ) - - -@pytest.mark.parametrize("request_type", [ - conversionsources.UpdateConversionSourceRequest, - dict, -]) -def test_update_conversion_source(request_type, transport: str = 'grpc'): - client = ConversionSourcesServiceClient( - 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_conversion_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversionsources.ConversionSource( - name='name_value', - state=conversionsources.ConversionSource.State.ACTIVE, - controller=conversionsources.ConversionSource.Controller.MERCHANT, - ) - response = client.update_conversion_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = conversionsources.UpdateConversionSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, conversionsources.ConversionSource) - assert response.name == 'name_value' - assert response.state == conversionsources.ConversionSource.State.ACTIVE - assert response.controller == conversionsources.ConversionSource.Controller.MERCHANT - - -def test_update_conversion_source_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 = ConversionSourcesServiceClient( - 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 = conversionsources.UpdateConversionSourceRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_conversion_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_conversion_source(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversionsources.UpdateConversionSourceRequest( - ) - -def test_update_conversion_source_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ConversionSourcesServiceClient( - 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_conversion_source in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_conversion_source] = mock_rpc - request = {} - client.update_conversion_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_conversion_source(request) - - # Establish that a new wrapper 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_conversion_source_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = ConversionSourcesServiceAsyncClient( - 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_conversion_source in client._client._transport._wrapped_methods - - # 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_conversion_source] = mock_rpc - - request = {} - await client.update_conversion_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_conversion_source(request) - - # Establish that a new wrapper 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_conversion_source_async(transport: str = 'grpc_asyncio', request_type=conversionsources.UpdateConversionSourceRequest): - client = ConversionSourcesServiceAsyncClient( - 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_conversion_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversionsources.ConversionSource( - name='name_value', - state=conversionsources.ConversionSource.State.ACTIVE, - controller=conversionsources.ConversionSource.Controller.MERCHANT, - )) - response = await client.update_conversion_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = conversionsources.UpdateConversionSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, conversionsources.ConversionSource) - assert response.name == 'name_value' - assert response.state == conversionsources.ConversionSource.State.ACTIVE - assert response.controller == conversionsources.ConversionSource.Controller.MERCHANT - - -@pytest.mark.asyncio -async def test_update_conversion_source_async_from_dict(): - await test_update_conversion_source_async(request_type=dict) - -def test_update_conversion_source_field_headers(): - client = ConversionSourcesServiceClient( - 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 = conversionsources.UpdateConversionSourceRequest() - - request.conversion_source.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_conversion_source), - '__call__') as call: - call.return_value = conversionsources.ConversionSource() - client.update_conversion_source(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', - 'conversion_source.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_conversion_source_field_headers_async(): - client = ConversionSourcesServiceAsyncClient( - 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 = conversionsources.UpdateConversionSourceRequest() - - request.conversion_source.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_conversion_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversionsources.ConversionSource()) - await client.update_conversion_source(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', - 'conversion_source.name=name_value', - ) in kw['metadata'] - - -def test_update_conversion_source_flattened(): - client = ConversionSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_conversion_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversionsources.ConversionSource() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_conversion_source( - conversion_source=conversionsources.ConversionSource(google_analytics_link=conversionsources.GoogleAnalyticsLink(property_id=1201)), - 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].conversion_source - mock_val = conversionsources.ConversionSource(google_analytics_link=conversionsources.GoogleAnalyticsLink(property_id=1201)) - 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_conversion_source_flattened_error(): - client = ConversionSourcesServiceClient( - 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_conversion_source( - conversionsources.UpdateConversionSourceRequest(), - conversion_source=conversionsources.ConversionSource(google_analytics_link=conversionsources.GoogleAnalyticsLink(property_id=1201)), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_conversion_source_flattened_async(): - client = ConversionSourcesServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_conversion_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversionsources.ConversionSource() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversionsources.ConversionSource()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_conversion_source( - conversion_source=conversionsources.ConversionSource(google_analytics_link=conversionsources.GoogleAnalyticsLink(property_id=1201)), - 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].conversion_source - mock_val = conversionsources.ConversionSource(google_analytics_link=conversionsources.GoogleAnalyticsLink(property_id=1201)) - 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_conversion_source_flattened_error_async(): - client = ConversionSourcesServiceAsyncClient( - 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_conversion_source( - conversionsources.UpdateConversionSourceRequest(), - conversion_source=conversionsources.ConversionSource(google_analytics_link=conversionsources.GoogleAnalyticsLink(property_id=1201)), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - conversionsources.DeleteConversionSourceRequest, - dict, -]) -def test_delete_conversion_source(request_type, transport: str = 'grpc'): - client = ConversionSourcesServiceClient( - 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_conversion_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_conversion_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = conversionsources.DeleteConversionSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_conversion_source_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 = ConversionSourcesServiceClient( - 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 = conversionsources.DeleteConversionSourceRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_conversion_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_conversion_source(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversionsources.DeleteConversionSourceRequest( - name='name_value', - ) - -def test_delete_conversion_source_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ConversionSourcesServiceClient( - 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_conversion_source in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_conversion_source] = mock_rpc - request = {} - client.delete_conversion_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_conversion_source(request) - - # Establish that a new wrapper 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_conversion_source_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = ConversionSourcesServiceAsyncClient( - 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_conversion_source in client._client._transport._wrapped_methods - - # 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_conversion_source] = mock_rpc - - request = {} - await client.delete_conversion_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.delete_conversion_source(request) - - # Establish that a new wrapper 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_conversion_source_async(transport: str = 'grpc_asyncio', request_type=conversionsources.DeleteConversionSourceRequest): - client = ConversionSourcesServiceAsyncClient( - 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_conversion_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_conversion_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = conversionsources.DeleteConversionSourceRequest() - 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_conversion_source_async_from_dict(): - await test_delete_conversion_source_async(request_type=dict) - -def test_delete_conversion_source_field_headers(): - client = ConversionSourcesServiceClient( - 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 = conversionsources.DeleteConversionSourceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_conversion_source), - '__call__') as call: - call.return_value = None - client.delete_conversion_source(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_conversion_source_field_headers_async(): - client = ConversionSourcesServiceAsyncClient( - 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 = conversionsources.DeleteConversionSourceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_conversion_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_conversion_source(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_conversion_source_flattened(): - client = ConversionSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_conversion_source), - '__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_conversion_source( - 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_conversion_source_flattened_error(): - client = ConversionSourcesServiceClient( - 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_conversion_source( - conversionsources.DeleteConversionSourceRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_conversion_source_flattened_async(): - client = ConversionSourcesServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_conversion_source), - '__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_conversion_source( - 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_conversion_source_flattened_error_async(): - client = ConversionSourcesServiceAsyncClient( - 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_conversion_source( - conversionsources.DeleteConversionSourceRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - conversionsources.UndeleteConversionSourceRequest, - dict, -]) -def test_undelete_conversion_source(request_type, transport: str = 'grpc'): - client = ConversionSourcesServiceClient( - 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.undelete_conversion_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversionsources.ConversionSource( - name='name_value', - state=conversionsources.ConversionSource.State.ACTIVE, - controller=conversionsources.ConversionSource.Controller.MERCHANT, - ) - response = client.undelete_conversion_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = conversionsources.UndeleteConversionSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, conversionsources.ConversionSource) - assert response.name == 'name_value' - assert response.state == conversionsources.ConversionSource.State.ACTIVE - assert response.controller == conversionsources.ConversionSource.Controller.MERCHANT - - -def test_undelete_conversion_source_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 = ConversionSourcesServiceClient( - 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 = conversionsources.UndeleteConversionSourceRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undelete_conversion_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.undelete_conversion_source(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversionsources.UndeleteConversionSourceRequest( - name='name_value', - ) - -def test_undelete_conversion_source_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ConversionSourcesServiceClient( - 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.undelete_conversion_source in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.undelete_conversion_source] = mock_rpc - request = {} - client.undelete_conversion_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.undelete_conversion_source(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_undelete_conversion_source_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = ConversionSourcesServiceAsyncClient( - 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.undelete_conversion_source in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.undelete_conversion_source] = mock_rpc - - request = {} - await client.undelete_conversion_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.undelete_conversion_source(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_undelete_conversion_source_async(transport: str = 'grpc_asyncio', request_type=conversionsources.UndeleteConversionSourceRequest): - client = ConversionSourcesServiceAsyncClient( - 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.undelete_conversion_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversionsources.ConversionSource( - name='name_value', - state=conversionsources.ConversionSource.State.ACTIVE, - controller=conversionsources.ConversionSource.Controller.MERCHANT, - )) - response = await client.undelete_conversion_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = conversionsources.UndeleteConversionSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, conversionsources.ConversionSource) - assert response.name == 'name_value' - assert response.state == conversionsources.ConversionSource.State.ACTIVE - assert response.controller == conversionsources.ConversionSource.Controller.MERCHANT - - -@pytest.mark.asyncio -async def test_undelete_conversion_source_async_from_dict(): - await test_undelete_conversion_source_async(request_type=dict) - -def test_undelete_conversion_source_field_headers(): - client = ConversionSourcesServiceClient( - 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 = conversionsources.UndeleteConversionSourceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undelete_conversion_source), - '__call__') as call: - call.return_value = conversionsources.ConversionSource() - client.undelete_conversion_source(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_undelete_conversion_source_field_headers_async(): - client = ConversionSourcesServiceAsyncClient( - 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 = conversionsources.UndeleteConversionSourceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undelete_conversion_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversionsources.ConversionSource()) - await client.undelete_conversion_source(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", [ - conversionsources.GetConversionSourceRequest, - dict, -]) -def test_get_conversion_source(request_type, transport: str = 'grpc'): - client = ConversionSourcesServiceClient( - 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_conversion_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversionsources.ConversionSource( - name='name_value', - state=conversionsources.ConversionSource.State.ACTIVE, - controller=conversionsources.ConversionSource.Controller.MERCHANT, - ) - response = client.get_conversion_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = conversionsources.GetConversionSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, conversionsources.ConversionSource) - assert response.name == 'name_value' - assert response.state == conversionsources.ConversionSource.State.ACTIVE - assert response.controller == conversionsources.ConversionSource.Controller.MERCHANT - - -def test_get_conversion_source_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 = ConversionSourcesServiceClient( - 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 = conversionsources.GetConversionSourceRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_conversion_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_conversion_source(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversionsources.GetConversionSourceRequest( - name='name_value', - ) - -def test_get_conversion_source_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ConversionSourcesServiceClient( - 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_conversion_source in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_conversion_source] = mock_rpc - request = {} - client.get_conversion_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_conversion_source(request) - - # Establish that a new wrapper 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_conversion_source_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = ConversionSourcesServiceAsyncClient( - 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_conversion_source in client._client._transport._wrapped_methods - - # 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_conversion_source] = mock_rpc - - request = {} - await client.get_conversion_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_conversion_source(request) - - # Establish that a new wrapper 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_conversion_source_async(transport: str = 'grpc_asyncio', request_type=conversionsources.GetConversionSourceRequest): - client = ConversionSourcesServiceAsyncClient( - 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_conversion_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversionsources.ConversionSource( - name='name_value', - state=conversionsources.ConversionSource.State.ACTIVE, - controller=conversionsources.ConversionSource.Controller.MERCHANT, - )) - response = await client.get_conversion_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = conversionsources.GetConversionSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, conversionsources.ConversionSource) - assert response.name == 'name_value' - assert response.state == conversionsources.ConversionSource.State.ACTIVE - assert response.controller == conversionsources.ConversionSource.Controller.MERCHANT - - -@pytest.mark.asyncio -async def test_get_conversion_source_async_from_dict(): - await test_get_conversion_source_async(request_type=dict) - -def test_get_conversion_source_field_headers(): - client = ConversionSourcesServiceClient( - 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 = conversionsources.GetConversionSourceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_conversion_source), - '__call__') as call: - call.return_value = conversionsources.ConversionSource() - client.get_conversion_source(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_conversion_source_field_headers_async(): - client = ConversionSourcesServiceAsyncClient( - 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 = conversionsources.GetConversionSourceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_conversion_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversionsources.ConversionSource()) - await client.get_conversion_source(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_conversion_source_flattened(): - client = ConversionSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_conversion_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversionsources.ConversionSource() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_conversion_source( - 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_conversion_source_flattened_error(): - client = ConversionSourcesServiceClient( - 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_conversion_source( - conversionsources.GetConversionSourceRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_conversion_source_flattened_async(): - client = ConversionSourcesServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_conversion_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversionsources.ConversionSource() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversionsources.ConversionSource()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_conversion_source( - 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_conversion_source_flattened_error_async(): - client = ConversionSourcesServiceAsyncClient( - 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_conversion_source( - conversionsources.GetConversionSourceRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - conversionsources.ListConversionSourcesRequest, - dict, -]) -def test_list_conversion_sources(request_type, transport: str = 'grpc'): - client = ConversionSourcesServiceClient( - 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_conversion_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversionsources.ListConversionSourcesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_conversion_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = conversionsources.ListConversionSourcesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListConversionSourcesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_conversion_sources_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 = ConversionSourcesServiceClient( - 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 = conversionsources.ListConversionSourcesRequest( - 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_conversion_sources), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_conversion_sources(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversionsources.ListConversionSourcesRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_conversion_sources_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ConversionSourcesServiceClient( - 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_conversion_sources in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_conversion_sources] = mock_rpc - request = {} - client.list_conversion_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_conversion_sources(request) - - # Establish that a new wrapper 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_conversion_sources_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = ConversionSourcesServiceAsyncClient( - 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_conversion_sources in client._client._transport._wrapped_methods - - # 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_conversion_sources] = mock_rpc - - request = {} - await client.list_conversion_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_conversion_sources(request) - - # Establish that a new wrapper 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_conversion_sources_async(transport: str = 'grpc_asyncio', request_type=conversionsources.ListConversionSourcesRequest): - client = ConversionSourcesServiceAsyncClient( - 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_conversion_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversionsources.ListConversionSourcesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_conversion_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = conversionsources.ListConversionSourcesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListConversionSourcesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_conversion_sources_async_from_dict(): - await test_list_conversion_sources_async(request_type=dict) - -def test_list_conversion_sources_field_headers(): - client = ConversionSourcesServiceClient( - 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 = conversionsources.ListConversionSourcesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversion_sources), - '__call__') as call: - call.return_value = conversionsources.ListConversionSourcesResponse() - client.list_conversion_sources(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_conversion_sources_field_headers_async(): - client = ConversionSourcesServiceAsyncClient( - 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 = conversionsources.ListConversionSourcesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversion_sources), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversionsources.ListConversionSourcesResponse()) - await client.list_conversion_sources(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_conversion_sources_flattened(): - client = ConversionSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversion_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversionsources.ListConversionSourcesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_conversion_sources( - 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_conversion_sources_flattened_error(): - client = ConversionSourcesServiceClient( - 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_conversion_sources( - conversionsources.ListConversionSourcesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_conversion_sources_flattened_async(): - client = ConversionSourcesServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversion_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversionsources.ListConversionSourcesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversionsources.ListConversionSourcesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_conversion_sources( - 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_conversion_sources_flattened_error_async(): - client = ConversionSourcesServiceAsyncClient( - 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_conversion_sources( - conversionsources.ListConversionSourcesRequest(), - parent='parent_value', - ) - - -def test_list_conversion_sources_pager(transport_name: str = "grpc"): - client = ConversionSourcesServiceClient( - 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_conversion_sources), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - conversionsources.ListConversionSourcesResponse( - conversion_sources=[ - conversionsources.ConversionSource(), - conversionsources.ConversionSource(), - conversionsources.ConversionSource(), - ], - next_page_token='abc', - ), - conversionsources.ListConversionSourcesResponse( - conversion_sources=[], - next_page_token='def', - ), - conversionsources.ListConversionSourcesResponse( - conversion_sources=[ - conversionsources.ConversionSource(), - ], - next_page_token='ghi', - ), - conversionsources.ListConversionSourcesResponse( - conversion_sources=[ - conversionsources.ConversionSource(), - conversionsources.ConversionSource(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_conversion_sources(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, conversionsources.ConversionSource) - for i in results) -def test_list_conversion_sources_pages(transport_name: str = "grpc"): - client = ConversionSourcesServiceClient( - 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_conversion_sources), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - conversionsources.ListConversionSourcesResponse( - conversion_sources=[ - conversionsources.ConversionSource(), - conversionsources.ConversionSource(), - conversionsources.ConversionSource(), - ], - next_page_token='abc', - ), - conversionsources.ListConversionSourcesResponse( - conversion_sources=[], - next_page_token='def', - ), - conversionsources.ListConversionSourcesResponse( - conversion_sources=[ - conversionsources.ConversionSource(), - ], - next_page_token='ghi', - ), - conversionsources.ListConversionSourcesResponse( - conversion_sources=[ - conversionsources.ConversionSource(), - conversionsources.ConversionSource(), - ], - ), - RuntimeError, - ) - pages = list(client.list_conversion_sources(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_conversion_sources_async_pager(): - client = ConversionSourcesServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversion_sources), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - conversionsources.ListConversionSourcesResponse( - conversion_sources=[ - conversionsources.ConversionSource(), - conversionsources.ConversionSource(), - conversionsources.ConversionSource(), - ], - next_page_token='abc', - ), - conversionsources.ListConversionSourcesResponse( - conversion_sources=[], - next_page_token='def', - ), - conversionsources.ListConversionSourcesResponse( - conversion_sources=[ - conversionsources.ConversionSource(), - ], - next_page_token='ghi', - ), - conversionsources.ListConversionSourcesResponse( - conversion_sources=[ - conversionsources.ConversionSource(), - conversionsources.ConversionSource(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_conversion_sources(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, conversionsources.ConversionSource) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_conversion_sources_async_pages(): - client = ConversionSourcesServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversion_sources), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - conversionsources.ListConversionSourcesResponse( - conversion_sources=[ - conversionsources.ConversionSource(), - conversionsources.ConversionSource(), - conversionsources.ConversionSource(), - ], - next_page_token='abc', - ), - conversionsources.ListConversionSourcesResponse( - conversion_sources=[], - next_page_token='def', - ), - conversionsources.ListConversionSourcesResponse( - conversion_sources=[ - conversionsources.ConversionSource(), - ], - next_page_token='ghi', - ), - conversionsources.ListConversionSourcesResponse( - conversion_sources=[ - conversionsources.ConversionSource(), - conversionsources.ConversionSource(), - ], - ), - 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_conversion_sources(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_create_conversion_source_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 = ConversionSourcesServiceClient( - 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_conversion_source in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_conversion_source] = mock_rpc - - request = {} - client.create_conversion_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_conversion_source(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_conversion_source_rest_required_fields(request_type=conversionsources.CreateConversionSourceRequest): - transport_class = transports.ConversionSourcesServiceRestTransport - - 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_conversion_source._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_conversion_source._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 = ConversionSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = conversionsources.ConversionSource() - # 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 = conversionsources.ConversionSource.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_conversion_source(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_conversion_source_rest_unset_required_fields(): - transport = transports.ConversionSourcesServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_conversion_source._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "conversionSource", ))) - - -def test_create_conversion_source_rest_flattened(): - client = ConversionSourcesServiceClient( - 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 = conversionsources.ConversionSource() - - # 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', - conversion_source=conversionsources.ConversionSource(google_analytics_link=conversionsources.GoogleAnalyticsLink(property_id=1201)), - ) - 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 = conversionsources.ConversionSource.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_conversion_source(**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/conversions/v1beta/{parent=accounts/*}/conversionSources" % client.transport._host, args[1]) - - -def test_create_conversion_source_rest_flattened_error(transport: str = 'rest'): - client = ConversionSourcesServiceClient( - 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_conversion_source( - conversionsources.CreateConversionSourceRequest(), - parent='parent_value', - conversion_source=conversionsources.ConversionSource(google_analytics_link=conversionsources.GoogleAnalyticsLink(property_id=1201)), - ) - - -def test_update_conversion_source_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 = ConversionSourcesServiceClient( - 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_conversion_source in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_conversion_source] = mock_rpc - - request = {} - client.update_conversion_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_conversion_source(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_conversion_source_rest_required_fields(request_type=conversionsources.UpdateConversionSourceRequest): - transport_class = transports.ConversionSourcesServiceRestTransport - - 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_conversion_source._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_conversion_source._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 = ConversionSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = conversionsources.ConversionSource() - # 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 = conversionsources.ConversionSource.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_conversion_source(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_conversion_source_rest_unset_required_fields(): - transport = transports.ConversionSourcesServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_conversion_source._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("conversionSource", "updateMask", ))) - - -def test_update_conversion_source_rest_flattened(): - client = ConversionSourcesServiceClient( - 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 = conversionsources.ConversionSource() - - # get arguments that satisfy an http rule for this method - sample_request = {'conversion_source': {'name': 'accounts/sample1/conversionSources/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - conversion_source=conversionsources.ConversionSource(google_analytics_link=conversionsources.GoogleAnalyticsLink(property_id=1201)), - 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 = conversionsources.ConversionSource.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_conversion_source(**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/conversions/v1beta/{conversion_source.name=accounts/*/conversionSources/*}" % client.transport._host, args[1]) - - -def test_update_conversion_source_rest_flattened_error(transport: str = 'rest'): - client = ConversionSourcesServiceClient( - 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_conversion_source( - conversionsources.UpdateConversionSourceRequest(), - conversion_source=conversionsources.ConversionSource(google_analytics_link=conversionsources.GoogleAnalyticsLink(property_id=1201)), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_conversion_source_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 = ConversionSourcesServiceClient( - 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_conversion_source in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_conversion_source] = mock_rpc - - request = {} - client.delete_conversion_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_conversion_source(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_conversion_source_rest_required_fields(request_type=conversionsources.DeleteConversionSourceRequest): - transport_class = transports.ConversionSourcesServiceRestTransport - - 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_conversion_source._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_conversion_source._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 = ConversionSourcesServiceClient( - 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_conversion_source(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_conversion_source_rest_unset_required_fields(): - transport = transports.ConversionSourcesServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_conversion_source._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_delete_conversion_source_rest_flattened(): - client = ConversionSourcesServiceClient( - 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/conversionSources/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_conversion_source(**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/conversions/v1beta/{name=accounts/*/conversionSources/*}" % client.transport._host, args[1]) - - -def test_delete_conversion_source_rest_flattened_error(transport: str = 'rest'): - client = ConversionSourcesServiceClient( - 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_conversion_source( - conversionsources.DeleteConversionSourceRequest(), - name='name_value', - ) - - -def test_undelete_conversion_source_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 = ConversionSourcesServiceClient( - 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.undelete_conversion_source in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.undelete_conversion_source] = mock_rpc - - request = {} - client.undelete_conversion_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.undelete_conversion_source(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_undelete_conversion_source_rest_required_fields(request_type=conversionsources.UndeleteConversionSourceRequest): - transport_class = transports.ConversionSourcesServiceRestTransport - - 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()).undelete_conversion_source._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()).undelete_conversion_source._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 = ConversionSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = conversionsources.ConversionSource() - # 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 = conversionsources.ConversionSource.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.undelete_conversion_source(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_undelete_conversion_source_rest_unset_required_fields(): - transport = transports.ConversionSourcesServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.undelete_conversion_source._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_conversion_source_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 = ConversionSourcesServiceClient( - 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_conversion_source in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_conversion_source] = mock_rpc - - request = {} - client.get_conversion_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_conversion_source(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_conversion_source_rest_required_fields(request_type=conversionsources.GetConversionSourceRequest): - transport_class = transports.ConversionSourcesServiceRestTransport - - 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_conversion_source._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_conversion_source._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 = ConversionSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = conversionsources.ConversionSource() - # 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 = conversionsources.ConversionSource.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_conversion_source(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_conversion_source_rest_unset_required_fields(): - transport = transports.ConversionSourcesServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_conversion_source._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_conversion_source_rest_flattened(): - client = ConversionSourcesServiceClient( - 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 = conversionsources.ConversionSource() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/conversionSources/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 = conversionsources.ConversionSource.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_conversion_source(**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/conversions/v1beta/{name=accounts/*/conversionSources/*}" % client.transport._host, args[1]) - - -def test_get_conversion_source_rest_flattened_error(transport: str = 'rest'): - client = ConversionSourcesServiceClient( - 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_conversion_source( - conversionsources.GetConversionSourceRequest(), - name='name_value', - ) - - -def test_list_conversion_sources_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 = ConversionSourcesServiceClient( - 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_conversion_sources in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_conversion_sources] = mock_rpc - - request = {} - client.list_conversion_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_conversion_sources(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_conversion_sources_rest_required_fields(request_type=conversionsources.ListConversionSourcesRequest): - transport_class = transports.ConversionSourcesServiceRestTransport - - 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_conversion_sources._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_conversion_sources._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", "show_deleted", )) - 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 = ConversionSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = conversionsources.ListConversionSourcesResponse() - # 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 = conversionsources.ListConversionSourcesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_conversion_sources(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_conversion_sources_rest_unset_required_fields(): - transport = transports.ConversionSourcesServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_conversion_sources._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", "showDeleted", )) & set(("parent", ))) - - -def test_list_conversion_sources_rest_flattened(): - client = ConversionSourcesServiceClient( - 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 = conversionsources.ListConversionSourcesResponse() - - # 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 = conversionsources.ListConversionSourcesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_conversion_sources(**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/conversions/v1beta/{parent=accounts/*}/conversionSources" % client.transport._host, args[1]) - - -def test_list_conversion_sources_rest_flattened_error(transport: str = 'rest'): - client = ConversionSourcesServiceClient( - 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_conversion_sources( - conversionsources.ListConversionSourcesRequest(), - parent='parent_value', - ) - - -def test_list_conversion_sources_rest_pager(transport: str = 'rest'): - client = ConversionSourcesServiceClient( - 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 = ( - conversionsources.ListConversionSourcesResponse( - conversion_sources=[ - conversionsources.ConversionSource(), - conversionsources.ConversionSource(), - conversionsources.ConversionSource(), - ], - next_page_token='abc', - ), - conversionsources.ListConversionSourcesResponse( - conversion_sources=[], - next_page_token='def', - ), - conversionsources.ListConversionSourcesResponse( - conversion_sources=[ - conversionsources.ConversionSource(), - ], - next_page_token='ghi', - ), - conversionsources.ListConversionSourcesResponse( - conversion_sources=[ - conversionsources.ConversionSource(), - conversionsources.ConversionSource(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(conversionsources.ListConversionSourcesResponse.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_conversion_sources(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, conversionsources.ConversionSource) - for i in results) - - pages = list(client.list_conversion_sources(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.ConversionSourcesServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ConversionSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ConversionSourcesServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ConversionSourcesServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ConversionSourcesServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ConversionSourcesServiceClient( - 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 = ConversionSourcesServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ConversionSourcesServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ConversionSourcesServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ConversionSourcesServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ConversionSourcesServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ConversionSourcesServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ConversionSourcesServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ConversionSourcesServiceGrpcTransport, - transports.ConversionSourcesServiceGrpcAsyncIOTransport, - transports.ConversionSourcesServiceRestTransport, -]) -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 = ConversionSourcesServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = ConversionSourcesServiceClient( - 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_create_conversion_source_empty_call_grpc(): - client = ConversionSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_conversion_source), - '__call__') as call: - call.return_value = conversionsources.ConversionSource() - client.create_conversion_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = conversionsources.CreateConversionSourceRequest() - - assert args[0] == request_msg - - -# This 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_conversion_source_empty_call_grpc(): - client = ConversionSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_conversion_source), - '__call__') as call: - call.return_value = conversionsources.ConversionSource() - client.update_conversion_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = conversionsources.UpdateConversionSourceRequest() - - assert args[0] == request_msg - - -# This 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_conversion_source_empty_call_grpc(): - client = ConversionSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_conversion_source), - '__call__') as call: - call.return_value = None - client.delete_conversion_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = conversionsources.DeleteConversionSourceRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_undelete_conversion_source_empty_call_grpc(): - client = ConversionSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.undelete_conversion_source), - '__call__') as call: - call.return_value = conversionsources.ConversionSource() - client.undelete_conversion_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = conversionsources.UndeleteConversionSourceRequest() - - assert args[0] == request_msg - - -# This 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_conversion_source_empty_call_grpc(): - client = ConversionSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_conversion_source), - '__call__') as call: - call.return_value = conversionsources.ConversionSource() - client.get_conversion_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = conversionsources.GetConversionSourceRequest() - - assert args[0] == request_msg - - -# This 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_conversion_sources_empty_call_grpc(): - client = ConversionSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_conversion_sources), - '__call__') as call: - call.return_value = conversionsources.ListConversionSourcesResponse() - client.list_conversion_sources(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = conversionsources.ListConversionSourcesRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = ConversionSourcesServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = ConversionSourcesServiceAsyncClient( - 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_create_conversion_source_empty_call_grpc_asyncio(): - client = ConversionSourcesServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_conversion_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversionsources.ConversionSource( - name='name_value', - state=conversionsources.ConversionSource.State.ACTIVE, - controller=conversionsources.ConversionSource.Controller.MERCHANT, - )) - await client.create_conversion_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = conversionsources.CreateConversionSourceRequest() - - assert args[0] == request_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_conversion_source_empty_call_grpc_asyncio(): - client = ConversionSourcesServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_conversion_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversionsources.ConversionSource( - name='name_value', - state=conversionsources.ConversionSource.State.ACTIVE, - controller=conversionsources.ConversionSource.Controller.MERCHANT, - )) - await client.update_conversion_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = conversionsources.UpdateConversionSourceRequest() - - assert args[0] == request_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_conversion_source_empty_call_grpc_asyncio(): - client = ConversionSourcesServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_conversion_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_conversion_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = conversionsources.DeleteConversionSourceRequest() - - assert args[0] == request_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_undelete_conversion_source_empty_call_grpc_asyncio(): - client = ConversionSourcesServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.undelete_conversion_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversionsources.ConversionSource( - name='name_value', - state=conversionsources.ConversionSource.State.ACTIVE, - controller=conversionsources.ConversionSource.Controller.MERCHANT, - )) - await client.undelete_conversion_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = conversionsources.UndeleteConversionSourceRequest() - - assert args[0] == request_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_conversion_source_empty_call_grpc_asyncio(): - client = ConversionSourcesServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_conversion_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversionsources.ConversionSource( - name='name_value', - state=conversionsources.ConversionSource.State.ACTIVE, - controller=conversionsources.ConversionSource.Controller.MERCHANT, - )) - await client.get_conversion_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = conversionsources.GetConversionSourceRequest() - - assert args[0] == request_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_conversion_sources_empty_call_grpc_asyncio(): - client = ConversionSourcesServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_conversion_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversionsources.ListConversionSourcesResponse( - next_page_token='next_page_token_value', - )) - await client.list_conversion_sources(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = conversionsources.ListConversionSourcesRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = ConversionSourcesServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_create_conversion_source_rest_bad_request(request_type=conversionsources.CreateConversionSourceRequest): - client = ConversionSourcesServiceClient( - 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_conversion_source(request) - - -@pytest.mark.parametrize("request_type", [ - conversionsources.CreateConversionSourceRequest, - dict, -]) -def test_create_conversion_source_rest_call_success(request_type): - client = ConversionSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} - request_init["conversion_source"] = {'google_analytics_link': {'property_id': 1201, 'attribution_settings': {'attribution_lookback_window_days': 3425, 'attribution_model': 1, 'conversion_type': [{'name': 'name_value', 'report': True}]}, 'property': 'property_value'}, 'merchant_center_destination': {'destination': 'destination_value', 'attribution_settings': {}, 'display_name': 'display_name_value', 'currency_code': 'currency_code_value'}, 'name': 'name_value', 'state': 1, 'expire_time': {'seconds': 751, 'nanos': 543}, 'controller': 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 = conversionsources.CreateConversionSourceRequest.meta.fields["conversion_source"] - - 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["conversion_source"].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["conversion_source"][field])): - del request_init["conversion_source"][field][i][subfield] - else: - del request_init["conversion_source"][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 = conversionsources.ConversionSource( - name='name_value', - state=conversionsources.ConversionSource.State.ACTIVE, - controller=conversionsources.ConversionSource.Controller.MERCHANT, - ) - - # 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 = conversionsources.ConversionSource.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_conversion_source(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, conversionsources.ConversionSource) - assert response.name == 'name_value' - assert response.state == conversionsources.ConversionSource.State.ACTIVE - assert response.controller == conversionsources.ConversionSource.Controller.MERCHANT - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_conversion_source_rest_interceptors(null_interceptor): - transport = transports.ConversionSourcesServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversionSourcesServiceRestInterceptor(), - ) - client = ConversionSourcesServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversionSourcesServiceRestInterceptor, "post_create_conversion_source") as post, \ - mock.patch.object(transports.ConversionSourcesServiceRestInterceptor, "pre_create_conversion_source") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = conversionsources.CreateConversionSourceRequest.pb(conversionsources.CreateConversionSourceRequest()) - 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 = conversionsources.ConversionSource.to_json(conversionsources.ConversionSource()) - req.return_value.content = return_value - - request = conversionsources.CreateConversionSourceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = conversionsources.ConversionSource() - - client.create_conversion_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_conversion_source_rest_bad_request(request_type=conversionsources.UpdateConversionSourceRequest): - client = ConversionSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'conversion_source': {'name': 'accounts/sample1/conversionSources/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_conversion_source(request) - - -@pytest.mark.parametrize("request_type", [ - conversionsources.UpdateConversionSourceRequest, - dict, -]) -def test_update_conversion_source_rest_call_success(request_type): - client = ConversionSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'conversion_source': {'name': 'accounts/sample1/conversionSources/sample2'}} - request_init["conversion_source"] = {'google_analytics_link': {'property_id': 1201, 'attribution_settings': {'attribution_lookback_window_days': 3425, 'attribution_model': 1, 'conversion_type': [{'name': 'name_value', 'report': True}]}, 'property': 'property_value'}, 'merchant_center_destination': {'destination': 'destination_value', 'attribution_settings': {}, 'display_name': 'display_name_value', 'currency_code': 'currency_code_value'}, 'name': 'accounts/sample1/conversionSources/sample2', 'state': 1, 'expire_time': {'seconds': 751, 'nanos': 543}, 'controller': 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 = conversionsources.UpdateConversionSourceRequest.meta.fields["conversion_source"] - - 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["conversion_source"].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["conversion_source"][field])): - del request_init["conversion_source"][field][i][subfield] - else: - del request_init["conversion_source"][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 = conversionsources.ConversionSource( - name='name_value', - state=conversionsources.ConversionSource.State.ACTIVE, - controller=conversionsources.ConversionSource.Controller.MERCHANT, - ) - - # 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 = conversionsources.ConversionSource.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_conversion_source(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, conversionsources.ConversionSource) - assert response.name == 'name_value' - assert response.state == conversionsources.ConversionSource.State.ACTIVE - assert response.controller == conversionsources.ConversionSource.Controller.MERCHANT - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_conversion_source_rest_interceptors(null_interceptor): - transport = transports.ConversionSourcesServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversionSourcesServiceRestInterceptor(), - ) - client = ConversionSourcesServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversionSourcesServiceRestInterceptor, "post_update_conversion_source") as post, \ - mock.patch.object(transports.ConversionSourcesServiceRestInterceptor, "pre_update_conversion_source") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = conversionsources.UpdateConversionSourceRequest.pb(conversionsources.UpdateConversionSourceRequest()) - 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 = conversionsources.ConversionSource.to_json(conversionsources.ConversionSource()) - req.return_value.content = return_value - - request = conversionsources.UpdateConversionSourceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = conversionsources.ConversionSource() - - client.update_conversion_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_conversion_source_rest_bad_request(request_type=conversionsources.DeleteConversionSourceRequest): - client = ConversionSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/conversionSources/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_conversion_source(request) - - -@pytest.mark.parametrize("request_type", [ - conversionsources.DeleteConversionSourceRequest, - dict, -]) -def test_delete_conversion_source_rest_call_success(request_type): - client = ConversionSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/conversionSources/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_conversion_source(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_conversion_source_rest_interceptors(null_interceptor): - transport = transports.ConversionSourcesServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversionSourcesServiceRestInterceptor(), - ) - client = ConversionSourcesServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversionSourcesServiceRestInterceptor, "pre_delete_conversion_source") as pre: - pre.assert_not_called() - pb_message = conversionsources.DeleteConversionSourceRequest.pb(conversionsources.DeleteConversionSourceRequest()) - 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 = conversionsources.DeleteConversionSourceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_conversion_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_undelete_conversion_source_rest_bad_request(request_type=conversionsources.UndeleteConversionSourceRequest): - client = ConversionSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/conversionSources/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.undelete_conversion_source(request) - - -@pytest.mark.parametrize("request_type", [ - conversionsources.UndeleteConversionSourceRequest, - dict, -]) -def test_undelete_conversion_source_rest_call_success(request_type): - client = ConversionSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/conversionSources/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 = conversionsources.ConversionSource( - name='name_value', - state=conversionsources.ConversionSource.State.ACTIVE, - controller=conversionsources.ConversionSource.Controller.MERCHANT, - ) - - # 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 = conversionsources.ConversionSource.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.undelete_conversion_source(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, conversionsources.ConversionSource) - assert response.name == 'name_value' - assert response.state == conversionsources.ConversionSource.State.ACTIVE - assert response.controller == conversionsources.ConversionSource.Controller.MERCHANT - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_undelete_conversion_source_rest_interceptors(null_interceptor): - transport = transports.ConversionSourcesServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversionSourcesServiceRestInterceptor(), - ) - client = ConversionSourcesServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversionSourcesServiceRestInterceptor, "post_undelete_conversion_source") as post, \ - mock.patch.object(transports.ConversionSourcesServiceRestInterceptor, "pre_undelete_conversion_source") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = conversionsources.UndeleteConversionSourceRequest.pb(conversionsources.UndeleteConversionSourceRequest()) - 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 = conversionsources.ConversionSource.to_json(conversionsources.ConversionSource()) - req.return_value.content = return_value - - request = conversionsources.UndeleteConversionSourceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = conversionsources.ConversionSource() - - client.undelete_conversion_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_conversion_source_rest_bad_request(request_type=conversionsources.GetConversionSourceRequest): - client = ConversionSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/conversionSources/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_conversion_source(request) - - -@pytest.mark.parametrize("request_type", [ - conversionsources.GetConversionSourceRequest, - dict, -]) -def test_get_conversion_source_rest_call_success(request_type): - client = ConversionSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/conversionSources/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 = conversionsources.ConversionSource( - name='name_value', - state=conversionsources.ConversionSource.State.ACTIVE, - controller=conversionsources.ConversionSource.Controller.MERCHANT, - ) - - # 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 = conversionsources.ConversionSource.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_conversion_source(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, conversionsources.ConversionSource) - assert response.name == 'name_value' - assert response.state == conversionsources.ConversionSource.State.ACTIVE - assert response.controller == conversionsources.ConversionSource.Controller.MERCHANT - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_conversion_source_rest_interceptors(null_interceptor): - transport = transports.ConversionSourcesServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversionSourcesServiceRestInterceptor(), - ) - client = ConversionSourcesServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversionSourcesServiceRestInterceptor, "post_get_conversion_source") as post, \ - mock.patch.object(transports.ConversionSourcesServiceRestInterceptor, "pre_get_conversion_source") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = conversionsources.GetConversionSourceRequest.pb(conversionsources.GetConversionSourceRequest()) - 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 = conversionsources.ConversionSource.to_json(conversionsources.ConversionSource()) - req.return_value.content = return_value - - request = conversionsources.GetConversionSourceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = conversionsources.ConversionSource() - - client.get_conversion_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_conversion_sources_rest_bad_request(request_type=conversionsources.ListConversionSourcesRequest): - client = ConversionSourcesServiceClient( - 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_conversion_sources(request) - - -@pytest.mark.parametrize("request_type", [ - conversionsources.ListConversionSourcesRequest, - dict, -]) -def test_list_conversion_sources_rest_call_success(request_type): - client = ConversionSourcesServiceClient( - 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 = conversionsources.ListConversionSourcesResponse( - 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 = conversionsources.ListConversionSourcesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_conversion_sources(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListConversionSourcesPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_conversion_sources_rest_interceptors(null_interceptor): - transport = transports.ConversionSourcesServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversionSourcesServiceRestInterceptor(), - ) - client = ConversionSourcesServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversionSourcesServiceRestInterceptor, "post_list_conversion_sources") as post, \ - mock.patch.object(transports.ConversionSourcesServiceRestInterceptor, "pre_list_conversion_sources") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = conversionsources.ListConversionSourcesRequest.pb(conversionsources.ListConversionSourcesRequest()) - 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 = conversionsources.ListConversionSourcesResponse.to_json(conversionsources.ListConversionSourcesResponse()) - req.return_value.content = return_value - - request = conversionsources.ListConversionSourcesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = conversionsources.ListConversionSourcesResponse() - - client.list_conversion_sources(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - -def test_initialize_client_w_rest(): - client = ConversionSourcesServiceClient( - 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_create_conversion_source_empty_call_rest(): - client = ConversionSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_conversion_source), - '__call__') as call: - client.create_conversion_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = conversionsources.CreateConversionSourceRequest() - - assert args[0] == request_msg - - -# This 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_conversion_source_empty_call_rest(): - client = ConversionSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_conversion_source), - '__call__') as call: - client.update_conversion_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = conversionsources.UpdateConversionSourceRequest() - - assert args[0] == request_msg - - -# This 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_conversion_source_empty_call_rest(): - client = ConversionSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_conversion_source), - '__call__') as call: - client.delete_conversion_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = conversionsources.DeleteConversionSourceRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_undelete_conversion_source_empty_call_rest(): - client = ConversionSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.undelete_conversion_source), - '__call__') as call: - client.undelete_conversion_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = conversionsources.UndeleteConversionSourceRequest() - - assert args[0] == request_msg - - -# This 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_conversion_source_empty_call_rest(): - client = ConversionSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_conversion_source), - '__call__') as call: - client.get_conversion_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = conversionsources.GetConversionSourceRequest() - - assert args[0] == request_msg - - -# This 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_conversion_sources_empty_call_rest(): - client = ConversionSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_conversion_sources), - '__call__') as call: - client.list_conversion_sources(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = conversionsources.ListConversionSourcesRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = ConversionSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ConversionSourcesServiceGrpcTransport, - ) - -def test_conversion_sources_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ConversionSourcesServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_conversion_sources_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.shopping.merchant_conversions_v1beta.services.conversion_sources_service.transports.ConversionSourcesServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ConversionSourcesServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_conversion_source', - 'update_conversion_source', - 'delete_conversion_source', - 'undelete_conversion_source', - 'get_conversion_source', - 'list_conversion_sources', - ) - 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_conversion_sources_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_conversions_v1beta.services.conversion_sources_service.transports.ConversionSourcesServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ConversionSourcesServiceTransport( - 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_conversion_sources_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_conversions_v1beta.services.conversion_sources_service.transports.ConversionSourcesServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ConversionSourcesServiceTransport() - adc.assert_called_once() - - -def test_conversion_sources_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) - ConversionSourcesServiceClient() - 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.ConversionSourcesServiceGrpcTransport, - transports.ConversionSourcesServiceGrpcAsyncIOTransport, - ], -) -def test_conversion_sources_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.ConversionSourcesServiceGrpcTransport, - transports.ConversionSourcesServiceGrpcAsyncIOTransport, - transports.ConversionSourcesServiceRestTransport, - ], -) -def test_conversion_sources_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.ConversionSourcesServiceGrpcTransport, grpc_helpers), - (transports.ConversionSourcesServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_conversion_sources_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.ConversionSourcesServiceGrpcTransport, transports.ConversionSourcesServiceGrpcAsyncIOTransport]) -def test_conversion_sources_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_conversion_sources_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.ConversionSourcesServiceRestTransport ( - 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_conversion_sources_service_host_no_port(transport_name): - client = ConversionSourcesServiceClient( - 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_conversion_sources_service_host_with_port(transport_name): - client = ConversionSourcesServiceClient( - 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_conversion_sources_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = ConversionSourcesServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = ConversionSourcesServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.create_conversion_source._session - session2 = client2.transport.create_conversion_source._session - assert session1 != session2 - session1 = client1.transport.update_conversion_source._session - session2 = client2.transport.update_conversion_source._session - assert session1 != session2 - session1 = client1.transport.delete_conversion_source._session - session2 = client2.transport.delete_conversion_source._session - assert session1 != session2 - session1 = client1.transport.undelete_conversion_source._session - session2 = client2.transport.undelete_conversion_source._session - assert session1 != session2 - session1 = client1.transport.get_conversion_source._session - session2 = client2.transport.get_conversion_source._session - assert session1 != session2 - session1 = client1.transport.list_conversion_sources._session - session2 = client2.transport.list_conversion_sources._session - assert session1 != session2 -def test_conversion_sources_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ConversionSourcesServiceGrpcTransport( - 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_conversion_sources_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ConversionSourcesServiceGrpcAsyncIOTransport( - 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.ConversionSourcesServiceGrpcTransport, transports.ConversionSourcesServiceGrpcAsyncIOTransport]) -def test_conversion_sources_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.ConversionSourcesServiceGrpcTransport, transports.ConversionSourcesServiceGrpcAsyncIOTransport]) -def test_conversion_sources_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_conversion_source_path(): - account = "squid" - conversion_source = "clam" - expected = "accounts/{account}/conversionSources/{conversion_source}".format(account=account, conversion_source=conversion_source, ) - actual = ConversionSourcesServiceClient.conversion_source_path(account, conversion_source) - assert expected == actual - - -def test_parse_conversion_source_path(): - expected = { - "account": "whelk", - "conversion_source": "octopus", - } - path = ConversionSourcesServiceClient.conversion_source_path(**expected) - - # Check that the path construction is reversible. - actual = ConversionSourcesServiceClient.parse_conversion_source_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ConversionSourcesServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = ConversionSourcesServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ConversionSourcesServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = ConversionSourcesServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = ConversionSourcesServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ConversionSourcesServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ConversionSourcesServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = ConversionSourcesServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ConversionSourcesServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = ConversionSourcesServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = ConversionSourcesServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ConversionSourcesServiceClient.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 = ConversionSourcesServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = ConversionSourcesServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ConversionSourcesServiceClient.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.ConversionSourcesServiceTransport, '_prep_wrapped_messages') as prep: - client = ConversionSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ConversionSourcesServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = ConversionSourcesServiceClient.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 = ConversionSourcesServiceClient( - 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 = ConversionSourcesServiceAsyncClient( - 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 = ConversionSourcesServiceClient( - 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 = ConversionSourcesServiceClient( - 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", [ - (ConversionSourcesServiceClient, transports.ConversionSourcesServiceGrpcTransport), - (ConversionSourcesServiceAsyncClient, transports.ConversionSourcesServiceGrpcAsyncIOTransport), -]) -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-datasources/v1beta/.coveragerc b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/.coveragerc deleted file mode 100644 index 67aeac1093c8..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/shopping/merchant_datasources/__init__.py - google/shopping/merchant_datasources/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-datasources/v1beta/.flake8 b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/MANIFEST.in b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/MANIFEST.in deleted file mode 100644 index ab3bc5b3d4df..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/shopping/merchant_datasources *.py -recursive-include google/shopping/merchant_datasources_v1beta *.py diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/README.rst b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/README.rst deleted file mode 100644 index 8a0e5d463dd0..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Shopping Merchant Datasources 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 Datasources 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 diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/_static/custom.css b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/_static/custom.css +++ /dev/null @@ -1,3 +0,0 @@ -dl.field-list > dt { - min-width: 100px -} diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/conf.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/conf.py deleted file mode 100644 index 52640877d629..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-datasources 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("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# 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.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -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-datasources" -copyright = u"2023, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# 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 = 'en' - -# 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"] - -# 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 Python", - "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-datasources-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-datasources.tex", - u"google-shopping-merchant-datasources 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-datasources", - u"Google Shopping Merchant Datasources 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-datasources", - u"google-shopping-merchant-datasources Documentation", - author, - "google-shopping-merchant-datasources", - "GAPIC library for Google Shopping Merchant Datasources API", - "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": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", 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-datasources/v1beta/docs/index.rst b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/index.rst deleted file mode 100644 index dd26af210690..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - merchant_datasources_v1beta/services_ - merchant_datasources_v1beta/types_ diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/merchant_datasources_v1beta/data_sources_service.rst b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/merchant_datasources_v1beta/data_sources_service.rst deleted file mode 100644 index 0adda9607d6f..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/merchant_datasources_v1beta/data_sources_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -DataSourcesService ------------------------------------- - -.. automodule:: google.shopping.merchant_datasources_v1beta.services.data_sources_service - :members: - :inherited-members: - -.. automodule:: google.shopping.merchant_datasources_v1beta.services.data_sources_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/merchant_datasources_v1beta/file_uploads_service.rst b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/merchant_datasources_v1beta/file_uploads_service.rst deleted file mode 100644 index 2cb7cfc2bd21..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/merchant_datasources_v1beta/file_uploads_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -FileUploadsService ------------------------------------- - -.. automodule:: google.shopping.merchant_datasources_v1beta.services.file_uploads_service - :members: - :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/merchant_datasources_v1beta/services_.rst b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/merchant_datasources_v1beta/services_.rst deleted file mode 100644 index c306312a77f1..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/merchant_datasources_v1beta/services_.rst +++ /dev/null @@ -1,7 +0,0 @@ -Services for Google Shopping Merchant Datasources v1beta API -============================================================ -.. toctree:: - :maxdepth: 2 - - data_sources_service - file_uploads_service diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/merchant_datasources_v1beta/types_.rst b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/merchant_datasources_v1beta/types_.rst deleted file mode 100644 index 567ff11ee41e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/docs/merchant_datasources_v1beta/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Shopping Merchant Datasources v1beta API -========================================================= - -.. automodule:: google.shopping.merchant_datasources_v1beta.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources/__init__.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources/__init__.py deleted file mode 100644 index 9ce584515e52..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources/__init__.py +++ /dev/null @@ -1,65 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_datasources import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.shopping.merchant_datasources_v1beta.services.data_sources_service.client import DataSourcesServiceClient -from google.shopping.merchant_datasources_v1beta.services.data_sources_service.async_client import DataSourcesServiceAsyncClient -from google.shopping.merchant_datasources_v1beta.services.file_uploads_service.client import FileUploadsServiceClient -from google.shopping.merchant_datasources_v1beta.services.file_uploads_service.async_client import FileUploadsServiceAsyncClient - -from google.shopping.merchant_datasources_v1beta.types.datasources import CreateDataSourceRequest -from google.shopping.merchant_datasources_v1beta.types.datasources import DataSource -from google.shopping.merchant_datasources_v1beta.types.datasources import DeleteDataSourceRequest -from google.shopping.merchant_datasources_v1beta.types.datasources import FetchDataSourceRequest -from google.shopping.merchant_datasources_v1beta.types.datasources import GetDataSourceRequest -from google.shopping.merchant_datasources_v1beta.types.datasources import ListDataSourcesRequest -from google.shopping.merchant_datasources_v1beta.types.datasources import ListDataSourcesResponse -from google.shopping.merchant_datasources_v1beta.types.datasources import UpdateDataSourceRequest -from google.shopping.merchant_datasources_v1beta.types.datasourcetypes import DataSourceReference -from google.shopping.merchant_datasources_v1beta.types.datasourcetypes import LocalInventoryDataSource -from google.shopping.merchant_datasources_v1beta.types.datasourcetypes import PrimaryProductDataSource -from google.shopping.merchant_datasources_v1beta.types.datasourcetypes import PromotionDataSource -from google.shopping.merchant_datasources_v1beta.types.datasourcetypes import RegionalInventoryDataSource -from google.shopping.merchant_datasources_v1beta.types.datasourcetypes import SupplementalProductDataSource -from google.shopping.merchant_datasources_v1beta.types.fileinputs import FileInput -from google.shopping.merchant_datasources_v1beta.types.fileuploads import FileUpload -from google.shopping.merchant_datasources_v1beta.types.fileuploads import GetFileUploadRequest - -__all__ = ('DataSourcesServiceClient', - 'DataSourcesServiceAsyncClient', - 'FileUploadsServiceClient', - 'FileUploadsServiceAsyncClient', - 'CreateDataSourceRequest', - 'DataSource', - 'DeleteDataSourceRequest', - 'FetchDataSourceRequest', - 'GetDataSourceRequest', - 'ListDataSourcesRequest', - 'ListDataSourcesResponse', - 'UpdateDataSourceRequest', - 'DataSourceReference', - 'LocalInventoryDataSource', - 'PrimaryProductDataSource', - 'PromotionDataSource', - 'RegionalInventoryDataSource', - 'SupplementalProductDataSource', - 'FileInput', - 'FileUpload', - 'GetFileUploadRequest', -) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources/gapic_version.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-datasources/v1beta/google/shopping/merchant_datasources/py.typed b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources/py.typed deleted file mode 100644 index 035cdd22912c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-shopping-merchant-datasources package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/__init__.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/__init__.py deleted file mode 100644 index a4cce51e3871..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/__init__.py +++ /dev/null @@ -1,66 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_datasources_v1beta import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.data_sources_service import DataSourcesServiceClient -from .services.data_sources_service import DataSourcesServiceAsyncClient -from .services.file_uploads_service import FileUploadsServiceClient -from .services.file_uploads_service import FileUploadsServiceAsyncClient - -from .types.datasources import CreateDataSourceRequest -from .types.datasources import DataSource -from .types.datasources import DeleteDataSourceRequest -from .types.datasources import FetchDataSourceRequest -from .types.datasources import GetDataSourceRequest -from .types.datasources import ListDataSourcesRequest -from .types.datasources import ListDataSourcesResponse -from .types.datasources import UpdateDataSourceRequest -from .types.datasourcetypes import DataSourceReference -from .types.datasourcetypes import LocalInventoryDataSource -from .types.datasourcetypes import PrimaryProductDataSource -from .types.datasourcetypes import PromotionDataSource -from .types.datasourcetypes import RegionalInventoryDataSource -from .types.datasourcetypes import SupplementalProductDataSource -from .types.fileinputs import FileInput -from .types.fileuploads import FileUpload -from .types.fileuploads import GetFileUploadRequest - -__all__ = ( - 'DataSourcesServiceAsyncClient', - 'FileUploadsServiceAsyncClient', -'CreateDataSourceRequest', -'DataSource', -'DataSourceReference', -'DataSourcesServiceClient', -'DeleteDataSourceRequest', -'FetchDataSourceRequest', -'FileInput', -'FileUpload', -'FileUploadsServiceClient', -'GetDataSourceRequest', -'GetFileUploadRequest', -'ListDataSourcesRequest', -'ListDataSourcesResponse', -'LocalInventoryDataSource', -'PrimaryProductDataSource', -'PromotionDataSource', -'RegionalInventoryDataSource', -'SupplementalProductDataSource', -'UpdateDataSourceRequest', -) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/gapic_metadata.json b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/gapic_metadata.json deleted file mode 100644 index ec4728128d9c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/gapic_metadata.json +++ /dev/null @@ -1,152 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.shopping.merchant_datasources_v1beta", - "protoPackage": "google.shopping.merchant.datasources.v1beta", - "schema": "1.0", - "services": { - "DataSourcesService": { - "clients": { - "grpc": { - "libraryClient": "DataSourcesServiceClient", - "rpcs": { - "CreateDataSource": { - "methods": [ - "create_data_source" - ] - }, - "DeleteDataSource": { - "methods": [ - "delete_data_source" - ] - }, - "FetchDataSource": { - "methods": [ - "fetch_data_source" - ] - }, - "GetDataSource": { - "methods": [ - "get_data_source" - ] - }, - "ListDataSources": { - "methods": [ - "list_data_sources" - ] - }, - "UpdateDataSource": { - "methods": [ - "update_data_source" - ] - } - } - }, - "grpc-async": { - "libraryClient": "DataSourcesServiceAsyncClient", - "rpcs": { - "CreateDataSource": { - "methods": [ - "create_data_source" - ] - }, - "DeleteDataSource": { - "methods": [ - "delete_data_source" - ] - }, - "FetchDataSource": { - "methods": [ - "fetch_data_source" - ] - }, - "GetDataSource": { - "methods": [ - "get_data_source" - ] - }, - "ListDataSources": { - "methods": [ - "list_data_sources" - ] - }, - "UpdateDataSource": { - "methods": [ - "update_data_source" - ] - } - } - }, - "rest": { - "libraryClient": "DataSourcesServiceClient", - "rpcs": { - "CreateDataSource": { - "methods": [ - "create_data_source" - ] - }, - "DeleteDataSource": { - "methods": [ - "delete_data_source" - ] - }, - "FetchDataSource": { - "methods": [ - "fetch_data_source" - ] - }, - "GetDataSource": { - "methods": [ - "get_data_source" - ] - }, - "ListDataSources": { - "methods": [ - "list_data_sources" - ] - }, - "UpdateDataSource": { - "methods": [ - "update_data_source" - ] - } - } - } - } - }, - "FileUploadsService": { - "clients": { - "grpc": { - "libraryClient": "FileUploadsServiceClient", - "rpcs": { - "GetFileUpload": { - "methods": [ - "get_file_upload" - ] - } - } - }, - "grpc-async": { - "libraryClient": "FileUploadsServiceAsyncClient", - "rpcs": { - "GetFileUpload": { - "methods": [ - "get_file_upload" - ] - } - } - }, - "rest": { - "libraryClient": "FileUploadsServiceClient", - "rpcs": { - "GetFileUpload": { - "methods": [ - "get_file_upload" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/gapic_version.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-datasources/v1beta/google/shopping/merchant_datasources_v1beta/py.typed b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/py.typed deleted file mode 100644 index 035cdd22912c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-shopping-merchant-datasources package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/__init__.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/__init__.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/__init__.py deleted file mode 100644 index 359f46aef4ed..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 DataSourcesServiceClient -from .async_client import DataSourcesServiceAsyncClient - -__all__ = ( - 'DataSourcesServiceClient', - 'DataSourcesServiceAsyncClient', -) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/async_client.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/async_client.py deleted file mode 100644 index 9b8069d307d4..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/async_client.py +++ /dev/null @@ -1,913 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_datasources_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 - - -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_datasources_v1beta.services.data_sources_service import pagers -from google.shopping.merchant_datasources_v1beta.types import datasources -from google.shopping.merchant_datasources_v1beta.types import datasourcetypes -from google.shopping.merchant_datasources_v1beta.types import fileinputs -from .transports.base import DataSourcesServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import DataSourcesServiceGrpcAsyncIOTransport -from .client import DataSourcesServiceClient - -try: - from google.api_core import client_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 DataSourcesServiceAsyncClient: - """Service to manage primary, supplemental, inventory and other data - sources. See more in the `Merchant - Center `__ help - article. - """ - - _client: DataSourcesServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = DataSourcesServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = DataSourcesServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = DataSourcesServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = DataSourcesServiceClient._DEFAULT_UNIVERSE - - data_source_path = staticmethod(DataSourcesServiceClient.data_source_path) - parse_data_source_path = staticmethod(DataSourcesServiceClient.parse_data_source_path) - common_billing_account_path = staticmethod(DataSourcesServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(DataSourcesServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(DataSourcesServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(DataSourcesServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(DataSourcesServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(DataSourcesServiceClient.parse_common_organization_path) - common_project_path = staticmethod(DataSourcesServiceClient.common_project_path) - parse_common_project_path = staticmethod(DataSourcesServiceClient.parse_common_project_path) - common_location_path = staticmethod(DataSourcesServiceClient.common_location_path) - parse_common_location_path = staticmethod(DataSourcesServiceClient.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: - DataSourcesServiceAsyncClient: The constructed client. - """ - return DataSourcesServiceClient.from_service_account_info.__func__(DataSourcesServiceAsyncClient, 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: - DataSourcesServiceAsyncClient: The constructed client. - """ - return DataSourcesServiceClient.from_service_account_file.__func__(DataSourcesServiceAsyncClient, 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 DataSourcesServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> DataSourcesServiceTransport: - """Returns the transport used by the client instance. - - Returns: - DataSourcesServiceTransport: 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 = DataSourcesServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, DataSourcesServiceTransport, Callable[..., DataSourcesServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the data sources 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,DataSourcesServiceTransport,Callable[..., DataSourcesServiceTransport]]]): - 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 DataSourcesServiceTransport 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 = DataSourcesServiceClient( - 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.datasources_v1beta.DataSourcesServiceAsyncClient`.", - extra = { - "serviceName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", - "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.datasources.v1beta.DataSourcesService", - "credentialsType": None, - } - ) - - async def get_data_source(self, - request: Optional[Union[datasources.GetDataSourceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> datasources.DataSource: - r"""Retrieves the data source configuration for the given - account. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_datasources_v1beta - - async def sample_get_data_source(): - # Create a client - client = merchant_datasources_v1beta.DataSourcesServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_datasources_v1beta.GetDataSourceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_data_source(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_datasources_v1beta.types.GetDataSourceRequest, dict]]): - The request object. Request message for the GetDataSource - method. - name (:class:`str`): - Required. The name of the data source to retrieve. - Format: ``accounts/{account}/dataSources/{datasource}`` - - 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_datasources_v1beta.types.DataSource: - The [data source](\ https://support.google.com/merchants/answer/7439058) for - the Merchant Center 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, datasources.GetDataSourceRequest): - request = datasources.GetDataSourceRequest(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_data_source] - - # Certain 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_data_sources(self, - request: Optional[Union[datasources.ListDataSourcesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListDataSourcesAsyncPager: - r"""Lists the configurations for data sources for the - given account. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_datasources_v1beta - - async def sample_list_data_sources(): - # Create a client - client = merchant_datasources_v1beta.DataSourcesServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_datasources_v1beta.ListDataSourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_data_sources(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_datasources_v1beta.types.ListDataSourcesRequest, dict]]): - The request object. Request message for the - ListDataSources method. - parent (:class:`str`): - Required. The account to list data sources 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_datasources_v1beta.services.data_sources_service.pagers.ListDataSourcesAsyncPager: - Response message for the - ListDataSources 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, datasources.ListDataSourcesRequest): - request = datasources.ListDataSourcesRequest(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_data_sources] - - # Certain 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.ListDataSourcesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_data_source(self, - request: Optional[Union[datasources.CreateDataSourceRequest, dict]] = None, - *, - parent: Optional[str] = None, - data_source: Optional[datasources.DataSource] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> datasources.DataSource: - r"""Creates the new data source configuration for the - given account. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_datasources_v1beta - - async def sample_create_data_source(): - # Create a client - client = merchant_datasources_v1beta.DataSourcesServiceAsyncClient() - - # Initialize request argument(s) - data_source = merchant_datasources_v1beta.DataSource() - data_source.primary_product_data_source.channel = "PRODUCTS" - data_source.display_name = "display_name_value" - - request = merchant_datasources_v1beta.CreateDataSourceRequest( - parent="parent_value", - data_source=data_source, - ) - - # Make the request - response = await client.create_data_source(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_datasources_v1beta.types.CreateDataSourceRequest, dict]]): - The request object. Request message for the - CreateDataSource method. - parent (:class:`str`): - Required. The account where this data source 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. - data_source (:class:`google.shopping.merchant_datasources_v1beta.types.DataSource`): - Required. The data source to create. - This corresponds to the ``data_source`` 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_datasources_v1beta.types.DataSource: - The [data source](\ https://support.google.com/merchants/answer/7439058) for - the Merchant Center 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. - has_flattened_params = any([parent, data_source]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, datasources.CreateDataSourceRequest): - request = datasources.CreateDataSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if data_source is not None: - request.data_source = data_source - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_data_source] - - # Certain 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_data_source(self, - request: Optional[Union[datasources.UpdateDataSourceRequest, dict]] = None, - *, - data_source: Optional[datasources.DataSource] = 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]]] = (), - ) -> datasources.DataSource: - r"""Updates the existing data source configuration. The - fields that are set in the update mask but not provided - in the resource will be deleted. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_datasources_v1beta - - async def sample_update_data_source(): - # Create a client - client = merchant_datasources_v1beta.DataSourcesServiceAsyncClient() - - # Initialize request argument(s) - data_source = merchant_datasources_v1beta.DataSource() - data_source.primary_product_data_source.channel = "PRODUCTS" - data_source.display_name = "display_name_value" - - request = merchant_datasources_v1beta.UpdateDataSourceRequest( - data_source=data_source, - ) - - # Make the request - response = await client.update_data_source(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_datasources_v1beta.types.UpdateDataSourceRequest, dict]]): - The request object. Request message for the - UpdateDataSource method. - data_source (:class:`google.shopping.merchant_datasources_v1beta.types.DataSource`): - Required. The data source resource to - update. - - This corresponds to the ``data_source`` 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 data source fields to be updated. - - Fields specified in the update mask without a value - specified in the body will be deleted from the data - source. - - Providing special "*" value for full data source - replacement is not supported. - - 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_datasources_v1beta.types.DataSource: - The [data source](\ https://support.google.com/merchants/answer/7439058) for - the Merchant Center 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. - has_flattened_params = any([data_source, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, datasources.UpdateDataSourceRequest): - request = datasources.UpdateDataSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if data_source is not None: - request.data_source = data_source - 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_data_source] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("data_source.name", request.data_source.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_data_source(self, - request: Optional[Union[datasources.DeleteDataSourceRequest, dict]] = None, - *, - name: Optional[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 data source from 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_datasources_v1beta - - async def sample_delete_data_source(): - # Create a client - client = merchant_datasources_v1beta.DataSourcesServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_datasources_v1beta.DeleteDataSourceRequest( - name="name_value", - ) - - # Make the request - await client.delete_data_source(request=request) - - Args: - request (Optional[Union[google.shopping.merchant_datasources_v1beta.types.DeleteDataSourceRequest, dict]]): - The request object. Request message for the - DeleteDataSource method. - name (:class:`str`): - Required. The name of the data source to delete. Format: - ``accounts/{account}/dataSources/{datasource}`` - - 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, datasources.DeleteDataSourceRequest): - request = datasources.DeleteDataSourceRequest(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_data_source] - - # Certain 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 fetch_data_source(self, - request: Optional[Union[datasources.FetchDataSourceRequest, 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"""Performs the data fetch immediately (even outside - fetch schedule) on a data source from your Merchant - Center Account. If you need to call this method more - than once per day, you should use the Products service - to update your product data instead. - This method only works on data sources with a file input - set. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_datasources_v1beta - - async def sample_fetch_data_source(): - # Create a client - client = merchant_datasources_v1beta.DataSourcesServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_datasources_v1beta.FetchDataSourceRequest( - name="name_value", - ) - - # Make the request - await client.fetch_data_source(request=request) - - Args: - request (Optional[Union[google.shopping.merchant_datasources_v1beta.types.FetchDataSourceRequest, dict]]): - The request object. Request message for the - FetchDataSource 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, datasources.FetchDataSourceRequest): - request = datasources.FetchDataSourceRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.fetch_data_source] - - # Certain 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) -> "DataSourcesServiceAsyncClient": - 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__) - - -__all__ = ( - "DataSourcesServiceAsyncClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/client.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/client.py deleted file mode 100644 index 0c4624333501..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/client.py +++ /dev/null @@ -1,1244 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -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_datasources_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 - -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_datasources_v1beta.services.data_sources_service import pagers -from google.shopping.merchant_datasources_v1beta.types import datasources -from google.shopping.merchant_datasources_v1beta.types import datasourcetypes -from google.shopping.merchant_datasources_v1beta.types import fileinputs -from .transports.base import DataSourcesServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import DataSourcesServiceGrpcTransport -from .transports.grpc_asyncio import DataSourcesServiceGrpcAsyncIOTransport -from .transports.rest import DataSourcesServiceRestTransport - - -class DataSourcesServiceClientMeta(type): - """Metaclass for the DataSourcesService 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[DataSourcesServiceTransport]] - _transport_registry["grpc"] = DataSourcesServiceGrpcTransport - _transport_registry["grpc_asyncio"] = DataSourcesServiceGrpcAsyncIOTransport - _transport_registry["rest"] = DataSourcesServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[DataSourcesServiceTransport]: - """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 DataSourcesServiceClient(metaclass=DataSourcesServiceClientMeta): - """Service to manage primary, supplemental, inventory and other data - sources. See more in the `Merchant - Center `__ help - article. - """ - - @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: - DataSourcesServiceClient: 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: - DataSourcesServiceClient: 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) -> DataSourcesServiceTransport: - """Returns the transport used by the client instance. - - Returns: - DataSourcesServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def data_source_path(account: str,datasource: str,) -> str: - """Returns a fully-qualified data_source string.""" - return "accounts/{account}/dataSources/{datasource}".format(account=account, datasource=datasource, ) - - @staticmethod - def parse_data_source_path(path: str) -> Dict[str,str]: - """Parses a data_source path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/dataSources/(?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 = DataSourcesServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = DataSourcesServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = DataSourcesServiceClient._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 = DataSourcesServiceClient._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 - - @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, DataSourcesServiceTransport, Callable[..., DataSourcesServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the data sources 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,DataSourcesServiceTransport,Callable[..., DataSourcesServiceTransport]]]): - 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 DataSourcesServiceTransport 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 = DataSourcesServiceClient._read_environment_variables() - self._client_cert_source = DataSourcesServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = DataSourcesServiceClient._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, DataSourcesServiceTransport) - if transport_provided: - # transport is a DataSourcesServiceTransport 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(DataSourcesServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - DataSourcesServiceClient._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[DataSourcesServiceTransport], Callable[..., DataSourcesServiceTransport]] = ( - DataSourcesServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., DataSourcesServiceTransport], 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.datasources_v1beta.DataSourcesServiceClient`.", - extra = { - "serviceName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", - "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.datasources.v1beta.DataSourcesService", - "credentialsType": None, - } - ) - - def get_data_source(self, - request: Optional[Union[datasources.GetDataSourceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> datasources.DataSource: - r"""Retrieves the data source configuration for the given - account. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_datasources_v1beta - - def sample_get_data_source(): - # Create a client - client = merchant_datasources_v1beta.DataSourcesServiceClient() - - # Initialize request argument(s) - request = merchant_datasources_v1beta.GetDataSourceRequest( - name="name_value", - ) - - # Make the request - response = client.get_data_source(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_datasources_v1beta.types.GetDataSourceRequest, dict]): - The request object. Request message for the GetDataSource - method. - name (str): - Required. The name of the data source to retrieve. - Format: ``accounts/{account}/dataSources/{datasource}`` - - 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_datasources_v1beta.types.DataSource: - The [data source](\ https://support.google.com/merchants/answer/7439058) for - the Merchant Center 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, datasources.GetDataSourceRequest): - request = datasources.GetDataSourceRequest(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_data_source] - - # Certain 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_data_sources(self, - request: Optional[Union[datasources.ListDataSourcesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListDataSourcesPager: - r"""Lists the configurations for data sources for the - given account. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_datasources_v1beta - - def sample_list_data_sources(): - # Create a client - client = merchant_datasources_v1beta.DataSourcesServiceClient() - - # Initialize request argument(s) - request = merchant_datasources_v1beta.ListDataSourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_data_sources(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.shopping.merchant_datasources_v1beta.types.ListDataSourcesRequest, dict]): - The request object. Request message for the - ListDataSources method. - parent (str): - Required. The account to list data sources 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_datasources_v1beta.services.data_sources_service.pagers.ListDataSourcesPager: - Response message for the - ListDataSources 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, datasources.ListDataSourcesRequest): - request = datasources.ListDataSourcesRequest(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_data_sources] - - # Certain 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.ListDataSourcesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_data_source(self, - request: Optional[Union[datasources.CreateDataSourceRequest, dict]] = None, - *, - parent: Optional[str] = None, - data_source: Optional[datasources.DataSource] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> datasources.DataSource: - r"""Creates the new data source configuration for the - given account. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_datasources_v1beta - - def sample_create_data_source(): - # Create a client - client = merchant_datasources_v1beta.DataSourcesServiceClient() - - # Initialize request argument(s) - data_source = merchant_datasources_v1beta.DataSource() - data_source.primary_product_data_source.channel = "PRODUCTS" - data_source.display_name = "display_name_value" - - request = merchant_datasources_v1beta.CreateDataSourceRequest( - parent="parent_value", - data_source=data_source, - ) - - # Make the request - response = client.create_data_source(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_datasources_v1beta.types.CreateDataSourceRequest, dict]): - The request object. Request message for the - CreateDataSource method. - parent (str): - Required. The account where this data source 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. - data_source (google.shopping.merchant_datasources_v1beta.types.DataSource): - Required. The data source to create. - This corresponds to the ``data_source`` 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_datasources_v1beta.types.DataSource: - The [data source](\ https://support.google.com/merchants/answer/7439058) for - the Merchant Center 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. - has_flattened_params = any([parent, data_source]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, datasources.CreateDataSourceRequest): - request = datasources.CreateDataSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if data_source is not None: - request.data_source = data_source - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_data_source] - - # Certain 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_data_source(self, - request: Optional[Union[datasources.UpdateDataSourceRequest, dict]] = None, - *, - data_source: Optional[datasources.DataSource] = 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]]] = (), - ) -> datasources.DataSource: - r"""Updates the existing data source configuration. The - fields that are set in the update mask but not provided - in the resource will be deleted. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_datasources_v1beta - - def sample_update_data_source(): - # Create a client - client = merchant_datasources_v1beta.DataSourcesServiceClient() - - # Initialize request argument(s) - data_source = merchant_datasources_v1beta.DataSource() - data_source.primary_product_data_source.channel = "PRODUCTS" - data_source.display_name = "display_name_value" - - request = merchant_datasources_v1beta.UpdateDataSourceRequest( - data_source=data_source, - ) - - # Make the request - response = client.update_data_source(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_datasources_v1beta.types.UpdateDataSourceRequest, dict]): - The request object. Request message for the - UpdateDataSource method. - data_source (google.shopping.merchant_datasources_v1beta.types.DataSource): - Required. The data source resource to - update. - - This corresponds to the ``data_source`` 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 data source fields to be updated. - - Fields specified in the update mask without a value - specified in the body will be deleted from the data - source. - - Providing special "*" value for full data source - replacement is not supported. - - 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_datasources_v1beta.types.DataSource: - The [data source](\ https://support.google.com/merchants/answer/7439058) for - the Merchant Center 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. - has_flattened_params = any([data_source, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, datasources.UpdateDataSourceRequest): - request = datasources.UpdateDataSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if data_source is not None: - request.data_source = data_source - 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_data_source] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("data_source.name", request.data_source.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_data_source(self, - request: Optional[Union[datasources.DeleteDataSourceRequest, dict]] = None, - *, - name: Optional[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 data source from 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_datasources_v1beta - - def sample_delete_data_source(): - # Create a client - client = merchant_datasources_v1beta.DataSourcesServiceClient() - - # Initialize request argument(s) - request = merchant_datasources_v1beta.DeleteDataSourceRequest( - name="name_value", - ) - - # Make the request - client.delete_data_source(request=request) - - Args: - request (Union[google.shopping.merchant_datasources_v1beta.types.DeleteDataSourceRequest, dict]): - The request object. Request message for the - DeleteDataSource method. - name (str): - Required. The name of the data source to delete. Format: - ``accounts/{account}/dataSources/{datasource}`` - - 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, datasources.DeleteDataSourceRequest): - request = datasources.DeleteDataSourceRequest(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_data_source] - - # Certain 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 fetch_data_source(self, - request: Optional[Union[datasources.FetchDataSourceRequest, 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"""Performs the data fetch immediately (even outside - fetch schedule) on a data source from your Merchant - Center Account. If you need to call this method more - than once per day, you should use the Products service - to update your product data instead. - This method only works on data sources with a file input - set. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_datasources_v1beta - - def sample_fetch_data_source(): - # Create a client - client = merchant_datasources_v1beta.DataSourcesServiceClient() - - # Initialize request argument(s) - request = merchant_datasources_v1beta.FetchDataSourceRequest( - name="name_value", - ) - - # Make the request - client.fetch_data_source(request=request) - - Args: - request (Union[google.shopping.merchant_datasources_v1beta.types.FetchDataSourceRequest, dict]): - The request object. Request message for the - FetchDataSource method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, 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, datasources.FetchDataSourceRequest): - request = datasources.FetchDataSourceRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.fetch_data_source] - - # Certain 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) -> "DataSourcesServiceClient": - 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__) - - -__all__ = ( - "DataSourcesServiceClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/pagers.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/pagers.py deleted file mode 100644 index 47f429541905..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/pagers.py +++ /dev/null @@ -1,166 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_datasources_v1beta.types import datasources - - -class ListDataSourcesPager: - """A pager for iterating through ``list_data_sources`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_datasources_v1beta.types.ListDataSourcesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``data_sources`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListDataSources`` requests and continue to iterate - through the ``data_sources`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_datasources_v1beta.types.ListDataSourcesResponse` - 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[..., datasources.ListDataSourcesResponse], - request: datasources.ListDataSourcesRequest, - response: datasources.ListDataSourcesResponse, - *, - 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_datasources_v1beta.types.ListDataSourcesRequest): - The initial request object. - response (google.shopping.merchant_datasources_v1beta.types.ListDataSourcesResponse): - 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 = datasources.ListDataSourcesRequest(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[datasources.ListDataSourcesResponse]: - 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[datasources.DataSource]: - for page in self.pages: - yield from page.data_sources - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListDataSourcesAsyncPager: - """A pager for iterating through ``list_data_sources`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_datasources_v1beta.types.ListDataSourcesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``data_sources`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListDataSources`` requests and continue to iterate - through the ``data_sources`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_datasources_v1beta.types.ListDataSourcesResponse` - 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[datasources.ListDataSourcesResponse]], - request: datasources.ListDataSourcesRequest, - response: datasources.ListDataSourcesResponse, - *, - 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_datasources_v1beta.types.ListDataSourcesRequest): - The initial request object. - response (google.shopping.merchant_datasources_v1beta.types.ListDataSourcesResponse): - 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 = datasources.ListDataSourcesRequest(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[datasources.ListDataSourcesResponse]: - 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[datasources.DataSource]: - async def async_generator(): - async for page in self.pages: - for response in page.data_sources: - 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-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/README.rst deleted file mode 100644 index bed349bac943..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`DataSourcesServiceTransport` is the ABC for all transports. -- public child `DataSourcesServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `DataSourcesServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseDataSourcesServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `DataSourcesServiceRestTransport` 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-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/__init__.py deleted file mode 100644 index 66c47267dddd..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 DataSourcesServiceTransport -from .grpc import DataSourcesServiceGrpcTransport -from .grpc_asyncio import DataSourcesServiceGrpcAsyncIOTransport -from .rest import DataSourcesServiceRestTransport -from .rest import DataSourcesServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[DataSourcesServiceTransport]] -_transport_registry['grpc'] = DataSourcesServiceGrpcTransport -_transport_registry['grpc_asyncio'] = DataSourcesServiceGrpcAsyncIOTransport -_transport_registry['rest'] = DataSourcesServiceRestTransport - -__all__ = ( - 'DataSourcesServiceTransport', - 'DataSourcesServiceGrpcTransport', - 'DataSourcesServiceGrpcAsyncIOTransport', - 'DataSourcesServiceRestTransport', - 'DataSourcesServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/base.py deleted file mode 100644 index 91843154c040..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/base.py +++ /dev/null @@ -1,225 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_datasources_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 - -from google.protobuf import empty_pb2 # type: ignore -from google.shopping.merchant_datasources_v1beta.types import datasources - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class DataSourcesServiceTransport(abc.ABC): - """Abstract transport class for DataSourcesService.""" - - 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_data_source: gapic_v1.method.wrap_method( - self.get_data_source, - default_timeout=None, - client_info=client_info, - ), - self.list_data_sources: gapic_v1.method.wrap_method( - self.list_data_sources, - default_timeout=None, - client_info=client_info, - ), - self.create_data_source: gapic_v1.method.wrap_method( - self.create_data_source, - default_timeout=None, - client_info=client_info, - ), - self.update_data_source: gapic_v1.method.wrap_method( - self.update_data_source, - default_timeout=None, - client_info=client_info, - ), - self.delete_data_source: gapic_v1.method.wrap_method( - self.delete_data_source, - default_timeout=None, - client_info=client_info, - ), - self.fetch_data_source: gapic_v1.method.wrap_method( - self.fetch_data_source, - 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_data_source(self) -> Callable[ - [datasources.GetDataSourceRequest], - Union[ - datasources.DataSource, - Awaitable[datasources.DataSource] - ]]: - raise NotImplementedError() - - @property - def list_data_sources(self) -> Callable[ - [datasources.ListDataSourcesRequest], - Union[ - datasources.ListDataSourcesResponse, - Awaitable[datasources.ListDataSourcesResponse] - ]]: - raise NotImplementedError() - - @property - def create_data_source(self) -> Callable[ - [datasources.CreateDataSourceRequest], - Union[ - datasources.DataSource, - Awaitable[datasources.DataSource] - ]]: - raise NotImplementedError() - - @property - def update_data_source(self) -> Callable[ - [datasources.UpdateDataSourceRequest], - Union[ - datasources.DataSource, - Awaitable[datasources.DataSource] - ]]: - raise NotImplementedError() - - @property - def delete_data_source(self) -> Callable[ - [datasources.DeleteDataSourceRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def fetch_data_source(self) -> Callable[ - [datasources.FetchDataSourceRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'DataSourcesServiceTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/grpc.py deleted file mode 100644 index 249da51b0608..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/grpc.py +++ /dev/null @@ -1,493 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_datasources_v1beta.types import datasources -from .base import DataSourcesServiceTransport, 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.datasources.v1beta.DataSourcesService", - "rpcName": 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.datasources.v1beta.DataSourcesService", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class DataSourcesServiceGrpcTransport(DataSourcesServiceTransport): - """gRPC backend transport for DataSourcesService. - - Service to manage primary, supplemental, inventory and other data - sources. See more in the `Merchant - Center `__ help - article. - - This 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_data_source(self) -> Callable[ - [datasources.GetDataSourceRequest], - datasources.DataSource]: - r"""Return a callable for the get data source method over gRPC. - - Retrieves the data source configuration for the given - account. - - Returns: - Callable[[~.GetDataSourceRequest], - ~.DataSource]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_data_source' not in self._stubs: - self._stubs['get_data_source'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.datasources.v1beta.DataSourcesService/GetDataSource', - request_serializer=datasources.GetDataSourceRequest.serialize, - response_deserializer=datasources.DataSource.deserialize, - ) - return self._stubs['get_data_source'] - - @property - def list_data_sources(self) -> Callable[ - [datasources.ListDataSourcesRequest], - datasources.ListDataSourcesResponse]: - r"""Return a callable for the list data sources method over gRPC. - - Lists the configurations for data sources for the - given account. - - Returns: - Callable[[~.ListDataSourcesRequest], - ~.ListDataSourcesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_data_sources' not in self._stubs: - self._stubs['list_data_sources'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.datasources.v1beta.DataSourcesService/ListDataSources', - request_serializer=datasources.ListDataSourcesRequest.serialize, - response_deserializer=datasources.ListDataSourcesResponse.deserialize, - ) - return self._stubs['list_data_sources'] - - @property - def create_data_source(self) -> Callable[ - [datasources.CreateDataSourceRequest], - datasources.DataSource]: - r"""Return a callable for the create data source method over gRPC. - - Creates the new data source configuration for the - given account. - - Returns: - Callable[[~.CreateDataSourceRequest], - ~.DataSource]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_data_source' not in self._stubs: - self._stubs['create_data_source'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.datasources.v1beta.DataSourcesService/CreateDataSource', - request_serializer=datasources.CreateDataSourceRequest.serialize, - response_deserializer=datasources.DataSource.deserialize, - ) - return self._stubs['create_data_source'] - - @property - def update_data_source(self) -> Callable[ - [datasources.UpdateDataSourceRequest], - datasources.DataSource]: - r"""Return a callable for the update data source method over gRPC. - - Updates the existing data source configuration. The - fields that are set in the update mask but not provided - in the resource will be deleted. - - Returns: - Callable[[~.UpdateDataSourceRequest], - ~.DataSource]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_data_source' not in self._stubs: - self._stubs['update_data_source'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.datasources.v1beta.DataSourcesService/UpdateDataSource', - request_serializer=datasources.UpdateDataSourceRequest.serialize, - response_deserializer=datasources.DataSource.deserialize, - ) - return self._stubs['update_data_source'] - - @property - def delete_data_source(self) -> Callable[ - [datasources.DeleteDataSourceRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete data source method over gRPC. - - Deletes a data source from your Merchant Center - account. - - Returns: - Callable[[~.DeleteDataSourceRequest], - ~.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_data_source' not in self._stubs: - self._stubs['delete_data_source'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.datasources.v1beta.DataSourcesService/DeleteDataSource', - request_serializer=datasources.DeleteDataSourceRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_data_source'] - - @property - def fetch_data_source(self) -> Callable[ - [datasources.FetchDataSourceRequest], - empty_pb2.Empty]: - r"""Return a callable for the fetch data source method over gRPC. - - Performs the data fetch immediately (even outside - fetch schedule) on a data source from your Merchant - Center Account. If you need to call this method more - than once per day, you should use the Products service - to update your product data instead. - This method only works on data sources with a file input - set. - - Returns: - Callable[[~.FetchDataSourceRequest], - ~.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 'fetch_data_source' not in self._stubs: - self._stubs['fetch_data_source'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.datasources.v1beta.DataSourcesService/FetchDataSource', - request_serializer=datasources.FetchDataSourceRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['fetch_data_source'] - - def close(self): - self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'DataSourcesServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/grpc_asyncio.py deleted file mode 100644 index 5af9b5cb8e6c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,538 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_datasources_v1beta.types import datasources -from .base import DataSourcesServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import DataSourcesServiceGrpcTransport - -try: - from google.api_core import client_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.datasources.v1beta.DataSourcesService", - "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.datasources.v1beta.DataSourcesService", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class DataSourcesServiceGrpcAsyncIOTransport(DataSourcesServiceTransport): - """gRPC AsyncIO backend transport for DataSourcesService. - - Service to manage primary, supplemental, inventory and other data - sources. See more in the `Merchant - Center `__ help - article. - - This 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_data_source(self) -> Callable[ - [datasources.GetDataSourceRequest], - Awaitable[datasources.DataSource]]: - r"""Return a callable for the get data source method over gRPC. - - Retrieves the data source configuration for the given - account. - - Returns: - Callable[[~.GetDataSourceRequest], - Awaitable[~.DataSource]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_data_source' not in self._stubs: - self._stubs['get_data_source'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.datasources.v1beta.DataSourcesService/GetDataSource', - request_serializer=datasources.GetDataSourceRequest.serialize, - response_deserializer=datasources.DataSource.deserialize, - ) - return self._stubs['get_data_source'] - - @property - def list_data_sources(self) -> Callable[ - [datasources.ListDataSourcesRequest], - Awaitable[datasources.ListDataSourcesResponse]]: - r"""Return a callable for the list data sources method over gRPC. - - Lists the configurations for data sources for the - given account. - - Returns: - Callable[[~.ListDataSourcesRequest], - Awaitable[~.ListDataSourcesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_data_sources' not in self._stubs: - self._stubs['list_data_sources'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.datasources.v1beta.DataSourcesService/ListDataSources', - request_serializer=datasources.ListDataSourcesRequest.serialize, - response_deserializer=datasources.ListDataSourcesResponse.deserialize, - ) - return self._stubs['list_data_sources'] - - @property - def create_data_source(self) -> Callable[ - [datasources.CreateDataSourceRequest], - Awaitable[datasources.DataSource]]: - r"""Return a callable for the create data source method over gRPC. - - Creates the new data source configuration for the - given account. - - Returns: - Callable[[~.CreateDataSourceRequest], - Awaitable[~.DataSource]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_data_source' not in self._stubs: - self._stubs['create_data_source'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.datasources.v1beta.DataSourcesService/CreateDataSource', - request_serializer=datasources.CreateDataSourceRequest.serialize, - response_deserializer=datasources.DataSource.deserialize, - ) - return self._stubs['create_data_source'] - - @property - def update_data_source(self) -> Callable[ - [datasources.UpdateDataSourceRequest], - Awaitable[datasources.DataSource]]: - r"""Return a callable for the update data source method over gRPC. - - Updates the existing data source configuration. The - fields that are set in the update mask but not provided - in the resource will be deleted. - - Returns: - Callable[[~.UpdateDataSourceRequest], - Awaitable[~.DataSource]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_data_source' not in self._stubs: - self._stubs['update_data_source'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.datasources.v1beta.DataSourcesService/UpdateDataSource', - request_serializer=datasources.UpdateDataSourceRequest.serialize, - response_deserializer=datasources.DataSource.deserialize, - ) - return self._stubs['update_data_source'] - - @property - def delete_data_source(self) -> Callable[ - [datasources.DeleteDataSourceRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete data source method over gRPC. - - Deletes a data source from your Merchant Center - account. - - Returns: - Callable[[~.DeleteDataSourceRequest], - 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_data_source' not in self._stubs: - self._stubs['delete_data_source'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.datasources.v1beta.DataSourcesService/DeleteDataSource', - request_serializer=datasources.DeleteDataSourceRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_data_source'] - - @property - def fetch_data_source(self) -> Callable[ - [datasources.FetchDataSourceRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the fetch data source method over gRPC. - - Performs the data fetch immediately (even outside - fetch schedule) on a data source from your Merchant - Center Account. If you need to call this method more - than once per day, you should use the Products service - to update your product data instead. - This method only works on data sources with a file input - set. - - Returns: - Callable[[~.FetchDataSourceRequest], - 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 'fetch_data_source' not in self._stubs: - self._stubs['fetch_data_source'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.datasources.v1beta.DataSourcesService/FetchDataSource', - request_serializer=datasources.FetchDataSourceRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['fetch_data_source'] - - 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_data_source: self._wrap_method( - self.get_data_source, - default_timeout=None, - client_info=client_info, - ), - self.list_data_sources: self._wrap_method( - self.list_data_sources, - default_timeout=None, - client_info=client_info, - ), - self.create_data_source: self._wrap_method( - self.create_data_source, - default_timeout=None, - client_info=client_info, - ), - self.update_data_source: self._wrap_method( - self.update_data_source, - default_timeout=None, - client_info=client_info, - ), - self.delete_data_source: self._wrap_method( - self.delete_data_source, - default_timeout=None, - client_info=client_info, - ), - self.fetch_data_source: self._wrap_method( - self.fetch_data_source, - 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__ = ( - 'DataSourcesServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/rest.py deleted file mode 100644 index bde98ec2e52e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/rest.py +++ /dev/null @@ -1,1016 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -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_datasources_v1beta.types import datasources - - -from .rest_base import _BaseDataSourcesServiceRestTransport -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}", -) - - -class DataSourcesServiceRestInterceptor: - """Interceptor for DataSourcesService. - - 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 DataSourcesServiceRestTransport. - - .. code-block:: python - class MyCustomDataSourcesServiceInterceptor(DataSourcesServiceRestInterceptor): - def pre_create_data_source(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_data_source(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_data_source(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_fetch_data_source(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_data_source(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_data_source(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_data_sources(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_data_sources(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_data_source(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_data_source(self, response): - logging.log(f"Received response: {response}") - return response - - transport = DataSourcesServiceRestTransport(interceptor=MyCustomDataSourcesServiceInterceptor()) - client = DataSourcesServiceClient(transport=transport) - - - """ - def pre_create_data_source(self, request: datasources.CreateDataSourceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[datasources.CreateDataSourceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for create_data_source - - Override in a subclass to manipulate the request or metadata - before they are sent to the DataSourcesService server. - """ - return request, metadata - - def post_create_data_source(self, response: datasources.DataSource) -> datasources.DataSource: - """Post-rpc interceptor for create_data_source - - Override in a subclass to manipulate the response - after it is returned by the DataSourcesService server but before - it is returned to user code. - """ - return response - - def pre_delete_data_source(self, request: datasources.DeleteDataSourceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[datasources.DeleteDataSourceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_data_source - - Override in a subclass to manipulate the request or metadata - before they are sent to the DataSourcesService server. - """ - return request, metadata - - def pre_fetch_data_source(self, request: datasources.FetchDataSourceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[datasources.FetchDataSourceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for fetch_data_source - - Override in a subclass to manipulate the request or metadata - before they are sent to the DataSourcesService server. - """ - return request, metadata - - def pre_get_data_source(self, request: datasources.GetDataSourceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[datasources.GetDataSourceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_data_source - - Override in a subclass to manipulate the request or metadata - before they are sent to the DataSourcesService server. - """ - return request, metadata - - def post_get_data_source(self, response: datasources.DataSource) -> datasources.DataSource: - """Post-rpc interceptor for get_data_source - - Override in a subclass to manipulate the response - after it is returned by the DataSourcesService server but before - it is returned to user code. - """ - return response - - def pre_list_data_sources(self, request: datasources.ListDataSourcesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[datasources.ListDataSourcesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_data_sources - - Override in a subclass to manipulate the request or metadata - before they are sent to the DataSourcesService server. - """ - return request, metadata - - def post_list_data_sources(self, response: datasources.ListDataSourcesResponse) -> datasources.ListDataSourcesResponse: - """Post-rpc interceptor for list_data_sources - - Override in a subclass to manipulate the response - after it is returned by the DataSourcesService server but before - it is returned to user code. - """ - return response - - def pre_update_data_source(self, request: datasources.UpdateDataSourceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[datasources.UpdateDataSourceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for update_data_source - - Override in a subclass to manipulate the request or metadata - before they are sent to the DataSourcesService server. - """ - return request, metadata - - def post_update_data_source(self, response: datasources.DataSource) -> datasources.DataSource: - """Post-rpc interceptor for update_data_source - - Override in a subclass to manipulate the response - after it is returned by the DataSourcesService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class DataSourcesServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: DataSourcesServiceRestInterceptor - - -class DataSourcesServiceRestTransport(_BaseDataSourcesServiceRestTransport): - """REST backend synchronous transport for DataSourcesService. - - Service to manage primary, supplemental, inventory and other data - sources. See more in the `Merchant - Center `__ help - article. - - This 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[DataSourcesServiceRestInterceptor] = 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 DataSourcesServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _CreateDataSource(_BaseDataSourcesServiceRestTransport._BaseCreateDataSource, DataSourcesServiceRestStub): - def __hash__(self): - return hash("DataSourcesServiceRestTransport.CreateDataSource") - - @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: datasources.CreateDataSourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> datasources.DataSource: - r"""Call the create data source method over HTTP. - - Args: - request (~.datasources.CreateDataSourceRequest): - The request object. Request message for the - CreateDataSource method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.datasources.DataSource: - The `data - source `__ - for the Merchant Center account. - - """ - - http_options = _BaseDataSourcesServiceRestTransport._BaseCreateDataSource._get_http_options() - - request, metadata = self._interceptor.pre_create_data_source(request, metadata) - transcoded_request = _BaseDataSourcesServiceRestTransport._BaseCreateDataSource._get_transcoded_request(http_options, request) - - body = _BaseDataSourcesServiceRestTransport._BaseCreateDataSource._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseDataSourcesServiceRestTransport._BaseCreateDataSource._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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.datasources_v1beta.DataSourcesServiceClient.CreateDataSource", - extra = { - "serviceName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", - "rpcName": "CreateDataSource", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = DataSourcesServiceRestTransport._CreateDataSource._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 = datasources.DataSource() - pb_resp = datasources.DataSource.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_create_data_source(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = datasources.DataSource.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.datasources_v1beta.DataSourcesServiceClient.create_data_source", - extra = { - "serviceName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", - "rpcName": "CreateDataSource", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _DeleteDataSource(_BaseDataSourcesServiceRestTransport._BaseDeleteDataSource, DataSourcesServiceRestStub): - def __hash__(self): - return hash("DataSourcesServiceRestTransport.DeleteDataSource") - - @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: datasources.DeleteDataSourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ): - r"""Call the delete data source method over HTTP. - - Args: - request (~.datasources.DeleteDataSourceRequest): - The request object. Request message for the - DeleteDataSource method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, 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 = _BaseDataSourcesServiceRestTransport._BaseDeleteDataSource._get_http_options() - - request, metadata = self._interceptor.pre_delete_data_source(request, metadata) - transcoded_request = _BaseDataSourcesServiceRestTransport._BaseDeleteDataSource._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseDataSourcesServiceRestTransport._BaseDeleteDataSource._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(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.datasources_v1beta.DataSourcesServiceClient.DeleteDataSource", - extra = { - "serviceName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", - "rpcName": "DeleteDataSource", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = DataSourcesServiceRestTransport._DeleteDataSource._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 _FetchDataSource(_BaseDataSourcesServiceRestTransport._BaseFetchDataSource, DataSourcesServiceRestStub): - def __hash__(self): - return hash("DataSourcesServiceRestTransport.FetchDataSource") - - @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: datasources.FetchDataSourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ): - r"""Call the fetch data source method over HTTP. - - Args: - request (~.datasources.FetchDataSourceRequest): - The request object. Request message for the - FetchDataSource method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, 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 = _BaseDataSourcesServiceRestTransport._BaseFetchDataSource._get_http_options() - - request, metadata = self._interceptor.pre_fetch_data_source(request, metadata) - transcoded_request = _BaseDataSourcesServiceRestTransport._BaseFetchDataSource._get_transcoded_request(http_options, request) - - body = _BaseDataSourcesServiceRestTransport._BaseFetchDataSource._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseDataSourcesServiceRestTransport._BaseFetchDataSource._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(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.datasources_v1beta.DataSourcesServiceClient.FetchDataSource", - extra = { - "serviceName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", - "rpcName": "FetchDataSource", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = DataSourcesServiceRestTransport._FetchDataSource._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _GetDataSource(_BaseDataSourcesServiceRestTransport._BaseGetDataSource, DataSourcesServiceRestStub): - def __hash__(self): - return hash("DataSourcesServiceRestTransport.GetDataSource") - - @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: datasources.GetDataSourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> datasources.DataSource: - r"""Call the get data source method over HTTP. - - Args: - request (~.datasources.GetDataSourceRequest): - The request object. Request message for the GetDataSource - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.datasources.DataSource: - The `data - source `__ - for the Merchant Center account. - - """ - - http_options = _BaseDataSourcesServiceRestTransport._BaseGetDataSource._get_http_options() - - request, metadata = self._interceptor.pre_get_data_source(request, metadata) - transcoded_request = _BaseDataSourcesServiceRestTransport._BaseGetDataSource._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseDataSourcesServiceRestTransport._BaseGetDataSource._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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.datasources_v1beta.DataSourcesServiceClient.GetDataSource", - extra = { - "serviceName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", - "rpcName": "GetDataSource", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = DataSourcesServiceRestTransport._GetDataSource._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 = datasources.DataSource() - pb_resp = datasources.DataSource.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_data_source(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = datasources.DataSource.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.datasources_v1beta.DataSourcesServiceClient.get_data_source", - extra = { - "serviceName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", - "rpcName": "GetDataSource", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListDataSources(_BaseDataSourcesServiceRestTransport._BaseListDataSources, DataSourcesServiceRestStub): - def __hash__(self): - return hash("DataSourcesServiceRestTransport.ListDataSources") - - @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: datasources.ListDataSourcesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> datasources.ListDataSourcesResponse: - r"""Call the list data sources method over HTTP. - - Args: - request (~.datasources.ListDataSourcesRequest): - The request object. Request message for the - ListDataSources method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.datasources.ListDataSourcesResponse: - Response message for the - ListDataSources method. - - """ - - http_options = _BaseDataSourcesServiceRestTransport._BaseListDataSources._get_http_options() - - request, metadata = self._interceptor.pre_list_data_sources(request, metadata) - transcoded_request = _BaseDataSourcesServiceRestTransport._BaseListDataSources._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseDataSourcesServiceRestTransport._BaseListDataSources._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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.datasources_v1beta.DataSourcesServiceClient.ListDataSources", - extra = { - "serviceName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", - "rpcName": "ListDataSources", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = DataSourcesServiceRestTransport._ListDataSources._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 = datasources.ListDataSourcesResponse() - pb_resp = datasources.ListDataSourcesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_data_sources(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = datasources.ListDataSourcesResponse.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.datasources_v1beta.DataSourcesServiceClient.list_data_sources", - extra = { - "serviceName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", - "rpcName": "ListDataSources", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UpdateDataSource(_BaseDataSourcesServiceRestTransport._BaseUpdateDataSource, DataSourcesServiceRestStub): - def __hash__(self): - return hash("DataSourcesServiceRestTransport.UpdateDataSource") - - @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: datasources.UpdateDataSourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> datasources.DataSource: - r"""Call the update data source method over HTTP. - - Args: - request (~.datasources.UpdateDataSourceRequest): - The request object. Request message for the - UpdateDataSource method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.datasources.DataSource: - The `data - source `__ - for the Merchant Center account. - - """ - - http_options = _BaseDataSourcesServiceRestTransport._BaseUpdateDataSource._get_http_options() - - request, metadata = self._interceptor.pre_update_data_source(request, metadata) - transcoded_request = _BaseDataSourcesServiceRestTransport._BaseUpdateDataSource._get_transcoded_request(http_options, request) - - body = _BaseDataSourcesServiceRestTransport._BaseUpdateDataSource._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseDataSourcesServiceRestTransport._BaseUpdateDataSource._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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.datasources_v1beta.DataSourcesServiceClient.UpdateDataSource", - extra = { - "serviceName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", - "rpcName": "UpdateDataSource", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = DataSourcesServiceRestTransport._UpdateDataSource._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 = datasources.DataSource() - pb_resp = datasources.DataSource.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_update_data_source(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = datasources.DataSource.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.datasources_v1beta.DataSourcesServiceClient.update_data_source", - extra = { - "serviceName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", - "rpcName": "UpdateDataSource", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def create_data_source(self) -> Callable[ - [datasources.CreateDataSourceRequest], - datasources.DataSource]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateDataSource(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_data_source(self) -> Callable[ - [datasources.DeleteDataSourceRequest], - 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._DeleteDataSource(self._session, self._host, self._interceptor) # type: ignore - - @property - def fetch_data_source(self) -> Callable[ - [datasources.FetchDataSourceRequest], - 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._FetchDataSource(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_data_source(self) -> Callable[ - [datasources.GetDataSourceRequest], - datasources.DataSource]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetDataSource(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_data_sources(self) -> Callable[ - [datasources.ListDataSourcesRequest], - datasources.ListDataSourcesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListDataSources(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_data_source(self) -> Callable[ - [datasources.UpdateDataSourceRequest], - datasources.DataSource]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateDataSource(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'DataSourcesServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/rest_base.py deleted file mode 100644 index 241c9ea5e7aa..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/rest_base.py +++ /dev/null @@ -1,344 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 DataSourcesServiceTransport, 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_datasources_v1beta.types import datasources - - -class _BaseDataSourcesServiceRestTransport(DataSourcesServiceTransport): - """Base REST backend transport for DataSourcesService. - - 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 _BaseCreateDataSource: - 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': '/datasources/v1beta/{parent=accounts/*}/dataSources', - 'body': 'data_source', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = datasources.CreateDataSourceRequest.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(_BaseDataSourcesServiceRestTransport._BaseCreateDataSource._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteDataSource: - 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': '/datasources/v1beta/{name=accounts/*/dataSources/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = datasources.DeleteDataSourceRequest.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(_BaseDataSourcesServiceRestTransport._BaseDeleteDataSource._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseFetchDataSource: - 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': '/datasources/v1beta/{name=accounts/*/dataSources/*}:fetch', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = datasources.FetchDataSourceRequest.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(_BaseDataSourcesServiceRestTransport._BaseFetchDataSource._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetDataSource: - 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': '/datasources/v1beta/{name=accounts/*/dataSources/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = datasources.GetDataSourceRequest.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(_BaseDataSourcesServiceRestTransport._BaseGetDataSource._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListDataSources: - 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': '/datasources/v1beta/{parent=accounts/*}/dataSources', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = datasources.ListDataSourcesRequest.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(_BaseDataSourcesServiceRestTransport._BaseListDataSources._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateDataSource: - 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': '/datasources/v1beta/{data_source.name=accounts/*/dataSources/*}', - 'body': 'data_source', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = datasources.UpdateDataSourceRequest.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(_BaseDataSourcesServiceRestTransport._BaseUpdateDataSource._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseDataSourcesServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/__init__.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/__init__.py deleted file mode 100644 index 654b958c5a64..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 FileUploadsServiceClient -from .async_client import FileUploadsServiceAsyncClient - -__all__ = ( - 'FileUploadsServiceClient', - 'FileUploadsServiceAsyncClient', -) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/async_client.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/async_client.py deleted file mode 100644 index acdb53d2490c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/async_client.py +++ /dev/null @@ -1,372 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_datasources_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 - - -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 timestamp_pb2 # type: ignore -from google.shopping.merchant_datasources_v1beta.types import fileuploads -from .transports.base import FileUploadsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import FileUploadsServiceGrpcAsyncIOTransport -from .client import FileUploadsServiceClient - -try: - from google.api_core import client_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 FileUploadsServiceAsyncClient: - """Service to manage data source file uploads.""" - - _client: FileUploadsServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = FileUploadsServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = FileUploadsServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = FileUploadsServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = FileUploadsServiceClient._DEFAULT_UNIVERSE - - file_upload_path = staticmethod(FileUploadsServiceClient.file_upload_path) - parse_file_upload_path = staticmethod(FileUploadsServiceClient.parse_file_upload_path) - common_billing_account_path = staticmethod(FileUploadsServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(FileUploadsServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(FileUploadsServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(FileUploadsServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(FileUploadsServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(FileUploadsServiceClient.parse_common_organization_path) - common_project_path = staticmethod(FileUploadsServiceClient.common_project_path) - parse_common_project_path = staticmethod(FileUploadsServiceClient.parse_common_project_path) - common_location_path = staticmethod(FileUploadsServiceClient.common_location_path) - parse_common_location_path = staticmethod(FileUploadsServiceClient.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: - FileUploadsServiceAsyncClient: The constructed client. - """ - return FileUploadsServiceClient.from_service_account_info.__func__(FileUploadsServiceAsyncClient, 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: - FileUploadsServiceAsyncClient: The constructed client. - """ - return FileUploadsServiceClient.from_service_account_file.__func__(FileUploadsServiceAsyncClient, 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 FileUploadsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> FileUploadsServiceTransport: - """Returns the transport used by the client instance. - - Returns: - FileUploadsServiceTransport: 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 = FileUploadsServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, FileUploadsServiceTransport, Callable[..., FileUploadsServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the file uploads 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,FileUploadsServiceTransport,Callable[..., FileUploadsServiceTransport]]]): - 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 FileUploadsServiceTransport 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 = FileUploadsServiceClient( - 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.datasources_v1beta.FileUploadsServiceAsyncClient`.", - extra = { - "serviceName": "google.shopping.merchant.datasources.v1beta.FileUploadsService", - "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.datasources.v1beta.FileUploadsService", - "credentialsType": None, - } - ) - - async def get_file_upload(self, - request: Optional[Union[fileuploads.GetFileUploadRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> fileuploads.FileUpload: - r"""Gets the latest data source file upload. Only the ``latest`` - alias is accepted for a file upload. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_datasources_v1beta - - async def sample_get_file_upload(): - # Create a client - client = merchant_datasources_v1beta.FileUploadsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_datasources_v1beta.GetFileUploadRequest( - name="name_value", - ) - - # Make the request - response = await client.get_file_upload(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_datasources_v1beta.types.GetFileUploadRequest, dict]]): - The request object. Request message for the - GetFileUploadRequest method. - name (:class:`str`): - Required. The name of the data source file upload to - retrieve. Format: - ``accounts/{account}/dataSources/{datasource}/fileUploads/latest`` - - 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_datasources_v1beta.types.FileUpload: - The file upload of a specific data - source, that is, the result of the - retrieval of the data source at a - certain timestamp computed - asynchronously when the data source - processing is finished. Only applicable - to file data sources. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, fileuploads.GetFileUploadRequest): - request = fileuploads.GetFileUploadRequest(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_file_upload] - - # Certain 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) -> "FileUploadsServiceAsyncClient": - 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__) - - -__all__ = ( - "FileUploadsServiceAsyncClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/client.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/client.py deleted file mode 100644 index a4913f7434e6..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/client.py +++ /dev/null @@ -1,707 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -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_datasources_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 - -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 timestamp_pb2 # type: ignore -from google.shopping.merchant_datasources_v1beta.types import fileuploads -from .transports.base import FileUploadsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import FileUploadsServiceGrpcTransport -from .transports.grpc_asyncio import FileUploadsServiceGrpcAsyncIOTransport -from .transports.rest import FileUploadsServiceRestTransport - - -class FileUploadsServiceClientMeta(type): - """Metaclass for the FileUploadsService 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[FileUploadsServiceTransport]] - _transport_registry["grpc"] = FileUploadsServiceGrpcTransport - _transport_registry["grpc_asyncio"] = FileUploadsServiceGrpcAsyncIOTransport - _transport_registry["rest"] = FileUploadsServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[FileUploadsServiceTransport]: - """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 FileUploadsServiceClient(metaclass=FileUploadsServiceClientMeta): - """Service to manage data source file uploads.""" - - @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: - FileUploadsServiceClient: 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: - FileUploadsServiceClient: 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) -> FileUploadsServiceTransport: - """Returns the transport used by the client instance. - - Returns: - FileUploadsServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def file_upload_path(account: str,datasource: str,fileupload: str,) -> str: - """Returns a fully-qualified file_upload string.""" - return "accounts/{account}/dataSources/{datasource}/fileUploads/{fileupload}".format(account=account, datasource=datasource, fileupload=fileupload, ) - - @staticmethod - def parse_file_upload_path(path: str) -> Dict[str,str]: - """Parses a file_upload path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/dataSources/(?P.+?)/fileUploads/(?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 = FileUploadsServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = FileUploadsServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = FileUploadsServiceClient._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 = FileUploadsServiceClient._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 - - @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, FileUploadsServiceTransport, Callable[..., FileUploadsServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the file uploads 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,FileUploadsServiceTransport,Callable[..., FileUploadsServiceTransport]]]): - 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 FileUploadsServiceTransport 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 = FileUploadsServiceClient._read_environment_variables() - self._client_cert_source = FileUploadsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = FileUploadsServiceClient._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, FileUploadsServiceTransport) - if transport_provided: - # transport is a FileUploadsServiceTransport 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(FileUploadsServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - FileUploadsServiceClient._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[FileUploadsServiceTransport], Callable[..., FileUploadsServiceTransport]] = ( - FileUploadsServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., FileUploadsServiceTransport], 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.datasources_v1beta.FileUploadsServiceClient`.", - extra = { - "serviceName": "google.shopping.merchant.datasources.v1beta.FileUploadsService", - "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.datasources.v1beta.FileUploadsService", - "credentialsType": None, - } - ) - - def get_file_upload(self, - request: Optional[Union[fileuploads.GetFileUploadRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> fileuploads.FileUpload: - r"""Gets the latest data source file upload. Only the ``latest`` - alias is accepted for a file upload. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_datasources_v1beta - - def sample_get_file_upload(): - # Create a client - client = merchant_datasources_v1beta.FileUploadsServiceClient() - - # Initialize request argument(s) - request = merchant_datasources_v1beta.GetFileUploadRequest( - name="name_value", - ) - - # Make the request - response = client.get_file_upload(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_datasources_v1beta.types.GetFileUploadRequest, dict]): - The request object. Request message for the - GetFileUploadRequest method. - name (str): - Required. The name of the data source file upload to - retrieve. Format: - ``accounts/{account}/dataSources/{datasource}/fileUploads/latest`` - - 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_datasources_v1beta.types.FileUpload: - The file upload of a specific data - source, that is, the result of the - retrieval of the data source at a - certain timestamp computed - asynchronously when the data source - processing is finished. Only applicable - to file data sources. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, fileuploads.GetFileUploadRequest): - request = fileuploads.GetFileUploadRequest(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_file_upload] - - # Certain 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) -> "FileUploadsServiceClient": - 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__) - - -__all__ = ( - "FileUploadsServiceClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/README.rst deleted file mode 100644 index 950ff4a21abd..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`FileUploadsServiceTransport` is the ABC for all transports. -- public child `FileUploadsServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `FileUploadsServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseFileUploadsServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `FileUploadsServiceRestTransport` 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-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/__init__.py deleted file mode 100644 index a25a3f24c7be..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 FileUploadsServiceTransport -from .grpc import FileUploadsServiceGrpcTransport -from .grpc_asyncio import FileUploadsServiceGrpcAsyncIOTransport -from .rest import FileUploadsServiceRestTransport -from .rest import FileUploadsServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[FileUploadsServiceTransport]] -_transport_registry['grpc'] = FileUploadsServiceGrpcTransport -_transport_registry['grpc_asyncio'] = FileUploadsServiceGrpcAsyncIOTransport -_transport_registry['rest'] = FileUploadsServiceRestTransport - -__all__ = ( - 'FileUploadsServiceTransport', - 'FileUploadsServiceGrpcTransport', - 'FileUploadsServiceGrpcAsyncIOTransport', - 'FileUploadsServiceRestTransport', - 'FileUploadsServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/base.py deleted file mode 100644 index f2ec31cc2944..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/base.py +++ /dev/null @@ -1,154 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_datasources_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 - -from google.shopping.merchant_datasources_v1beta.types import fileuploads - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class FileUploadsServiceTransport(abc.ABC): - """Abstract transport class for FileUploadsService.""" - - 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_file_upload: gapic_v1.method.wrap_method( - self.get_file_upload, - 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_file_upload(self) -> Callable[ - [fileuploads.GetFileUploadRequest], - Union[ - fileuploads.FileUpload, - Awaitable[fileuploads.FileUpload] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'FileUploadsServiceTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/grpc.py deleted file mode 100644 index 9b117a33dc20..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/grpc.py +++ /dev/null @@ -1,348 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_datasources_v1beta.types import fileuploads -from .base import FileUploadsServiceTransport, 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.datasources.v1beta.FileUploadsService", - "rpcName": 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.datasources.v1beta.FileUploadsService", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class FileUploadsServiceGrpcTransport(FileUploadsServiceTransport): - """gRPC backend transport for FileUploadsService. - - Service to manage data source file uploads. - - This 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_file_upload(self) -> Callable[ - [fileuploads.GetFileUploadRequest], - fileuploads.FileUpload]: - r"""Return a callable for the get file upload method over gRPC. - - Gets the latest data source file upload. Only the ``latest`` - alias is accepted for a file upload. - - Returns: - Callable[[~.GetFileUploadRequest], - ~.FileUpload]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_file_upload' not in self._stubs: - self._stubs['get_file_upload'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.datasources.v1beta.FileUploadsService/GetFileUpload', - request_serializer=fileuploads.GetFileUploadRequest.serialize, - response_deserializer=fileuploads.FileUpload.deserialize, - ) - return self._stubs['get_file_upload'] - - def close(self): - self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'FileUploadsServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/grpc_asyncio.py deleted file mode 100644 index 3b0b5d4fab73..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,368 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_datasources_v1beta.types import fileuploads -from .base import FileUploadsServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import FileUploadsServiceGrpcTransport - -try: - from google.api_core import client_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.datasources.v1beta.FileUploadsService", - "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.datasources.v1beta.FileUploadsService", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class FileUploadsServiceGrpcAsyncIOTransport(FileUploadsServiceTransport): - """gRPC AsyncIO backend transport for FileUploadsService. - - Service to manage data source file uploads. - - This 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_file_upload(self) -> Callable[ - [fileuploads.GetFileUploadRequest], - Awaitable[fileuploads.FileUpload]]: - r"""Return a callable for the get file upload method over gRPC. - - Gets the latest data source file upload. Only the ``latest`` - alias is accepted for a file upload. - - Returns: - Callable[[~.GetFileUploadRequest], - Awaitable[~.FileUpload]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_file_upload' not in self._stubs: - self._stubs['get_file_upload'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.datasources.v1beta.FileUploadsService/GetFileUpload', - request_serializer=fileuploads.GetFileUploadRequest.serialize, - response_deserializer=fileuploads.FileUpload.deserialize, - ) - return self._stubs['get_file_upload'] - - 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_file_upload: self._wrap_method( - self.get_file_upload, - 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__ = ( - 'FileUploadsServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/rest.py deleted file mode 100644 index 88985daefcd9..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/rest.py +++ /dev/null @@ -1,334 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -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_datasources_v1beta.types import fileuploads - - -from .rest_base import _BaseFileUploadsServiceRestTransport -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}", -) - - -class FileUploadsServiceRestInterceptor: - """Interceptor for FileUploadsService. - - 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 FileUploadsServiceRestTransport. - - .. code-block:: python - class MyCustomFileUploadsServiceInterceptor(FileUploadsServiceRestInterceptor): - def pre_get_file_upload(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_file_upload(self, response): - logging.log(f"Received response: {response}") - return response - - transport = FileUploadsServiceRestTransport(interceptor=MyCustomFileUploadsServiceInterceptor()) - client = FileUploadsServiceClient(transport=transport) - - - """ - def pre_get_file_upload(self, request: fileuploads.GetFileUploadRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[fileuploads.GetFileUploadRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_file_upload - - Override in a subclass to manipulate the request or metadata - before they are sent to the FileUploadsService server. - """ - return request, metadata - - def post_get_file_upload(self, response: fileuploads.FileUpload) -> fileuploads.FileUpload: - """Post-rpc interceptor for get_file_upload - - Override in a subclass to manipulate the response - after it is returned by the FileUploadsService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class FileUploadsServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: FileUploadsServiceRestInterceptor - - -class FileUploadsServiceRestTransport(_BaseFileUploadsServiceRestTransport): - """REST backend synchronous transport for FileUploadsService. - - Service to manage data source file uploads. - - This 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[FileUploadsServiceRestInterceptor] = 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 FileUploadsServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _GetFileUpload(_BaseFileUploadsServiceRestTransport._BaseGetFileUpload, FileUploadsServiceRestStub): - def __hash__(self): - return hash("FileUploadsServiceRestTransport.GetFileUpload") - - @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: fileuploads.GetFileUploadRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> fileuploads.FileUpload: - r"""Call the get file upload method over HTTP. - - Args: - request (~.fileuploads.GetFileUploadRequest): - The request object. Request message for the - GetFileUploadRequest method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.fileuploads.FileUpload: - The file upload of a specific data - source, that is, the result of the - retrieval of the data source at a - certain timestamp computed - asynchronously when the data source - processing is finished. Only applicable - to file data sources. - - """ - - http_options = _BaseFileUploadsServiceRestTransport._BaseGetFileUpload._get_http_options() - - request, metadata = self._interceptor.pre_get_file_upload(request, metadata) - transcoded_request = _BaseFileUploadsServiceRestTransport._BaseGetFileUpload._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseFileUploadsServiceRestTransport._BaseGetFileUpload._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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.datasources_v1beta.FileUploadsServiceClient.GetFileUpload", - extra = { - "serviceName": "google.shopping.merchant.datasources.v1beta.FileUploadsService", - "rpcName": "GetFileUpload", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = FileUploadsServiceRestTransport._GetFileUpload._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 = fileuploads.FileUpload() - pb_resp = fileuploads.FileUpload.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_file_upload(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = fileuploads.FileUpload.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.datasources_v1beta.FileUploadsServiceClient.get_file_upload", - extra = { - "serviceName": "google.shopping.merchant.datasources.v1beta.FileUploadsService", - "rpcName": "GetFileUpload", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def get_file_upload(self) -> Callable[ - [fileuploads.GetFileUploadRequest], - fileuploads.FileUpload]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetFileUpload(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'FileUploadsServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/rest_base.py deleted file mode 100644 index 65fd0e3b6d45..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/rest_base.py +++ /dev/null @@ -1,128 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 FileUploadsServiceTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.shopping.merchant_datasources_v1beta.types import fileuploads - - -class _BaseFileUploadsServiceRestTransport(FileUploadsServiceTransport): - """Base REST backend transport for FileUploadsService. - - 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 _BaseGetFileUpload: - 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': '/datasources/v1beta/{name=accounts/*/dataSources/*/fileUploads/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = fileuploads.GetFileUploadRequest.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(_BaseFileUploadsServiceRestTransport._BaseGetFileUpload._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseFileUploadsServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/types/__init__.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/types/__init__.py deleted file mode 100644 index 8579cd01b10c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/types/__init__.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .datasources import ( - CreateDataSourceRequest, - DataSource, - DeleteDataSourceRequest, - FetchDataSourceRequest, - GetDataSourceRequest, - ListDataSourcesRequest, - ListDataSourcesResponse, - UpdateDataSourceRequest, -) -from .datasourcetypes import ( - DataSourceReference, - LocalInventoryDataSource, - PrimaryProductDataSource, - PromotionDataSource, - RegionalInventoryDataSource, - SupplementalProductDataSource, -) -from .fileinputs import ( - FileInput, -) -from .fileuploads import ( - FileUpload, - GetFileUploadRequest, -) - -__all__ = ( - 'CreateDataSourceRequest', - 'DataSource', - 'DeleteDataSourceRequest', - 'FetchDataSourceRequest', - 'GetDataSourceRequest', - 'ListDataSourcesRequest', - 'ListDataSourcesResponse', - 'UpdateDataSourceRequest', - 'DataSourceReference', - 'LocalInventoryDataSource', - 'PrimaryProductDataSource', - 'PromotionDataSource', - 'RegionalInventoryDataSource', - 'SupplementalProductDataSource', - 'FileInput', - 'FileUpload', - 'GetFileUploadRequest', -) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/types/datasources.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/types/datasources.py deleted file mode 100644 index 59d2cddd3464..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/types/datasources.py +++ /dev/null @@ -1,351 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_datasources_v1beta.types import datasourcetypes -from google.shopping.merchant_datasources_v1beta.types import fileinputs - - -__protobuf__ = proto.module( - package='google.shopping.merchant.datasources.v1beta', - manifest={ - 'DataSource', - 'GetDataSourceRequest', - 'ListDataSourcesRequest', - 'ListDataSourcesResponse', - 'CreateDataSourceRequest', - 'UpdateDataSourceRequest', - 'FetchDataSourceRequest', - 'DeleteDataSourceRequest', - }, -) - - -class DataSource(proto.Message): - r"""The `data - source `__ for - the Merchant Center account. - - 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: - primary_product_data_source (google.shopping.merchant_datasources_v1beta.types.PrimaryProductDataSource): - Required. The `primary data - source `__ - for local and online products. - - This field is a member of `oneof`_ ``Type``. - supplemental_product_data_source (google.shopping.merchant_datasources_v1beta.types.SupplementalProductDataSource): - Required. The `supplemental data - source `__ - for local and online products. - - This field is a member of `oneof`_ ``Type``. - local_inventory_data_source (google.shopping.merchant_datasources_v1beta.types.LocalInventoryDataSource): - Required. The `local - inventory `__ - data source. - - This field is a member of `oneof`_ ``Type``. - regional_inventory_data_source (google.shopping.merchant_datasources_v1beta.types.RegionalInventoryDataSource): - Required. The `regional - inventory `__ - data source. - - This field is a member of `oneof`_ ``Type``. - promotion_data_source (google.shopping.merchant_datasources_v1beta.types.PromotionDataSource): - Required. The - `promotion `__ - data source. - - This field is a member of `oneof`_ ``Type``. - name (str): - Identifier. The name of the data source. Format: - ``{datasource.name=accounts/{account}/dataSources/{datasource}}`` - data_source_id (int): - Output only. The data source id. - display_name (str): - Required. The displayed data source name in - the Merchant Center UI. - input (google.shopping.merchant_datasources_v1beta.types.DataSource.Input): - Output only. Determines the type of input to - the data source. Based on the input some - settings might not work. Only generic data - sources can be created through the API. - file_input (google.shopping.merchant_datasources_v1beta.types.FileInput): - Optional. The field is used only when data is - managed through a file. - """ - class Input(proto.Enum): - r"""Determines the type of input to the data source. Based on the - input some settings might not be supported. - - Values: - INPUT_UNSPECIFIED (0): - Input unspecified. - API (1): - Represents data sources for which the data is - primarily provided through the API. - FILE (2): - Represents data sources for which the data is - primarily provided through file input. Data can - still be provided through the API. - UI (3): - The data source for products added directly - in Merchant Center. - This type of data source can not be created or - updated through this API, only by Merchant - Center UI. - - This type of data source is read only. - AUTOFEED (4): - This is also known as `Automated - feeds `__ - used to automatically build your product data. This type of - data source can be enabled or disabled through the Accounts - bundle. - """ - INPUT_UNSPECIFIED = 0 - API = 1 - FILE = 2 - UI = 3 - AUTOFEED = 4 - - primary_product_data_source: datasourcetypes.PrimaryProductDataSource = proto.Field( - proto.MESSAGE, - number=4, - oneof='Type', - message=datasourcetypes.PrimaryProductDataSource, - ) - supplemental_product_data_source: datasourcetypes.SupplementalProductDataSource = proto.Field( - proto.MESSAGE, - number=5, - oneof='Type', - message=datasourcetypes.SupplementalProductDataSource, - ) - local_inventory_data_source: datasourcetypes.LocalInventoryDataSource = proto.Field( - proto.MESSAGE, - number=6, - oneof='Type', - message=datasourcetypes.LocalInventoryDataSource, - ) - regional_inventory_data_source: datasourcetypes.RegionalInventoryDataSource = proto.Field( - proto.MESSAGE, - number=7, - oneof='Type', - message=datasourcetypes.RegionalInventoryDataSource, - ) - promotion_data_source: datasourcetypes.PromotionDataSource = proto.Field( - proto.MESSAGE, - number=8, - oneof='Type', - message=datasourcetypes.PromotionDataSource, - ) - name: str = proto.Field( - proto.STRING, - number=1, - ) - data_source_id: int = proto.Field( - proto.INT64, - number=2, - ) - display_name: str = proto.Field( - proto.STRING, - number=3, - ) - input: Input = proto.Field( - proto.ENUM, - number=10, - enum=Input, - ) - file_input: fileinputs.FileInput = proto.Field( - proto.MESSAGE, - number=11, - message=fileinputs.FileInput, - ) - - -class GetDataSourceRequest(proto.Message): - r"""Request message for the GetDataSource method. - - Attributes: - name (str): - Required. The name of the data source to retrieve. Format: - ``accounts/{account}/dataSources/{datasource}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListDataSourcesRequest(proto.Message): - r"""Request message for the ListDataSources method. - - Attributes: - parent (str): - Required. The account to list data sources for. Format: - ``accounts/{account}`` - page_size (int): - Optional. The maximum number of data sources - to return. The service may return fewer than - this value. The maximum value is 1000; values - above 1000 will be coerced to 1000. If - unspecified, the maximum number of data sources - will be returned. - page_token (str): - Optional. A page token, received from a previous - ``ListDataSources`` call. Provide this to retrieve the - subsequent page. - - When paginating, all other parameters provided to - ``ListDataSources`` 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 ListDataSourcesResponse(proto.Message): - r"""Response message for the ListDataSources method. - - Attributes: - data_sources (MutableSequence[google.shopping.merchant_datasources_v1beta.types.DataSource]): - The data sources 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 - - data_sources: MutableSequence['DataSource'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='DataSource', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class CreateDataSourceRequest(proto.Message): - r"""Request message for the CreateDataSource method. - - Attributes: - parent (str): - Required. The account where this data source will be - created. Format: ``accounts/{account}`` - data_source (google.shopping.merchant_datasources_v1beta.types.DataSource): - Required. The data source to create. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - data_source: 'DataSource' = proto.Field( - proto.MESSAGE, - number=2, - message='DataSource', - ) - - -class UpdateDataSourceRequest(proto.Message): - r"""Request message for the UpdateDataSource method. - - Attributes: - data_source (google.shopping.merchant_datasources_v1beta.types.DataSource): - Required. The data source resource to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The list of data source fields to be updated. - - Fields specified in the update mask without a value - specified in the body will be deleted from the data source. - - Providing special "*" value for full data source replacement - is not supported. - """ - - data_source: 'DataSource' = proto.Field( - proto.MESSAGE, - number=1, - message='DataSource', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class FetchDataSourceRequest(proto.Message): - r"""Request message for the FetchDataSource method. - - Attributes: - name (str): - Required. The name of the data source resource to fetch. - Format: ``accounts/{account}/dataSources/{datasource}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class DeleteDataSourceRequest(proto.Message): - r"""Request message for the DeleteDataSource method. - - Attributes: - name (str): - Required. The name of the data source to delete. Format: - ``accounts/{account}/dataSources/{datasource}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/types/datasourcetypes.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/types/datasourcetypes.py deleted file mode 100644 index eae022534c7b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/types/datasourcetypes.py +++ /dev/null @@ -1,372 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.datasources.v1beta', - manifest={ - 'PrimaryProductDataSource', - 'SupplementalProductDataSource', - 'LocalInventoryDataSource', - 'RegionalInventoryDataSource', - 'PromotionDataSource', - 'DataSourceReference', - }, -) - - -class PrimaryProductDataSource(proto.Message): - r"""The primary data source for local and online products. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - channel (google.shopping.merchant_datasources_v1beta.types.PrimaryProductDataSource.Channel): - Required. Immutable. Specifies the type of - data source channel. - feed_label (str): - Optional. Immutable. The feed label that is specified on the - data source level. - - Must be less than or equal to 20 uppercase letters (A-Z), - numbers (0-9), and dashes (-). - - See also `migration to feed - labels `__. - - ``feedLabel`` and ``contentLanguage`` must be either both - set or unset for data sources with product content type. - They must be set for data sources with a file input. - - If set, the data source will only accept products matching - this combination. If unset, the data source will accept - products without that restriction. - - This field is a member of `oneof`_ ``_feed_label``. - content_language (str): - Optional. Immutable. The two-letter ISO 639-1 language of - the items in the data source. - - ``feedLabel`` and ``contentLanguage`` must be either both - set or unset. The fields can only be unset for data sources - without file input. - - If set, the data source will only accept products matching - this combination. If unset, the data source will accept - products without that restriction. - - This field is a member of `oneof`_ ``_content_language``. - countries (MutableSequence[str]): - Optional. The countries where the items may be displayed. - Represented as a `CLDR territory - code `__. - default_rule (google.shopping.merchant_datasources_v1beta.types.PrimaryProductDataSource.DefaultRule): - Optional. Default rule management of the data - source. If set, the linked data sources will be - replaced. - """ - class Channel(proto.Enum): - r"""Data Source Channel. - - Channel is used to distinguish between data sources for - different product verticals. - - Values: - CHANNEL_UNSPECIFIED (0): - Not specified. - ONLINE_PRODUCTS (1): - Online product. - LOCAL_PRODUCTS (2): - Local product. - PRODUCTS (3): - Unified data source for both local and online - products. Note: Products management through the - API is not possible for this channel. - """ - CHANNEL_UNSPECIFIED = 0 - ONLINE_PRODUCTS = 1 - LOCAL_PRODUCTS = 2 - PRODUCTS = 3 - - class DefaultRule(proto.Message): - r"""Default rule management of the data source. - - Attributes: - take_from_data_sources (MutableSequence[google.shopping.merchant_datasources_v1beta.types.DataSourceReference]): - Required. The list of data sources linked in the `default - rule `__. - This list is ordered by the default rule priority of joining - the data. It might include none or multiple references to - ``self`` and supplemental data sources. - - The list must not be empty. - - To link the data source to the default rule, you need to add - a new reference to this list (in sequential order). - - To unlink the data source from the default rule, you need to - remove the given reference from this list. To create - attribute rules that are different from the default rule, - see `Set up your attribute - rules `__. - - Changing the order of this list will result in changing the - priority of data sources in the default rule. - - For example, providing the following list: [``1001``, - ``self``] will take attribute values from supplemental data - source ``1001``, and fallback to ``self`` if the attribute - is not set in ``1001``. - """ - - take_from_data_sources: MutableSequence['DataSourceReference'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='DataSourceReference', - ) - - channel: Channel = proto.Field( - proto.ENUM, - number=3, - enum=Channel, - ) - feed_label: str = proto.Field( - proto.STRING, - number=4, - optional=True, - ) - content_language: str = proto.Field( - proto.STRING, - number=5, - optional=True, - ) - countries: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=6, - ) - default_rule: DefaultRule = proto.Field( - proto.MESSAGE, - number=7, - message=DefaultRule, - ) - - -class SupplementalProductDataSource(proto.Message): - r"""The supplemental data source for local and online products. - Supplemental API data sources must not have ``feedLabel`` and - ``contentLanguage`` fields set. You can only use supplemental data - sources to update existing products. For information about creating - a supplemental data source, see `Create a supplemental data source - and link it to the primary data - source `__. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - feed_label (str): - Optional. Immutable. The feed label that is specified on the - data source level. - - Must be less than or equal to 20 uppercase letters (A-Z), - numbers (0-9), and dashes (-). - - See also `migration to feed - labels `__. - - ``feedLabel`` and ``contentLanguage`` must be either both - set or unset for data sources with product content type. - They must be set for data sources with a file input. - - If set, the data source will only accept products matching - this combination. If unset, the data source will accept - produts without that restriction. - - This field is a member of `oneof`_ ``_feed_label``. - content_language (str): - Optional. Immutable. The two-letter ISO 639-1 language of - the items in the data source. - - ``feedLabel`` and ``contentLanguage`` must be either both - set or unset. The fields can only be unset for data sources - without file input. - - If set, the data source will only accept products matching - this combination. If unset, the data source will accept - produts without that restriction. - - This field is a member of `oneof`_ ``_content_language``. - referencing_primary_data_sources (MutableSequence[google.shopping.merchant_datasources_v1beta.types.DataSourceReference]): - Output only. The (unordered and deduplicated) - list of all primary data sources linked to this - data source in either default or custom rules. - Supplemental data source cannot be deleted - before all links are removed. - """ - - feed_label: str = proto.Field( - proto.STRING, - number=4, - optional=True, - ) - content_language: str = proto.Field( - proto.STRING, - number=5, - optional=True, - ) - referencing_primary_data_sources: MutableSequence['DataSourceReference'] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message='DataSourceReference', - ) - - -class LocalInventoryDataSource(proto.Message): - r"""The local inventory data source. - - Attributes: - feed_label (str): - Required. Immutable. The feed label of the offers to which - the local inventory is provided. - - Must be less than or equal to 20 uppercase letters (A-Z), - numbers (0-9), and dashes (-). - - See also `migration to feed - labels `__. - content_language (str): - Required. Immutable. The two-letter ISO 639-1 - language of the items to which the local - inventory is provided. - """ - - feed_label: str = proto.Field( - proto.STRING, - number=4, - ) - content_language: str = proto.Field( - proto.STRING, - number=5, - ) - - -class RegionalInventoryDataSource(proto.Message): - r"""The regional inventory data source. - - Attributes: - feed_label (str): - Required. Immutable. The feed label of the offers to which - the regional inventory is provided. - - Must be less than or equal to 20 uppercase letters (A-Z), - numbers (0-9), and dashes (-). - - See also `migration to feed - labels `__. - content_language (str): - Required. Immutable. The two-letter ISO 639-1 - language of the items to which the regional - inventory is provided. - """ - - feed_label: str = proto.Field( - proto.STRING, - number=4, - ) - content_language: str = proto.Field( - proto.STRING, - number=5, - ) - - -class PromotionDataSource(proto.Message): - r"""The promotion data source. - - Attributes: - target_country (str): - Required. Immutable. The target country used as part of the - unique identifier. Represented as a `CLDR territory - code `__. - - Promotions are only available in selected - `countries `__. - content_language (str): - Required. Immutable. The two-letter ISO 639-1 - language of the items in the data source. - """ - - target_country: str = proto.Field( - proto.STRING, - number=1, - ) - content_language: str = proto.Field( - proto.STRING, - number=2, - ) - - -class DataSourceReference(proto.Message): - r"""Data source reference can be used to manage related data - sources within the data source service. - - 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: - self_ (bool): - Self should be used to reference the primary - data source itself. - - This field is a member of `oneof`_ ``data_source_id``. - primary_data_source_name (str): - Optional. The name of the primary data source. Format: - ``accounts/{account}/dataSources/{datasource}`` - - This field is a member of `oneof`_ ``data_source_id``. - supplemental_data_source_name (str): - Optional. The name of the supplemental data source. Format: - ``accounts/{account}/dataSources/{datasource}`` - - This field is a member of `oneof`_ ``data_source_id``. - """ - - self_: bool = proto.Field( - proto.BOOL, - number=1, - oneof='data_source_id', - ) - primary_data_source_name: str = proto.Field( - proto.STRING, - number=3, - oneof='data_source_id', - ) - supplemental_data_source_name: str = proto.Field( - proto.STRING, - number=2, - oneof='data_source_id', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/types/fileinputs.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/types/fileinputs.py deleted file mode 100644 index 18869a01a769..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/types/fileinputs.py +++ /dev/null @@ -1,201 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 dayofweek_pb2 # type: ignore -from google.type import timeofday_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.shopping.merchant.datasources.v1beta', - manifest={ - 'FileInput', - }, -) - - -class FileInput(proto.Message): - r"""The data specific for file data sources. This field is empty - for other data source inputs. - - Attributes: - fetch_settings (google.shopping.merchant_datasources_v1beta.types.FileInput.FetchSettings): - Optional. Fetch details to deliver the data source. It - contains settings for ``FETCH`` and ``GOOGLE_SHEETS`` file - input types. The required fields vary based on the frequency - of fetching. - file_name (str): - Optional. The file name of the data source. Required for - ``UPLOAD`` file input type. - file_input_type (google.shopping.merchant_datasources_v1beta.types.FileInput.FileInputType): - Output only. The type of file input. - """ - class FileInputType(proto.Enum): - r"""The method of file delivery. - - Values: - FILE_INPUT_TYPE_UNSPECIFIED (0): - File input type unspecified. - UPLOAD (1): - The file is uploaded through SFTP, Google - Cloud Storage or manually in the Merchant - Center. - FETCH (2): - The file is fetched from the configured - [fetch_uri][google.shopping.content.bundles.DataSources.FileInput.FetchSettings.fetch_uri]. - GOOGLE_SHEETS (3): - The file is fetched from Google Sheets specified in the - [fetch_uri][google.shopping.content.bundles.DataSources.FileInput.FetchSettings.fetch_uri]. - """ - FILE_INPUT_TYPE_UNSPECIFIED = 0 - UPLOAD = 1 - FETCH = 2 - GOOGLE_SHEETS = 3 - - class FetchSettings(proto.Message): - r"""Fetch details to deliver the data source. - - Attributes: - enabled (bool): - Optional. Enables or pauses the fetch - schedule. - day_of_month (int): - Optional. The day of the month when the data - source file should be fetched (1-31). This field - can only be set for monthly frequency. - time_of_day (google.type.timeofday_pb2.TimeOfDay): - Optional. The hour of the day when the data - source file should be fetched. Minutes and - seconds are not supported and will be ignored. - day_of_week (google.type.dayofweek_pb2.DayOfWeek): - Optional. The day of the week when the data - source file should be fetched. This field can - only be set for weekly frequency. - time_zone (str): - Optional. `Time zone `__ used for - schedule. UTC by default. For example, - "America/Los_Angeles". - frequency (google.shopping.merchant_datasources_v1beta.types.FileInput.FetchSettings.Frequency): - Required. The frequency describing fetch - schedule. - fetch_uri (str): - Optional. The URL where the data source file - can be fetched. Google Merchant Center supports - automatic scheduled uploads using the HTTP, - HTTPS or SFTP protocols, so the value will need - to be a valid link using one of those three - protocols. Immutable for Google Sheets files. - username (str): - Optional. An optional user name for [fetch - url][google.shopping.content.bundles.DataSources.FileInput.fetch_url]. - Used for `submitting data sources through - SFTP `__. - password (str): - Optional. An optional password for [fetch - url][google.shopping.content.bundles.DataSources.FileInput.fetch_url]. - Used for `submitting data sources through - SFTP `__. - """ - class Frequency(proto.Enum): - r"""The required fields vary based on the frequency of fetching. For a - monthly fetch schedule, [day of - month][google.shopping.content.bundles.DataSources.FileInput.FetchSchedule.day_of_month] - and [hour of - day][google.shopping.content.bundles.DataSources.FileInput.FetchSchedule.time_of_day] - are required. For a weekly fetch schedule, [day of - week][google.shopping.content.bundles.DataSources.FileInput.FetchSchedule.day_of_week] - and [hour of - day][google.shopping.content.bundles.DataSources.FileInput.FetchSchedule.time_of_day] - are required. For a daily fetch schedule, only an [hour of - day][google.shopping.content.bundles.DataSources.FileInput.FetchSchedule.time_of_day] - is required. - - Values: - FREQUENCY_UNSPECIFIED (0): - Frequency unspecified. - FREQUENCY_DAILY (1): - The fetch happens every day. - FREQUENCY_WEEKLY (2): - The fetch happens every week. - FREQUENCY_MONTHLY (3): - The fetch happens every month. - """ - FREQUENCY_UNSPECIFIED = 0 - FREQUENCY_DAILY = 1 - FREQUENCY_WEEKLY = 2 - FREQUENCY_MONTHLY = 3 - - enabled: bool = proto.Field( - proto.BOOL, - number=1, - ) - day_of_month: int = proto.Field( - proto.INT32, - number=2, - ) - time_of_day: timeofday_pb2.TimeOfDay = proto.Field( - proto.MESSAGE, - number=3, - message=timeofday_pb2.TimeOfDay, - ) - day_of_week: dayofweek_pb2.DayOfWeek = proto.Field( - proto.ENUM, - number=4, - enum=dayofweek_pb2.DayOfWeek, - ) - time_zone: str = proto.Field( - proto.STRING, - number=5, - ) - frequency: 'FileInput.FetchSettings.Frequency' = proto.Field( - proto.ENUM, - number=6, - enum='FileInput.FetchSettings.Frequency', - ) - fetch_uri: str = proto.Field( - proto.STRING, - number=7, - ) - username: str = proto.Field( - proto.STRING, - number=8, - ) - password: str = proto.Field( - proto.STRING, - number=9, - ) - - fetch_settings: FetchSettings = proto.Field( - proto.MESSAGE, - number=1, - message=FetchSettings, - ) - file_name: str = proto.Field( - proto.STRING, - number=2, - ) - file_input_type: FileInputType = proto.Field( - proto.ENUM, - number=3, - enum=FileInputType, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/types/fileuploads.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/types/fileuploads.py deleted file mode 100644 index 6488a963fc40..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/types/fileuploads.py +++ /dev/null @@ -1,205 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.shopping.merchant.datasources.v1beta', - manifest={ - 'FileUpload', - 'GetFileUploadRequest', - }, -) - - -class FileUpload(proto.Message): - r"""The file upload of a specific data source, that is, the - result of the retrieval of the data source at a certain - timestamp computed asynchronously when the data source - processing is finished. Only applicable to file data sources. - - Attributes: - name (str): - Identifier. The name of the data source file upload. Format: - ``{datasource.name=accounts/{account}/dataSources/{datasource}/fileUploads/{fileupload}}`` - data_source_id (int): - Output only. The data source id. - processing_state (google.shopping.merchant_datasources_v1beta.types.FileUpload.ProcessingState): - Output only. The processing state of the data - source. - issues (MutableSequence[google.shopping.merchant_datasources_v1beta.types.FileUpload.Issue]): - Output only. The list of issues occurring in - the data source. - items_total (int): - Output only. The number of items in the data - source that were processed. - items_created (int): - Output only. The number of items in the data - source that were created. - items_updated (int): - Output only. The number of items in the data - source that were updated. - upload_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The date at which the file of - the data source was uploaded. - """ - class ProcessingState(proto.Enum): - r"""The processing state of the data source. - - Values: - PROCESSING_STATE_UNSPECIFIED (0): - Processing state unspecified. - FAILED (1): - The data source could not be processed or all - the items had errors. - IN_PROGRESS (2): - The data source is being processed. - SUCCEEDED (3): - The data source was processed successfully, - though some items might have had errors. - """ - PROCESSING_STATE_UNSPECIFIED = 0 - FAILED = 1 - IN_PROGRESS = 2 - SUCCEEDED = 3 - - class Issue(proto.Message): - r"""An error occurring in the data source, like "invalid price". - - Attributes: - title (str): - Output only. The title of the issue, for - example, "Item too big". - description (str): - Output only. The error description, for - example, "Your data source contains items which - have too many attributes, or are too big. These - items will be dropped". - code (str): - Output only. The code of the error, for example, - "validation/invalid_value". Returns "?" if the code is - unknown. - count (int): - Output only. The number of occurrences of the - error in the file upload. - severity (google.shopping.merchant_datasources_v1beta.types.FileUpload.Issue.Severity): - Output only. The severity of the issue. - documentation_uri (str): - Output only. Link to the documentation - explaining the issue in more details, if - available. - """ - class Severity(proto.Enum): - r"""The severity of the issue. - - Values: - SEVERITY_UNSPECIFIED (0): - Severity unspecified. - WARNING (1): - The issue is the warning. - ERROR (2): - The issue is an error. - """ - SEVERITY_UNSPECIFIED = 0 - WARNING = 1 - ERROR = 2 - - title: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - code: str = proto.Field( - proto.STRING, - number=3, - ) - count: int = proto.Field( - proto.INT64, - number=4, - ) - severity: 'FileUpload.Issue.Severity' = proto.Field( - proto.ENUM, - number=5, - enum='FileUpload.Issue.Severity', - ) - documentation_uri: str = proto.Field( - proto.STRING, - number=6, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - data_source_id: int = proto.Field( - proto.INT64, - number=2, - ) - processing_state: ProcessingState = proto.Field( - proto.ENUM, - number=3, - enum=ProcessingState, - ) - issues: MutableSequence[Issue] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=Issue, - ) - items_total: int = proto.Field( - proto.INT64, - number=5, - ) - items_created: int = proto.Field( - proto.INT64, - number=6, - ) - items_updated: int = proto.Field( - proto.INT64, - number=7, - ) - upload_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=8, - message=timestamp_pb2.Timestamp, - ) - - -class GetFileUploadRequest(proto.Message): - r"""Request message for the GetFileUploadRequest method. - - Attributes: - name (str): - Required. The name of the data source file upload to - retrieve. Format: - ``accounts/{account}/dataSources/{datasource}/fileUploads/latest`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/mypy.ini b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/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-datasources/v1beta/noxfile.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/noxfile.py deleted file mode 100644 index cdbea940f142..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/noxfile.py +++ /dev/null @@ -1,280 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", - "3.12", - "3.13", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = 'google-shopping-merchant-datasources' - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.13" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "prerelease_deps", -] - -@nox.session(python=ALL_PYTHON) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def unit(session, protobuf_implementation): - """Run the unit test suite.""" - - 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+") - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") - - # 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") - - session.run( - 'py.test', - '--quiet', - '--cov=google/shopping/merchant_datasources_v1beta/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - -@nox.session(python=ALL_PYTHON[-1]) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def prerelease_deps(session, protobuf_implementation): - """Run the unit test suite against pre-release versions of dependencies.""" - - 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 test environment dependencies - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - - # Install the package without dependencies - session.install('-e', '.', '--no-deps') - - # We test the minimum dependency versions using the minimum Python - # version so the lowest python runtime that we test has a corresponding constraints - # file, located at `testing/constraints--.txt`, which contains all of the - # 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 - ) - ] - - session.install(*constraints_deps) - - prerel_deps = [ - "googleapis-common-protos", - "google-api-core", - "google-auth", - # Exclude grpcio!=1.67.0rc1 which does not support python 3.13 - "grpcio!=1.67.0rc1", - "grpcio-status", - "protobuf", - "proto-plus", - ] - - for dep in prerel_deps: - session.install("--pre", "--no-deps", "--upgrade", dep) - - # Remaining dependencies - other_deps = [ - "requests", - ] - session.install(*other_deps) - - # Print out prerelease package versions - - session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") - session.run("python", "-c", "import google.auth; print(google.auth.__version__)") - session.run("python", "-c", "import grpc; print(grpc.__version__)") - session.run( - "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" - ) - session.run( - "python", "-c", "import proto; print(proto.__version__)" - ) - - session.run( - 'py.test', - '--quiet', - '--cov=google/shopping/merchant_datasources_v1beta/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - - -@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=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 docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==7.0.1", "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=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", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_create_data_source_async.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_create_data_source_async.py deleted file mode 100644 index 3a58c16a898f..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_create_data_source_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateDataSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-datasources - - -# [START merchantapi_v1beta_generated_DataSourcesService_CreateDataSource_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_datasources_v1beta - - -async def sample_create_data_source(): - # Create a client - client = merchant_datasources_v1beta.DataSourcesServiceAsyncClient() - - # Initialize request argument(s) - data_source = merchant_datasources_v1beta.DataSource() - data_source.primary_product_data_source.channel = "PRODUCTS" - data_source.display_name = "display_name_value" - - request = merchant_datasources_v1beta.CreateDataSourceRequest( - parent="parent_value", - data_source=data_source, - ) - - # Make the request - response = await client.create_data_source(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_DataSourcesService_CreateDataSource_async] diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_create_data_source_sync.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_create_data_source_sync.py deleted file mode 100644 index e83b38fa6921..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_create_data_source_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateDataSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-datasources - - -# [START merchantapi_v1beta_generated_DataSourcesService_CreateDataSource_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_datasources_v1beta - - -def sample_create_data_source(): - # Create a client - client = merchant_datasources_v1beta.DataSourcesServiceClient() - - # Initialize request argument(s) - data_source = merchant_datasources_v1beta.DataSource() - data_source.primary_product_data_source.channel = "PRODUCTS" - data_source.display_name = "display_name_value" - - request = merchant_datasources_v1beta.CreateDataSourceRequest( - parent="parent_value", - data_source=data_source, - ) - - # Make the request - response = client.create_data_source(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_DataSourcesService_CreateDataSource_sync] diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_delete_data_source_async.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_delete_data_source_async.py deleted file mode 100644 index 3acdea1ade71..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_delete_data_source_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteDataSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-datasources - - -# [START merchantapi_v1beta_generated_DataSourcesService_DeleteDataSource_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_datasources_v1beta - - -async def sample_delete_data_source(): - # Create a client - client = merchant_datasources_v1beta.DataSourcesServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_datasources_v1beta.DeleteDataSourceRequest( - name="name_value", - ) - - # Make the request - await client.delete_data_source(request=request) - - -# [END merchantapi_v1beta_generated_DataSourcesService_DeleteDataSource_async] diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_delete_data_source_sync.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_delete_data_source_sync.py deleted file mode 100644 index 443f82260fcd..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_delete_data_source_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteDataSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-datasources - - -# [START merchantapi_v1beta_generated_DataSourcesService_DeleteDataSource_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_datasources_v1beta - - -def sample_delete_data_source(): - # Create a client - client = merchant_datasources_v1beta.DataSourcesServiceClient() - - # Initialize request argument(s) - request = merchant_datasources_v1beta.DeleteDataSourceRequest( - name="name_value", - ) - - # Make the request - client.delete_data_source(request=request) - - -# [END merchantapi_v1beta_generated_DataSourcesService_DeleteDataSource_sync] diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_fetch_data_source_async.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_fetch_data_source_async.py deleted file mode 100644 index 14df43d8bd47..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_fetch_data_source_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for FetchDataSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-datasources - - -# [START merchantapi_v1beta_generated_DataSourcesService_FetchDataSource_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_datasources_v1beta - - -async def sample_fetch_data_source(): - # Create a client - client = merchant_datasources_v1beta.DataSourcesServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_datasources_v1beta.FetchDataSourceRequest( - name="name_value", - ) - - # Make the request - await client.fetch_data_source(request=request) - - -# [END merchantapi_v1beta_generated_DataSourcesService_FetchDataSource_async] diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_fetch_data_source_sync.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_fetch_data_source_sync.py deleted file mode 100644 index 644b35470074..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_fetch_data_source_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for FetchDataSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-datasources - - -# [START merchantapi_v1beta_generated_DataSourcesService_FetchDataSource_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_datasources_v1beta - - -def sample_fetch_data_source(): - # Create a client - client = merchant_datasources_v1beta.DataSourcesServiceClient() - - # Initialize request argument(s) - request = merchant_datasources_v1beta.FetchDataSourceRequest( - name="name_value", - ) - - # Make the request - client.fetch_data_source(request=request) - - -# [END merchantapi_v1beta_generated_DataSourcesService_FetchDataSource_sync] diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_get_data_source_async.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_get_data_source_async.py deleted file mode 100644 index 091d08e5fbd5..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_get_data_source_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetDataSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-datasources - - -# [START merchantapi_v1beta_generated_DataSourcesService_GetDataSource_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_datasources_v1beta - - -async def sample_get_data_source(): - # Create a client - client = merchant_datasources_v1beta.DataSourcesServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_datasources_v1beta.GetDataSourceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_data_source(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_DataSourcesService_GetDataSource_async] diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_get_data_source_sync.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_get_data_source_sync.py deleted file mode 100644 index fa9c6c87bc15..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_get_data_source_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetDataSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-datasources - - -# [START merchantapi_v1beta_generated_DataSourcesService_GetDataSource_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_datasources_v1beta - - -def sample_get_data_source(): - # Create a client - client = merchant_datasources_v1beta.DataSourcesServiceClient() - - # Initialize request argument(s) - request = merchant_datasources_v1beta.GetDataSourceRequest( - name="name_value", - ) - - # Make the request - response = client.get_data_source(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_DataSourcesService_GetDataSource_sync] diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_list_data_sources_async.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_list_data_sources_async.py deleted file mode 100644 index 78339cc39b35..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_list_data_sources_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListDataSources -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-datasources - - -# [START merchantapi_v1beta_generated_DataSourcesService_ListDataSources_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_datasources_v1beta - - -async def sample_list_data_sources(): - # Create a client - client = merchant_datasources_v1beta.DataSourcesServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_datasources_v1beta.ListDataSourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_data_sources(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_DataSourcesService_ListDataSources_async] diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_list_data_sources_sync.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_list_data_sources_sync.py deleted file mode 100644 index 46febb24d2d8..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_list_data_sources_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListDataSources -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-datasources - - -# [START merchantapi_v1beta_generated_DataSourcesService_ListDataSources_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_datasources_v1beta - - -def sample_list_data_sources(): - # Create a client - client = merchant_datasources_v1beta.DataSourcesServiceClient() - - # Initialize request argument(s) - request = merchant_datasources_v1beta.ListDataSourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_data_sources(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_DataSourcesService_ListDataSources_sync] diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_update_data_source_async.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_update_data_source_async.py deleted file mode 100644 index a727ef72c51e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_update_data_source_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateDataSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-datasources - - -# [START merchantapi_v1beta_generated_DataSourcesService_UpdateDataSource_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_datasources_v1beta - - -async def sample_update_data_source(): - # Create a client - client = merchant_datasources_v1beta.DataSourcesServiceAsyncClient() - - # Initialize request argument(s) - data_source = merchant_datasources_v1beta.DataSource() - data_source.primary_product_data_source.channel = "PRODUCTS" - data_source.display_name = "display_name_value" - - request = merchant_datasources_v1beta.UpdateDataSourceRequest( - data_source=data_source, - ) - - # Make the request - response = await client.update_data_source(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_DataSourcesService_UpdateDataSource_async] diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_update_data_source_sync.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_update_data_source_sync.py deleted file mode 100644 index 72d7760192c6..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_data_sources_service_update_data_source_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateDataSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-datasources - - -# [START merchantapi_v1beta_generated_DataSourcesService_UpdateDataSource_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_datasources_v1beta - - -def sample_update_data_source(): - # Create a client - client = merchant_datasources_v1beta.DataSourcesServiceClient() - - # Initialize request argument(s) - data_source = merchant_datasources_v1beta.DataSource() - data_source.primary_product_data_source.channel = "PRODUCTS" - data_source.display_name = "display_name_value" - - request = merchant_datasources_v1beta.UpdateDataSourceRequest( - data_source=data_source, - ) - - # Make the request - response = client.update_data_source(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_DataSourcesService_UpdateDataSource_sync] diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_file_uploads_service_get_file_upload_async.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_file_uploads_service_get_file_upload_async.py deleted file mode 100644 index 69eed065c6f5..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_file_uploads_service_get_file_upload_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetFileUpload -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-datasources - - -# [START merchantapi_v1beta_generated_FileUploadsService_GetFileUpload_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_datasources_v1beta - - -async def sample_get_file_upload(): - # Create a client - client = merchant_datasources_v1beta.FileUploadsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_datasources_v1beta.GetFileUploadRequest( - name="name_value", - ) - - # Make the request - response = await client.get_file_upload(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_FileUploadsService_GetFileUpload_async] diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_file_uploads_service_get_file_upload_sync.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_file_uploads_service_get_file_upload_sync.py deleted file mode 100644 index 8ca612c4e3bd..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/merchantapi_v1beta_generated_file_uploads_service_get_file_upload_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetFileUpload -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-datasources - - -# [START merchantapi_v1beta_generated_FileUploadsService_GetFileUpload_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_datasources_v1beta - - -def sample_get_file_upload(): - # Create a client - client = merchant_datasources_v1beta.FileUploadsServiceClient() - - # Initialize request argument(s) - request = merchant_datasources_v1beta.GetFileUploadRequest( - name="name_value", - ) - - # Make the request - response = client.get_file_upload(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_FileUploadsService_GetFileUpload_sync] diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.datasources.v1beta.json b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.datasources.v1beta.json deleted file mode 100644 index 992de0dc6fb0..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.datasources.v1beta.json +++ /dev/null @@ -1,1138 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.shopping.merchant.datasources.v1beta", - "version": "v1beta" - } - ], - "language": "PYTHON", - "name": "google-shopping-merchant-datasources", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceAsyncClient", - "shortName": "DataSourcesServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceAsyncClient.create_data_source", - "method": { - "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService.CreateDataSource", - "service": { - "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", - "shortName": "DataSourcesService" - }, - "shortName": "CreateDataSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_datasources_v1beta.types.CreateDataSourceRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "data_source", - "type": "google.shopping.merchant_datasources_v1beta.types.DataSource" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.shopping.merchant_datasources_v1beta.types.DataSource", - "shortName": "create_data_source" - }, - "description": "Sample for CreateDataSource", - "file": "merchantapi_v1beta_generated_data_sources_service_create_data_source_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_DataSourcesService_CreateDataSource_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_data_sources_service_create_data_source_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceClient", - "shortName": "DataSourcesServiceClient" - }, - "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceClient.create_data_source", - "method": { - "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService.CreateDataSource", - "service": { - "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", - "shortName": "DataSourcesService" - }, - "shortName": "CreateDataSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_datasources_v1beta.types.CreateDataSourceRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "data_source", - "type": "google.shopping.merchant_datasources_v1beta.types.DataSource" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.shopping.merchant_datasources_v1beta.types.DataSource", - "shortName": "create_data_source" - }, - "description": "Sample for CreateDataSource", - "file": "merchantapi_v1beta_generated_data_sources_service_create_data_source_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_DataSourcesService_CreateDataSource_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_data_sources_service_create_data_source_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceAsyncClient", - "shortName": "DataSourcesServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceAsyncClient.delete_data_source", - "method": { - "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService.DeleteDataSource", - "service": { - "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", - "shortName": "DataSourcesService" - }, - "shortName": "DeleteDataSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_datasources_v1beta.types.DeleteDataSourceRequest" - }, - { - "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_data_source" - }, - "description": "Sample for DeleteDataSource", - "file": "merchantapi_v1beta_generated_data_sources_service_delete_data_source_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_DataSourcesService_DeleteDataSource_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_data_sources_service_delete_data_source_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceClient", - "shortName": "DataSourcesServiceClient" - }, - "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceClient.delete_data_source", - "method": { - "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService.DeleteDataSource", - "service": { - "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", - "shortName": "DataSourcesService" - }, - "shortName": "DeleteDataSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_datasources_v1beta.types.DeleteDataSourceRequest" - }, - { - "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_data_source" - }, - "description": "Sample for DeleteDataSource", - "file": "merchantapi_v1beta_generated_data_sources_service_delete_data_source_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_DataSourcesService_DeleteDataSource_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_data_sources_service_delete_data_source_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceAsyncClient", - "shortName": "DataSourcesServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceAsyncClient.fetch_data_source", - "method": { - "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService.FetchDataSource", - "service": { - "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", - "shortName": "DataSourcesService" - }, - "shortName": "FetchDataSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_datasources_v1beta.types.FetchDataSourceRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "shortName": "fetch_data_source" - }, - "description": "Sample for FetchDataSource", - "file": "merchantapi_v1beta_generated_data_sources_service_fetch_data_source_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_DataSourcesService_FetchDataSource_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_data_sources_service_fetch_data_source_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceClient", - "shortName": "DataSourcesServiceClient" - }, - "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceClient.fetch_data_source", - "method": { - "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService.FetchDataSource", - "service": { - "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", - "shortName": "DataSourcesService" - }, - "shortName": "FetchDataSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_datasources_v1beta.types.FetchDataSourceRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "shortName": "fetch_data_source" - }, - "description": "Sample for FetchDataSource", - "file": "merchantapi_v1beta_generated_data_sources_service_fetch_data_source_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_DataSourcesService_FetchDataSource_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_data_sources_service_fetch_data_source_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceAsyncClient", - "shortName": "DataSourcesServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceAsyncClient.get_data_source", - "method": { - "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService.GetDataSource", - "service": { - "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", - "shortName": "DataSourcesService" - }, - "shortName": "GetDataSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_datasources_v1beta.types.GetDataSourceRequest" - }, - { - "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_datasources_v1beta.types.DataSource", - "shortName": "get_data_source" - }, - "description": "Sample for GetDataSource", - "file": "merchantapi_v1beta_generated_data_sources_service_get_data_source_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_DataSourcesService_GetDataSource_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_data_sources_service_get_data_source_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceClient", - "shortName": "DataSourcesServiceClient" - }, - "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceClient.get_data_source", - "method": { - "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService.GetDataSource", - "service": { - "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", - "shortName": "DataSourcesService" - }, - "shortName": "GetDataSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_datasources_v1beta.types.GetDataSourceRequest" - }, - { - "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_datasources_v1beta.types.DataSource", - "shortName": "get_data_source" - }, - "description": "Sample for GetDataSource", - "file": "merchantapi_v1beta_generated_data_sources_service_get_data_source_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_DataSourcesService_GetDataSource_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_data_sources_service_get_data_source_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceAsyncClient", - "shortName": "DataSourcesServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceAsyncClient.list_data_sources", - "method": { - "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService.ListDataSources", - "service": { - "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", - "shortName": "DataSourcesService" - }, - "shortName": "ListDataSources" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_datasources_v1beta.types.ListDataSourcesRequest" - }, - { - "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_datasources_v1beta.services.data_sources_service.pagers.ListDataSourcesAsyncPager", - "shortName": "list_data_sources" - }, - "description": "Sample for ListDataSources", - "file": "merchantapi_v1beta_generated_data_sources_service_list_data_sources_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_DataSourcesService_ListDataSources_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_data_sources_service_list_data_sources_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceClient", - "shortName": "DataSourcesServiceClient" - }, - "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceClient.list_data_sources", - "method": { - "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService.ListDataSources", - "service": { - "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", - "shortName": "DataSourcesService" - }, - "shortName": "ListDataSources" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_datasources_v1beta.types.ListDataSourcesRequest" - }, - { - "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_datasources_v1beta.services.data_sources_service.pagers.ListDataSourcesPager", - "shortName": "list_data_sources" - }, - "description": "Sample for ListDataSources", - "file": "merchantapi_v1beta_generated_data_sources_service_list_data_sources_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_DataSourcesService_ListDataSources_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_data_sources_service_list_data_sources_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceAsyncClient", - "shortName": "DataSourcesServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceAsyncClient.update_data_source", - "method": { - "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService.UpdateDataSource", - "service": { - "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", - "shortName": "DataSourcesService" - }, - "shortName": "UpdateDataSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_datasources_v1beta.types.UpdateDataSourceRequest" - }, - { - "name": "data_source", - "type": "google.shopping.merchant_datasources_v1beta.types.DataSource" - }, - { - "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_datasources_v1beta.types.DataSource", - "shortName": "update_data_source" - }, - "description": "Sample for UpdateDataSource", - "file": "merchantapi_v1beta_generated_data_sources_service_update_data_source_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_DataSourcesService_UpdateDataSource_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_data_sources_service_update_data_source_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceClient", - "shortName": "DataSourcesServiceClient" - }, - "fullName": "google.shopping.merchant_datasources_v1beta.DataSourcesServiceClient.update_data_source", - "method": { - "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService.UpdateDataSource", - "service": { - "fullName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", - "shortName": "DataSourcesService" - }, - "shortName": "UpdateDataSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_datasources_v1beta.types.UpdateDataSourceRequest" - }, - { - "name": "data_source", - "type": "google.shopping.merchant_datasources_v1beta.types.DataSource" - }, - { - "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_datasources_v1beta.types.DataSource", - "shortName": "update_data_source" - }, - "description": "Sample for UpdateDataSource", - "file": "merchantapi_v1beta_generated_data_sources_service_update_data_source_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_DataSourcesService_UpdateDataSource_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_data_sources_service_update_data_source_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_datasources_v1beta.FileUploadsServiceAsyncClient", - "shortName": "FileUploadsServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_datasources_v1beta.FileUploadsServiceAsyncClient.get_file_upload", - "method": { - "fullName": "google.shopping.merchant.datasources.v1beta.FileUploadsService.GetFileUpload", - "service": { - "fullName": "google.shopping.merchant.datasources.v1beta.FileUploadsService", - "shortName": "FileUploadsService" - }, - "shortName": "GetFileUpload" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_datasources_v1beta.types.GetFileUploadRequest" - }, - { - "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_datasources_v1beta.types.FileUpload", - "shortName": "get_file_upload" - }, - "description": "Sample for GetFileUpload", - "file": "merchantapi_v1beta_generated_file_uploads_service_get_file_upload_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_FileUploadsService_GetFileUpload_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_file_uploads_service_get_file_upload_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_datasources_v1beta.FileUploadsServiceClient", - "shortName": "FileUploadsServiceClient" - }, - "fullName": "google.shopping.merchant_datasources_v1beta.FileUploadsServiceClient.get_file_upload", - "method": { - "fullName": "google.shopping.merchant.datasources.v1beta.FileUploadsService.GetFileUpload", - "service": { - "fullName": "google.shopping.merchant.datasources.v1beta.FileUploadsService", - "shortName": "FileUploadsService" - }, - "shortName": "GetFileUpload" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_datasources_v1beta.types.GetFileUploadRequest" - }, - { - "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_datasources_v1beta.types.FileUpload", - "shortName": "get_file_upload" - }, - "description": "Sample for GetFileUpload", - "file": "merchantapi_v1beta_generated_file_uploads_service_get_file_upload_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_FileUploadsService_GetFileUpload_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_file_uploads_service_get_file_upload_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/scripts/fixup_merchant_datasources_v1beta_keywords.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/scripts/fixup_merchant_datasources_v1beta_keywords.py deleted file mode 100644 index 74286e5cd17b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/scripts/fixup_merchant_datasources_v1beta_keywords.py +++ /dev/null @@ -1,182 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_datasourcesCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_data_source': ('parent', 'data_source', ), - 'delete_data_source': ('name', ), - 'fetch_data_source': ('name', ), - 'get_data_source': ('name', ), - 'get_file_upload': ('name', ), - 'list_data_sources': ('parent', 'page_size', 'page_token', ), - 'update_data_source': ('data_source', '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_datasourcesCallTransformer(), -): - """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_datasources 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-datasources/v1beta/setup.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/setup.py deleted file mode 100644 index c13b7221f606..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/setup.py +++ /dev/null @@ -1,98 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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-datasources' - - -description = "Google Shopping Merchant Datasources API client library" - -version = None - -with open(os.path.join(package_root, 'google/shopping/merchant_datasources/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.0dev,!=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.0dev,!=2.24.0,!=2.25.0", - "proto-plus >= 1.22.3, <2.0.0dev", - "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'", - "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", -] -extras = { -} -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-datasources" - -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-datasources/v1beta/testing/constraints-3.10.txt b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.10.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.10.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.11.txt b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.11.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.11.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.12.txt b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.12.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.12.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.13.txt b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.13.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.13.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.7.txt b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.7.txt deleted file mode 100644 index fc812592b0ee..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.7.txt +++ /dev/null @@ -1,10 +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.0dev", -# 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 diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.8.txt b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.8.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.8.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.9.txt b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.9.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/testing/constraints-3.9.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/tests/__init__.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-datasources/v1beta/tests/unit/__init__.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-datasources/v1beta/tests/unit/gapic/__init__.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-datasources/v1beta/tests/unit/gapic/merchant_datasources_v1beta/__init__.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/tests/unit/gapic/merchant_datasources_v1beta/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/tests/unit/gapic/merchant_datasources_v1beta/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-datasources/v1beta/tests/unit/gapic/merchant_datasources_v1beta/test_data_sources_service.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/tests/unit/gapic/merchant_datasources_v1beta/test_data_sources_service.py deleted file mode 100644 index a7e154e0e990..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/tests/unit/gapic/merchant_datasources_v1beta/test_data_sources_service.py +++ /dev/null @@ -1,5650 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_datasources_v1beta.services.data_sources_service import DataSourcesServiceAsyncClient -from google.shopping.merchant_datasources_v1beta.services.data_sources_service import DataSourcesServiceClient -from google.shopping.merchant_datasources_v1beta.services.data_sources_service import pagers -from google.shopping.merchant_datasources_v1beta.services.data_sources_service import transports -from google.shopping.merchant_datasources_v1beta.types import datasources -from google.shopping.merchant_datasources_v1beta.types import datasourcetypes -from google.shopping.merchant_datasources_v1beta.types import fileinputs -from google.type import dayofweek_pb2 # type: ignore -from google.type import timeofday_pb2 # type: ignore -import google.auth - - -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 DataSourcesServiceClient._get_default_mtls_endpoint(None) is None - assert DataSourcesServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert DataSourcesServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert DataSourcesServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert DataSourcesServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert DataSourcesServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert DataSourcesServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert DataSourcesServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert DataSourcesServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - DataSourcesServiceClient._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 DataSourcesServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert DataSourcesServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert DataSourcesServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - DataSourcesServiceClient._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 DataSourcesServiceClient._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 DataSourcesServiceClient._get_client_cert_source(None, False) is None - assert DataSourcesServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert DataSourcesServiceClient._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 DataSourcesServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert DataSourcesServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(DataSourcesServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DataSourcesServiceClient)) -@mock.patch.object(DataSourcesServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DataSourcesServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = DataSourcesServiceClient._DEFAULT_UNIVERSE - default_endpoint = DataSourcesServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = DataSourcesServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert DataSourcesServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert DataSourcesServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == DataSourcesServiceClient.DEFAULT_MTLS_ENDPOINT - assert DataSourcesServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert DataSourcesServiceClient._get_api_endpoint(None, None, default_universe, "always") == DataSourcesServiceClient.DEFAULT_MTLS_ENDPOINT - assert DataSourcesServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == DataSourcesServiceClient.DEFAULT_MTLS_ENDPOINT - assert DataSourcesServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert DataSourcesServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - DataSourcesServiceClient._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 DataSourcesServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert DataSourcesServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert DataSourcesServiceClient._get_universe_domain(None, None) == DataSourcesServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - DataSourcesServiceClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - - -@pytest.mark.parametrize("client_class,transport_name", [ - (DataSourcesServiceClient, "grpc"), - (DataSourcesServiceAsyncClient, "grpc_asyncio"), - (DataSourcesServiceClient, "rest"), -]) -def test_data_sources_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.DataSourcesServiceGrpcTransport, "grpc"), - (transports.DataSourcesServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.DataSourcesServiceRestTransport, "rest"), -]) -def test_data_sources_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", [ - (DataSourcesServiceClient, "grpc"), - (DataSourcesServiceAsyncClient, "grpc_asyncio"), - (DataSourcesServiceClient, "rest"), -]) -def test_data_sources_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_data_sources_service_client_get_transport_class(): - transport = DataSourcesServiceClient.get_transport_class() - available_transports = [ - transports.DataSourcesServiceGrpcTransport, - transports.DataSourcesServiceRestTransport, - ] - assert transport in available_transports - - transport = DataSourcesServiceClient.get_transport_class("grpc") - assert transport == transports.DataSourcesServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DataSourcesServiceClient, transports.DataSourcesServiceGrpcTransport, "grpc"), - (DataSourcesServiceAsyncClient, transports.DataSourcesServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (DataSourcesServiceClient, transports.DataSourcesServiceRestTransport, "rest"), -]) -@mock.patch.object(DataSourcesServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DataSourcesServiceClient)) -@mock.patch.object(DataSourcesServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DataSourcesServiceAsyncClient)) -def test_data_sources_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(DataSourcesServiceClient, '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(DataSourcesServiceClient, '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", [ - (DataSourcesServiceClient, transports.DataSourcesServiceGrpcTransport, "grpc", "true"), - (DataSourcesServiceAsyncClient, transports.DataSourcesServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (DataSourcesServiceClient, transports.DataSourcesServiceGrpcTransport, "grpc", "false"), - (DataSourcesServiceAsyncClient, transports.DataSourcesServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (DataSourcesServiceClient, transports.DataSourcesServiceRestTransport, "rest", "true"), - (DataSourcesServiceClient, transports.DataSourcesServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(DataSourcesServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DataSourcesServiceClient)) -@mock.patch.object(DataSourcesServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DataSourcesServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_data_sources_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", [ - DataSourcesServiceClient, DataSourcesServiceAsyncClient -]) -@mock.patch.object(DataSourcesServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataSourcesServiceClient)) -@mock.patch.object(DataSourcesServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataSourcesServiceAsyncClient)) -def test_data_sources_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", [ - DataSourcesServiceClient, DataSourcesServiceAsyncClient -]) -@mock.patch.object(DataSourcesServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DataSourcesServiceClient)) -@mock.patch.object(DataSourcesServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DataSourcesServiceAsyncClient)) -def test_data_sources_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = DataSourcesServiceClient._DEFAULT_UNIVERSE - default_endpoint = DataSourcesServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = DataSourcesServiceClient._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", [ - (DataSourcesServiceClient, transports.DataSourcesServiceGrpcTransport, "grpc"), - (DataSourcesServiceAsyncClient, transports.DataSourcesServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (DataSourcesServiceClient, transports.DataSourcesServiceRestTransport, "rest"), -]) -def test_data_sources_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", [ - (DataSourcesServiceClient, transports.DataSourcesServiceGrpcTransport, "grpc", grpc_helpers), - (DataSourcesServiceAsyncClient, transports.DataSourcesServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (DataSourcesServiceClient, transports.DataSourcesServiceRestTransport, "rest", None), -]) -def test_data_sources_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_data_sources_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_datasources_v1beta.services.data_sources_service.transports.DataSourcesServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = DataSourcesServiceClient( - 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", [ - (DataSourcesServiceClient, transports.DataSourcesServiceGrpcTransport, "grpc", grpc_helpers), - (DataSourcesServiceAsyncClient, transports.DataSourcesServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_data_sources_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", [ - datasources.GetDataSourceRequest, - dict, -]) -def test_get_data_source(request_type, transport: str = 'grpc'): - client = DataSourcesServiceClient( - 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_data_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datasources.DataSource( - name='name_value', - data_source_id=1462, - display_name='display_name_value', - input=datasources.DataSource.Input.API, - ) - response = client.get_data_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = datasources.GetDataSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, datasources.DataSource) - assert response.name == 'name_value' - assert response.data_source_id == 1462 - assert response.display_name == 'display_name_value' - assert response.input == datasources.DataSource.Input.API - - -def test_get_data_source_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 = DataSourcesServiceClient( - 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 = datasources.GetDataSourceRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_data_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_data_source(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datasources.GetDataSourceRequest( - name='name_value', - ) - -def test_get_data_source_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = DataSourcesServiceClient( - 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_data_source in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_data_source] = mock_rpc - request = {} - client.get_data_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_data_source(request) - - # Establish that a new wrapper 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_data_source_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = DataSourcesServiceAsyncClient( - 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_data_source in client._client._transport._wrapped_methods - - # 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_data_source] = mock_rpc - - request = {} - await client.get_data_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_data_source(request) - - # Establish that a new wrapper 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_data_source_async(transport: str = 'grpc_asyncio', request_type=datasources.GetDataSourceRequest): - client = DataSourcesServiceAsyncClient( - 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_data_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datasources.DataSource( - name='name_value', - data_source_id=1462, - display_name='display_name_value', - input=datasources.DataSource.Input.API, - )) - response = await client.get_data_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = datasources.GetDataSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, datasources.DataSource) - assert response.name == 'name_value' - assert response.data_source_id == 1462 - assert response.display_name == 'display_name_value' - assert response.input == datasources.DataSource.Input.API - - -@pytest.mark.asyncio -async def test_get_data_source_async_from_dict(): - await test_get_data_source_async(request_type=dict) - -def test_get_data_source_field_headers(): - client = DataSourcesServiceClient( - 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 = datasources.GetDataSourceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_data_source), - '__call__') as call: - call.return_value = datasources.DataSource() - client.get_data_source(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_data_source_field_headers_async(): - client = DataSourcesServiceAsyncClient( - 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 = datasources.GetDataSourceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_data_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datasources.DataSource()) - await client.get_data_source(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_data_source_flattened(): - client = DataSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_data_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datasources.DataSource() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_data_source( - 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_data_source_flattened_error(): - client = DataSourcesServiceClient( - 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_data_source( - datasources.GetDataSourceRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_data_source_flattened_async(): - client = DataSourcesServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_data_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datasources.DataSource() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datasources.DataSource()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_data_source( - 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_data_source_flattened_error_async(): - client = DataSourcesServiceAsyncClient( - 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_data_source( - datasources.GetDataSourceRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - datasources.ListDataSourcesRequest, - dict, -]) -def test_list_data_sources(request_type, transport: str = 'grpc'): - client = DataSourcesServiceClient( - 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_data_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datasources.ListDataSourcesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_data_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = datasources.ListDataSourcesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDataSourcesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_data_sources_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 = DataSourcesServiceClient( - 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 = datasources.ListDataSourcesRequest( - 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_data_sources), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_data_sources(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datasources.ListDataSourcesRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_data_sources_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = DataSourcesServiceClient( - 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_data_sources in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_data_sources] = mock_rpc - request = {} - client.list_data_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_data_sources(request) - - # Establish that a new wrapper 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_data_sources_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = DataSourcesServiceAsyncClient( - 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_data_sources in client._client._transport._wrapped_methods - - # 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_data_sources] = mock_rpc - - request = {} - await client.list_data_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_data_sources(request) - - # Establish that a new wrapper 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_data_sources_async(transport: str = 'grpc_asyncio', request_type=datasources.ListDataSourcesRequest): - client = DataSourcesServiceAsyncClient( - 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_data_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datasources.ListDataSourcesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_data_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = datasources.ListDataSourcesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDataSourcesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_data_sources_async_from_dict(): - await test_list_data_sources_async(request_type=dict) - -def test_list_data_sources_field_headers(): - client = DataSourcesServiceClient( - 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 = datasources.ListDataSourcesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_data_sources), - '__call__') as call: - call.return_value = datasources.ListDataSourcesResponse() - client.list_data_sources(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_data_sources_field_headers_async(): - client = DataSourcesServiceAsyncClient( - 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 = datasources.ListDataSourcesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_data_sources), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datasources.ListDataSourcesResponse()) - await client.list_data_sources(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_data_sources_flattened(): - client = DataSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_data_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datasources.ListDataSourcesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_data_sources( - 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_data_sources_flattened_error(): - client = DataSourcesServiceClient( - 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_data_sources( - datasources.ListDataSourcesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_data_sources_flattened_async(): - client = DataSourcesServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_data_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datasources.ListDataSourcesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datasources.ListDataSourcesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_data_sources( - 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_data_sources_flattened_error_async(): - client = DataSourcesServiceAsyncClient( - 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_data_sources( - datasources.ListDataSourcesRequest(), - parent='parent_value', - ) - - -def test_list_data_sources_pager(transport_name: str = "grpc"): - client = DataSourcesServiceClient( - 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_data_sources), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - datasources.ListDataSourcesResponse( - data_sources=[ - datasources.DataSource(), - datasources.DataSource(), - datasources.DataSource(), - ], - next_page_token='abc', - ), - datasources.ListDataSourcesResponse( - data_sources=[], - next_page_token='def', - ), - datasources.ListDataSourcesResponse( - data_sources=[ - datasources.DataSource(), - ], - next_page_token='ghi', - ), - datasources.ListDataSourcesResponse( - data_sources=[ - datasources.DataSource(), - datasources.DataSource(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_data_sources(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, datasources.DataSource) - for i in results) -def test_list_data_sources_pages(transport_name: str = "grpc"): - client = DataSourcesServiceClient( - 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_data_sources), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - datasources.ListDataSourcesResponse( - data_sources=[ - datasources.DataSource(), - datasources.DataSource(), - datasources.DataSource(), - ], - next_page_token='abc', - ), - datasources.ListDataSourcesResponse( - data_sources=[], - next_page_token='def', - ), - datasources.ListDataSourcesResponse( - data_sources=[ - datasources.DataSource(), - ], - next_page_token='ghi', - ), - datasources.ListDataSourcesResponse( - data_sources=[ - datasources.DataSource(), - datasources.DataSource(), - ], - ), - RuntimeError, - ) - pages = list(client.list_data_sources(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_data_sources_async_pager(): - client = DataSourcesServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_data_sources), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - datasources.ListDataSourcesResponse( - data_sources=[ - datasources.DataSource(), - datasources.DataSource(), - datasources.DataSource(), - ], - next_page_token='abc', - ), - datasources.ListDataSourcesResponse( - data_sources=[], - next_page_token='def', - ), - datasources.ListDataSourcesResponse( - data_sources=[ - datasources.DataSource(), - ], - next_page_token='ghi', - ), - datasources.ListDataSourcesResponse( - data_sources=[ - datasources.DataSource(), - datasources.DataSource(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_data_sources(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, datasources.DataSource) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_data_sources_async_pages(): - client = DataSourcesServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_data_sources), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - datasources.ListDataSourcesResponse( - data_sources=[ - datasources.DataSource(), - datasources.DataSource(), - datasources.DataSource(), - ], - next_page_token='abc', - ), - datasources.ListDataSourcesResponse( - data_sources=[], - next_page_token='def', - ), - datasources.ListDataSourcesResponse( - data_sources=[ - datasources.DataSource(), - ], - next_page_token='ghi', - ), - datasources.ListDataSourcesResponse( - data_sources=[ - datasources.DataSource(), - datasources.DataSource(), - ], - ), - 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_data_sources(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", [ - datasources.CreateDataSourceRequest, - dict, -]) -def test_create_data_source(request_type, transport: str = 'grpc'): - client = DataSourcesServiceClient( - 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_data_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datasources.DataSource( - name='name_value', - data_source_id=1462, - display_name='display_name_value', - input=datasources.DataSource.Input.API, - ) - response = client.create_data_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = datasources.CreateDataSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, datasources.DataSource) - assert response.name == 'name_value' - assert response.data_source_id == 1462 - assert response.display_name == 'display_name_value' - assert response.input == datasources.DataSource.Input.API - - -def test_create_data_source_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 = DataSourcesServiceClient( - 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 = datasources.CreateDataSourceRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_data_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_data_source(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datasources.CreateDataSourceRequest( - parent='parent_value', - ) - -def test_create_data_source_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = DataSourcesServiceClient( - 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_data_source in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_data_source] = mock_rpc - request = {} - client.create_data_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_data_source(request) - - # Establish that a new wrapper 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_data_source_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = DataSourcesServiceAsyncClient( - 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_data_source in client._client._transport._wrapped_methods - - # 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_data_source] = mock_rpc - - request = {} - await client.create_data_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.create_data_source(request) - - # Establish that a new wrapper 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_data_source_async(transport: str = 'grpc_asyncio', request_type=datasources.CreateDataSourceRequest): - client = DataSourcesServiceAsyncClient( - 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_data_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datasources.DataSource( - name='name_value', - data_source_id=1462, - display_name='display_name_value', - input=datasources.DataSource.Input.API, - )) - response = await client.create_data_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = datasources.CreateDataSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, datasources.DataSource) - assert response.name == 'name_value' - assert response.data_source_id == 1462 - assert response.display_name == 'display_name_value' - assert response.input == datasources.DataSource.Input.API - - -@pytest.mark.asyncio -async def test_create_data_source_async_from_dict(): - await test_create_data_source_async(request_type=dict) - -def test_create_data_source_field_headers(): - client = DataSourcesServiceClient( - 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 = datasources.CreateDataSourceRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_data_source), - '__call__') as call: - call.return_value = datasources.DataSource() - client.create_data_source(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_data_source_field_headers_async(): - client = DataSourcesServiceAsyncClient( - 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 = datasources.CreateDataSourceRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_data_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datasources.DataSource()) - await client.create_data_source(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_data_source_flattened(): - client = DataSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_data_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datasources.DataSource() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_data_source( - parent='parent_value', - data_source=datasources.DataSource(primary_product_data_source=datasourcetypes.PrimaryProductDataSource(channel=datasourcetypes.PrimaryProductDataSource.Channel.ONLINE_PRODUCTS)), - ) - - # 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].data_source - mock_val = datasources.DataSource(primary_product_data_source=datasourcetypes.PrimaryProductDataSource(channel=datasourcetypes.PrimaryProductDataSource.Channel.ONLINE_PRODUCTS)) - assert arg == mock_val - - -def test_create_data_source_flattened_error(): - client = DataSourcesServiceClient( - 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_data_source( - datasources.CreateDataSourceRequest(), - parent='parent_value', - data_source=datasources.DataSource(primary_product_data_source=datasourcetypes.PrimaryProductDataSource(channel=datasourcetypes.PrimaryProductDataSource.Channel.ONLINE_PRODUCTS)), - ) - -@pytest.mark.asyncio -async def test_create_data_source_flattened_async(): - client = DataSourcesServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_data_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datasources.DataSource() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datasources.DataSource()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_data_source( - parent='parent_value', - data_source=datasources.DataSource(primary_product_data_source=datasourcetypes.PrimaryProductDataSource(channel=datasourcetypes.PrimaryProductDataSource.Channel.ONLINE_PRODUCTS)), - ) - - # 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].data_source - mock_val = datasources.DataSource(primary_product_data_source=datasourcetypes.PrimaryProductDataSource(channel=datasourcetypes.PrimaryProductDataSource.Channel.ONLINE_PRODUCTS)) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_data_source_flattened_error_async(): - client = DataSourcesServiceAsyncClient( - 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_data_source( - datasources.CreateDataSourceRequest(), - parent='parent_value', - data_source=datasources.DataSource(primary_product_data_source=datasourcetypes.PrimaryProductDataSource(channel=datasourcetypes.PrimaryProductDataSource.Channel.ONLINE_PRODUCTS)), - ) - - -@pytest.mark.parametrize("request_type", [ - datasources.UpdateDataSourceRequest, - dict, -]) -def test_update_data_source(request_type, transport: str = 'grpc'): - client = DataSourcesServiceClient( - 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_data_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datasources.DataSource( - name='name_value', - data_source_id=1462, - display_name='display_name_value', - input=datasources.DataSource.Input.API, - ) - response = client.update_data_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = datasources.UpdateDataSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, datasources.DataSource) - assert response.name == 'name_value' - assert response.data_source_id == 1462 - assert response.display_name == 'display_name_value' - assert response.input == datasources.DataSource.Input.API - - -def test_update_data_source_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 = DataSourcesServiceClient( - 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 = datasources.UpdateDataSourceRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_data_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_data_source(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datasources.UpdateDataSourceRequest( - ) - -def test_update_data_source_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = DataSourcesServiceClient( - 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_data_source in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_data_source] = mock_rpc - request = {} - client.update_data_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_data_source(request) - - # Establish that a new wrapper 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_data_source_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = DataSourcesServiceAsyncClient( - 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_data_source in client._client._transport._wrapped_methods - - # 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_data_source] = mock_rpc - - request = {} - await client.update_data_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_data_source(request) - - # Establish that a new wrapper 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_data_source_async(transport: str = 'grpc_asyncio', request_type=datasources.UpdateDataSourceRequest): - client = DataSourcesServiceAsyncClient( - 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_data_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datasources.DataSource( - name='name_value', - data_source_id=1462, - display_name='display_name_value', - input=datasources.DataSource.Input.API, - )) - response = await client.update_data_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = datasources.UpdateDataSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, datasources.DataSource) - assert response.name == 'name_value' - assert response.data_source_id == 1462 - assert response.display_name == 'display_name_value' - assert response.input == datasources.DataSource.Input.API - - -@pytest.mark.asyncio -async def test_update_data_source_async_from_dict(): - await test_update_data_source_async(request_type=dict) - -def test_update_data_source_field_headers(): - client = DataSourcesServiceClient( - 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 = datasources.UpdateDataSourceRequest() - - request.data_source.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_data_source), - '__call__') as call: - call.return_value = datasources.DataSource() - client.update_data_source(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', - 'data_source.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_data_source_field_headers_async(): - client = DataSourcesServiceAsyncClient( - 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 = datasources.UpdateDataSourceRequest() - - request.data_source.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_data_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datasources.DataSource()) - await client.update_data_source(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', - 'data_source.name=name_value', - ) in kw['metadata'] - - -def test_update_data_source_flattened(): - client = DataSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_data_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datasources.DataSource() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_data_source( - data_source=datasources.DataSource(primary_product_data_source=datasourcetypes.PrimaryProductDataSource(channel=datasourcetypes.PrimaryProductDataSource.Channel.ONLINE_PRODUCTS)), - 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].data_source - mock_val = datasources.DataSource(primary_product_data_source=datasourcetypes.PrimaryProductDataSource(channel=datasourcetypes.PrimaryProductDataSource.Channel.ONLINE_PRODUCTS)) - 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_data_source_flattened_error(): - client = DataSourcesServiceClient( - 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_data_source( - datasources.UpdateDataSourceRequest(), - data_source=datasources.DataSource(primary_product_data_source=datasourcetypes.PrimaryProductDataSource(channel=datasourcetypes.PrimaryProductDataSource.Channel.ONLINE_PRODUCTS)), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_data_source_flattened_async(): - client = DataSourcesServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_data_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datasources.DataSource() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datasources.DataSource()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_data_source( - data_source=datasources.DataSource(primary_product_data_source=datasourcetypes.PrimaryProductDataSource(channel=datasourcetypes.PrimaryProductDataSource.Channel.ONLINE_PRODUCTS)), - 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].data_source - mock_val = datasources.DataSource(primary_product_data_source=datasourcetypes.PrimaryProductDataSource(channel=datasourcetypes.PrimaryProductDataSource.Channel.ONLINE_PRODUCTS)) - 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_data_source_flattened_error_async(): - client = DataSourcesServiceAsyncClient( - 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_data_source( - datasources.UpdateDataSourceRequest(), - data_source=datasources.DataSource(primary_product_data_source=datasourcetypes.PrimaryProductDataSource(channel=datasourcetypes.PrimaryProductDataSource.Channel.ONLINE_PRODUCTS)), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - datasources.DeleteDataSourceRequest, - dict, -]) -def test_delete_data_source(request_type, transport: str = 'grpc'): - client = DataSourcesServiceClient( - 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_data_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_data_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = datasources.DeleteDataSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_data_source_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 = DataSourcesServiceClient( - 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 = datasources.DeleteDataSourceRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_data_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_data_source(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datasources.DeleteDataSourceRequest( - name='name_value', - ) - -def test_delete_data_source_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = DataSourcesServiceClient( - 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_data_source in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_data_source] = mock_rpc - request = {} - client.delete_data_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_data_source(request) - - # Establish that a new wrapper 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_data_source_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = DataSourcesServiceAsyncClient( - 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_data_source in client._client._transport._wrapped_methods - - # 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_data_source] = mock_rpc - - request = {} - await client.delete_data_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.delete_data_source(request) - - # Establish that a new wrapper 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_data_source_async(transport: str = 'grpc_asyncio', request_type=datasources.DeleteDataSourceRequest): - client = DataSourcesServiceAsyncClient( - 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_data_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_data_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = datasources.DeleteDataSourceRequest() - 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_data_source_async_from_dict(): - await test_delete_data_source_async(request_type=dict) - -def test_delete_data_source_field_headers(): - client = DataSourcesServiceClient( - 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 = datasources.DeleteDataSourceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_data_source), - '__call__') as call: - call.return_value = None - client.delete_data_source(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_data_source_field_headers_async(): - client = DataSourcesServiceAsyncClient( - 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 = datasources.DeleteDataSourceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_data_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_data_source(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_data_source_flattened(): - client = DataSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_data_source), - '__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_data_source( - 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_data_source_flattened_error(): - client = DataSourcesServiceClient( - 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_data_source( - datasources.DeleteDataSourceRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_data_source_flattened_async(): - client = DataSourcesServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_data_source), - '__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_data_source( - 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_data_source_flattened_error_async(): - client = DataSourcesServiceAsyncClient( - 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_data_source( - datasources.DeleteDataSourceRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - datasources.FetchDataSourceRequest, - dict, -]) -def test_fetch_data_source(request_type, transport: str = 'grpc'): - client = DataSourcesServiceClient( - 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.fetch_data_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.fetch_data_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = datasources.FetchDataSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_fetch_data_source_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 = DataSourcesServiceClient( - 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 = datasources.FetchDataSourceRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.fetch_data_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.fetch_data_source(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datasources.FetchDataSourceRequest( - name='name_value', - ) - -def test_fetch_data_source_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = DataSourcesServiceClient( - 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.fetch_data_source in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.fetch_data_source] = mock_rpc - request = {} - client.fetch_data_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.fetch_data_source(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_fetch_data_source_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = DataSourcesServiceAsyncClient( - 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.fetch_data_source in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.fetch_data_source] = mock_rpc - - request = {} - await client.fetch_data_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.fetch_data_source(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_fetch_data_source_async(transport: str = 'grpc_asyncio', request_type=datasources.FetchDataSourceRequest): - client = DataSourcesServiceAsyncClient( - 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.fetch_data_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.fetch_data_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = datasources.FetchDataSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_fetch_data_source_async_from_dict(): - await test_fetch_data_source_async(request_type=dict) - -def test_fetch_data_source_field_headers(): - client = DataSourcesServiceClient( - 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 = datasources.FetchDataSourceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.fetch_data_source), - '__call__') as call: - call.return_value = None - client.fetch_data_source(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_fetch_data_source_field_headers_async(): - client = DataSourcesServiceAsyncClient( - 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 = datasources.FetchDataSourceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.fetch_data_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.fetch_data_source(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_data_source_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 = DataSourcesServiceClient( - 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_data_source in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_data_source] = mock_rpc - - request = {} - client.get_data_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_data_source(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_data_source_rest_required_fields(request_type=datasources.GetDataSourceRequest): - transport_class = transports.DataSourcesServiceRestTransport - - 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_data_source._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_data_source._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 = DataSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = datasources.DataSource() - # 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 = datasources.DataSource.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_data_source(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_data_source_rest_unset_required_fields(): - transport = transports.DataSourcesServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_data_source._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_data_source_rest_flattened(): - client = DataSourcesServiceClient( - 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 = datasources.DataSource() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/dataSources/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 = datasources.DataSource.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_data_source(**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/datasources/v1beta/{name=accounts/*/dataSources/*}" % client.transport._host, args[1]) - - -def test_get_data_source_rest_flattened_error(transport: str = 'rest'): - client = DataSourcesServiceClient( - 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_data_source( - datasources.GetDataSourceRequest(), - name='name_value', - ) - - -def test_list_data_sources_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 = DataSourcesServiceClient( - 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_data_sources in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_data_sources] = mock_rpc - - request = {} - client.list_data_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_data_sources(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_data_sources_rest_required_fields(request_type=datasources.ListDataSourcesRequest): - transport_class = transports.DataSourcesServiceRestTransport - - 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_data_sources._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_data_sources._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 = DataSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = datasources.ListDataSourcesResponse() - # 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 = datasources.ListDataSourcesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_data_sources(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_data_sources_rest_unset_required_fields(): - transport = transports.DataSourcesServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_data_sources._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_data_sources_rest_flattened(): - client = DataSourcesServiceClient( - 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 = datasources.ListDataSourcesResponse() - - # 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 = datasources.ListDataSourcesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_data_sources(**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/datasources/v1beta/{parent=accounts/*}/dataSources" % client.transport._host, args[1]) - - -def test_list_data_sources_rest_flattened_error(transport: str = 'rest'): - client = DataSourcesServiceClient( - 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_data_sources( - datasources.ListDataSourcesRequest(), - parent='parent_value', - ) - - -def test_list_data_sources_rest_pager(transport: str = 'rest'): - client = DataSourcesServiceClient( - 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 = ( - datasources.ListDataSourcesResponse( - data_sources=[ - datasources.DataSource(), - datasources.DataSource(), - datasources.DataSource(), - ], - next_page_token='abc', - ), - datasources.ListDataSourcesResponse( - data_sources=[], - next_page_token='def', - ), - datasources.ListDataSourcesResponse( - data_sources=[ - datasources.DataSource(), - ], - next_page_token='ghi', - ), - datasources.ListDataSourcesResponse( - data_sources=[ - datasources.DataSource(), - datasources.DataSource(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(datasources.ListDataSourcesResponse.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_data_sources(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, datasources.DataSource) - for i in results) - - pages = list(client.list_data_sources(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_create_data_source_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 = DataSourcesServiceClient( - 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_data_source in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_data_source] = mock_rpc - - request = {} - client.create_data_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_data_source(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_data_source_rest_required_fields(request_type=datasources.CreateDataSourceRequest): - transport_class = transports.DataSourcesServiceRestTransport - - 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_data_source._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_data_source._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 = DataSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = datasources.DataSource() - # 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 = datasources.DataSource.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_data_source(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_data_source_rest_unset_required_fields(): - transport = transports.DataSourcesServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_data_source._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "dataSource", ))) - - -def test_create_data_source_rest_flattened(): - client = DataSourcesServiceClient( - 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 = datasources.DataSource() - - # 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', - data_source=datasources.DataSource(primary_product_data_source=datasourcetypes.PrimaryProductDataSource(channel=datasourcetypes.PrimaryProductDataSource.Channel.ONLINE_PRODUCTS)), - ) - 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 = datasources.DataSource.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_data_source(**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/datasources/v1beta/{parent=accounts/*}/dataSources" % client.transport._host, args[1]) - - -def test_create_data_source_rest_flattened_error(transport: str = 'rest'): - client = DataSourcesServiceClient( - 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_data_source( - datasources.CreateDataSourceRequest(), - parent='parent_value', - data_source=datasources.DataSource(primary_product_data_source=datasourcetypes.PrimaryProductDataSource(channel=datasourcetypes.PrimaryProductDataSource.Channel.ONLINE_PRODUCTS)), - ) - - -def test_update_data_source_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 = DataSourcesServiceClient( - 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_data_source in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_data_source] = mock_rpc - - request = {} - client.update_data_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_data_source(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_data_source_rest_required_fields(request_type=datasources.UpdateDataSourceRequest): - transport_class = transports.DataSourcesServiceRestTransport - - 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_data_source._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_data_source._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 = DataSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = datasources.DataSource() - # 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 = datasources.DataSource.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_data_source(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_data_source_rest_unset_required_fields(): - transport = transports.DataSourcesServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_data_source._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("dataSource", "updateMask", ))) - - -def test_update_data_source_rest_flattened(): - client = DataSourcesServiceClient( - 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 = datasources.DataSource() - - # get arguments that satisfy an http rule for this method - sample_request = {'data_source': {'name': 'accounts/sample1/dataSources/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - data_source=datasources.DataSource(primary_product_data_source=datasourcetypes.PrimaryProductDataSource(channel=datasourcetypes.PrimaryProductDataSource.Channel.ONLINE_PRODUCTS)), - 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 = datasources.DataSource.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_data_source(**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/datasources/v1beta/{data_source.name=accounts/*/dataSources/*}" % client.transport._host, args[1]) - - -def test_update_data_source_rest_flattened_error(transport: str = 'rest'): - client = DataSourcesServiceClient( - 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_data_source( - datasources.UpdateDataSourceRequest(), - data_source=datasources.DataSource(primary_product_data_source=datasourcetypes.PrimaryProductDataSource(channel=datasourcetypes.PrimaryProductDataSource.Channel.ONLINE_PRODUCTS)), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_data_source_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 = DataSourcesServiceClient( - 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_data_source in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_data_source] = mock_rpc - - request = {} - client.delete_data_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_data_source(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_data_source_rest_required_fields(request_type=datasources.DeleteDataSourceRequest): - transport_class = transports.DataSourcesServiceRestTransport - - 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_data_source._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_data_source._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 = DataSourcesServiceClient( - 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_data_source(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_data_source_rest_unset_required_fields(): - transport = transports.DataSourcesServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_data_source._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_delete_data_source_rest_flattened(): - client = DataSourcesServiceClient( - 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/dataSources/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_data_source(**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/datasources/v1beta/{name=accounts/*/dataSources/*}" % client.transport._host, args[1]) - - -def test_delete_data_source_rest_flattened_error(transport: str = 'rest'): - client = DataSourcesServiceClient( - 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_data_source( - datasources.DeleteDataSourceRequest(), - name='name_value', - ) - - -def test_fetch_data_source_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 = DataSourcesServiceClient( - 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.fetch_data_source in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.fetch_data_source] = mock_rpc - - request = {} - client.fetch_data_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.fetch_data_source(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_fetch_data_source_rest_required_fields(request_type=datasources.FetchDataSourceRequest): - transport_class = transports.DataSourcesServiceRestTransport - - 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()).fetch_data_source._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()).fetch_data_source._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 = DataSourcesServiceClient( - 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.fetch_data_source(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_fetch_data_source_rest_unset_required_fields(): - transport = transports.DataSourcesServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.fetch_data_source._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.DataSourcesServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DataSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.DataSourcesServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DataSourcesServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.DataSourcesServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = DataSourcesServiceClient( - 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 = DataSourcesServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.DataSourcesServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DataSourcesServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.DataSourcesServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = DataSourcesServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.DataSourcesServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.DataSourcesServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.DataSourcesServiceGrpcTransport, - transports.DataSourcesServiceGrpcAsyncIOTransport, - transports.DataSourcesServiceRestTransport, -]) -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 = DataSourcesServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = DataSourcesServiceClient( - 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_data_source_empty_call_grpc(): - client = DataSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_data_source), - '__call__') as call: - call.return_value = datasources.DataSource() - client.get_data_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = datasources.GetDataSourceRequest() - - assert args[0] == request_msg - - -# This 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_data_sources_empty_call_grpc(): - client = DataSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_data_sources), - '__call__') as call: - call.return_value = datasources.ListDataSourcesResponse() - client.list_data_sources(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = datasources.ListDataSourcesRequest() - - assert args[0] == request_msg - - -# This 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_data_source_empty_call_grpc(): - client = DataSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_data_source), - '__call__') as call: - call.return_value = datasources.DataSource() - client.create_data_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = datasources.CreateDataSourceRequest() - - assert args[0] == request_msg - - -# This 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_data_source_empty_call_grpc(): - client = DataSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_data_source), - '__call__') as call: - call.return_value = datasources.DataSource() - client.update_data_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = datasources.UpdateDataSourceRequest() - - assert args[0] == request_msg - - -# This 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_data_source_empty_call_grpc(): - client = DataSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_data_source), - '__call__') as call: - call.return_value = None - client.delete_data_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = datasources.DeleteDataSourceRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_fetch_data_source_empty_call_grpc(): - client = DataSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.fetch_data_source), - '__call__') as call: - call.return_value = None - client.fetch_data_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = datasources.FetchDataSourceRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = DataSourcesServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = DataSourcesServiceAsyncClient( - 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_data_source_empty_call_grpc_asyncio(): - client = DataSourcesServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_data_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datasources.DataSource( - name='name_value', - data_source_id=1462, - display_name='display_name_value', - input=datasources.DataSource.Input.API, - )) - await client.get_data_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = datasources.GetDataSourceRequest() - - assert args[0] == request_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_data_sources_empty_call_grpc_asyncio(): - client = DataSourcesServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_data_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datasources.ListDataSourcesResponse( - next_page_token='next_page_token_value', - )) - await client.list_data_sources(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = datasources.ListDataSourcesRequest() - - assert args[0] == request_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_data_source_empty_call_grpc_asyncio(): - client = DataSourcesServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_data_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datasources.DataSource( - name='name_value', - data_source_id=1462, - display_name='display_name_value', - input=datasources.DataSource.Input.API, - )) - await client.create_data_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = datasources.CreateDataSourceRequest() - - assert args[0] == request_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_data_source_empty_call_grpc_asyncio(): - client = DataSourcesServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_data_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datasources.DataSource( - name='name_value', - data_source_id=1462, - display_name='display_name_value', - input=datasources.DataSource.Input.API, - )) - await client.update_data_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = datasources.UpdateDataSourceRequest() - - assert args[0] == request_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_data_source_empty_call_grpc_asyncio(): - client = DataSourcesServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_data_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_data_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = datasources.DeleteDataSourceRequest() - - assert args[0] == request_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_fetch_data_source_empty_call_grpc_asyncio(): - client = DataSourcesServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.fetch_data_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.fetch_data_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = datasources.FetchDataSourceRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = DataSourcesServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_get_data_source_rest_bad_request(request_type=datasources.GetDataSourceRequest): - client = DataSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/dataSources/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_data_source(request) - - -@pytest.mark.parametrize("request_type", [ - datasources.GetDataSourceRequest, - dict, -]) -def test_get_data_source_rest_call_success(request_type): - client = DataSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/dataSources/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 = datasources.DataSource( - name='name_value', - data_source_id=1462, - display_name='display_name_value', - input=datasources.DataSource.Input.API, - ) - - # 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 = datasources.DataSource.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_data_source(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, datasources.DataSource) - assert response.name == 'name_value' - assert response.data_source_id == 1462 - assert response.display_name == 'display_name_value' - assert response.input == datasources.DataSource.Input.API - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_data_source_rest_interceptors(null_interceptor): - transport = transports.DataSourcesServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DataSourcesServiceRestInterceptor(), - ) - client = DataSourcesServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DataSourcesServiceRestInterceptor, "post_get_data_source") as post, \ - mock.patch.object(transports.DataSourcesServiceRestInterceptor, "pre_get_data_source") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = datasources.GetDataSourceRequest.pb(datasources.GetDataSourceRequest()) - 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 = datasources.DataSource.to_json(datasources.DataSource()) - req.return_value.content = return_value - - request = datasources.GetDataSourceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = datasources.DataSource() - - client.get_data_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_data_sources_rest_bad_request(request_type=datasources.ListDataSourcesRequest): - client = DataSourcesServiceClient( - 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_data_sources(request) - - -@pytest.mark.parametrize("request_type", [ - datasources.ListDataSourcesRequest, - dict, -]) -def test_list_data_sources_rest_call_success(request_type): - client = DataSourcesServiceClient( - 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 = datasources.ListDataSourcesResponse( - 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 = datasources.ListDataSourcesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_data_sources(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDataSourcesPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_data_sources_rest_interceptors(null_interceptor): - transport = transports.DataSourcesServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DataSourcesServiceRestInterceptor(), - ) - client = DataSourcesServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DataSourcesServiceRestInterceptor, "post_list_data_sources") as post, \ - mock.patch.object(transports.DataSourcesServiceRestInterceptor, "pre_list_data_sources") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = datasources.ListDataSourcesRequest.pb(datasources.ListDataSourcesRequest()) - 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 = datasources.ListDataSourcesResponse.to_json(datasources.ListDataSourcesResponse()) - req.return_value.content = return_value - - request = datasources.ListDataSourcesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = datasources.ListDataSourcesResponse() - - client.list_data_sources(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_data_source_rest_bad_request(request_type=datasources.CreateDataSourceRequest): - client = DataSourcesServiceClient( - 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_data_source(request) - - -@pytest.mark.parametrize("request_type", [ - datasources.CreateDataSourceRequest, - dict, -]) -def test_create_data_source_rest_call_success(request_type): - client = DataSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} - request_init["data_source"] = {'primary_product_data_source': {'channel': 1, 'feed_label': 'feed_label_value', 'content_language': 'content_language_value', 'countries': ['countries_value1', 'countries_value2'], 'default_rule': {'take_from_data_sources': [{'self_': True, 'primary_data_source_name': 'primary_data_source_name_value', 'supplemental_data_source_name': 'supplemental_data_source_name_value'}]}}, 'supplemental_product_data_source': {'feed_label': 'feed_label_value', 'content_language': 'content_language_value', 'referencing_primary_data_sources': {}}, 'local_inventory_data_source': {'feed_label': 'feed_label_value', 'content_language': 'content_language_value'}, 'regional_inventory_data_source': {'feed_label': 'feed_label_value', 'content_language': 'content_language_value'}, 'promotion_data_source': {'target_country': 'target_country_value', 'content_language': 'content_language_value'}, 'name': 'name_value', 'data_source_id': 1462, 'display_name': 'display_name_value', 'input': 1, 'file_input': {'fetch_settings': {'enabled': True, 'day_of_month': 1271, 'time_of_day': {'hours': 561, 'minutes': 773, 'seconds': 751, 'nanos': 543}, 'day_of_week': 1, 'time_zone': 'time_zone_value', 'frequency': 1, 'fetch_uri': 'fetch_uri_value', 'username': 'username_value', 'password': 'password_value'}, 'file_name': 'file_name_value', 'file_input_type': 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 = datasources.CreateDataSourceRequest.meta.fields["data_source"] - - 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["data_source"].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["data_source"][field])): - del request_init["data_source"][field][i][subfield] - else: - del request_init["data_source"][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 = datasources.DataSource( - name='name_value', - data_source_id=1462, - display_name='display_name_value', - input=datasources.DataSource.Input.API, - ) - - # 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 = datasources.DataSource.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_data_source(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, datasources.DataSource) - assert response.name == 'name_value' - assert response.data_source_id == 1462 - assert response.display_name == 'display_name_value' - assert response.input == datasources.DataSource.Input.API - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_data_source_rest_interceptors(null_interceptor): - transport = transports.DataSourcesServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DataSourcesServiceRestInterceptor(), - ) - client = DataSourcesServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DataSourcesServiceRestInterceptor, "post_create_data_source") as post, \ - mock.patch.object(transports.DataSourcesServiceRestInterceptor, "pre_create_data_source") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = datasources.CreateDataSourceRequest.pb(datasources.CreateDataSourceRequest()) - 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 = datasources.DataSource.to_json(datasources.DataSource()) - req.return_value.content = return_value - - request = datasources.CreateDataSourceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = datasources.DataSource() - - client.create_data_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_data_source_rest_bad_request(request_type=datasources.UpdateDataSourceRequest): - client = DataSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'data_source': {'name': 'accounts/sample1/dataSources/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_data_source(request) - - -@pytest.mark.parametrize("request_type", [ - datasources.UpdateDataSourceRequest, - dict, -]) -def test_update_data_source_rest_call_success(request_type): - client = DataSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'data_source': {'name': 'accounts/sample1/dataSources/sample2'}} - request_init["data_source"] = {'primary_product_data_source': {'channel': 1, 'feed_label': 'feed_label_value', 'content_language': 'content_language_value', 'countries': ['countries_value1', 'countries_value2'], 'default_rule': {'take_from_data_sources': [{'self_': True, 'primary_data_source_name': 'primary_data_source_name_value', 'supplemental_data_source_name': 'supplemental_data_source_name_value'}]}}, 'supplemental_product_data_source': {'feed_label': 'feed_label_value', 'content_language': 'content_language_value', 'referencing_primary_data_sources': {}}, 'local_inventory_data_source': {'feed_label': 'feed_label_value', 'content_language': 'content_language_value'}, 'regional_inventory_data_source': {'feed_label': 'feed_label_value', 'content_language': 'content_language_value'}, 'promotion_data_source': {'target_country': 'target_country_value', 'content_language': 'content_language_value'}, 'name': 'accounts/sample1/dataSources/sample2', 'data_source_id': 1462, 'display_name': 'display_name_value', 'input': 1, 'file_input': {'fetch_settings': {'enabled': True, 'day_of_month': 1271, 'time_of_day': {'hours': 561, 'minutes': 773, 'seconds': 751, 'nanos': 543}, 'day_of_week': 1, 'time_zone': 'time_zone_value', 'frequency': 1, 'fetch_uri': 'fetch_uri_value', 'username': 'username_value', 'password': 'password_value'}, 'file_name': 'file_name_value', 'file_input_type': 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 = datasources.UpdateDataSourceRequest.meta.fields["data_source"] - - 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["data_source"].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["data_source"][field])): - del request_init["data_source"][field][i][subfield] - else: - del request_init["data_source"][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 = datasources.DataSource( - name='name_value', - data_source_id=1462, - display_name='display_name_value', - input=datasources.DataSource.Input.API, - ) - - # 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 = datasources.DataSource.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_data_source(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, datasources.DataSource) - assert response.name == 'name_value' - assert response.data_source_id == 1462 - assert response.display_name == 'display_name_value' - assert response.input == datasources.DataSource.Input.API - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_data_source_rest_interceptors(null_interceptor): - transport = transports.DataSourcesServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DataSourcesServiceRestInterceptor(), - ) - client = DataSourcesServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DataSourcesServiceRestInterceptor, "post_update_data_source") as post, \ - mock.patch.object(transports.DataSourcesServiceRestInterceptor, "pre_update_data_source") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = datasources.UpdateDataSourceRequest.pb(datasources.UpdateDataSourceRequest()) - 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 = datasources.DataSource.to_json(datasources.DataSource()) - req.return_value.content = return_value - - request = datasources.UpdateDataSourceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = datasources.DataSource() - - client.update_data_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_data_source_rest_bad_request(request_type=datasources.DeleteDataSourceRequest): - client = DataSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/dataSources/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_data_source(request) - - -@pytest.mark.parametrize("request_type", [ - datasources.DeleteDataSourceRequest, - dict, -]) -def test_delete_data_source_rest_call_success(request_type): - client = DataSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/dataSources/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_data_source(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_data_source_rest_interceptors(null_interceptor): - transport = transports.DataSourcesServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DataSourcesServiceRestInterceptor(), - ) - client = DataSourcesServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DataSourcesServiceRestInterceptor, "pre_delete_data_source") as pre: - pre.assert_not_called() - pb_message = datasources.DeleteDataSourceRequest.pb(datasources.DeleteDataSourceRequest()) - 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 = datasources.DeleteDataSourceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_data_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_fetch_data_source_rest_bad_request(request_type=datasources.FetchDataSourceRequest): - client = DataSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/dataSources/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.fetch_data_source(request) - - -@pytest.mark.parametrize("request_type", [ - datasources.FetchDataSourceRequest, - dict, -]) -def test_fetch_data_source_rest_call_success(request_type): - client = DataSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/dataSources/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.fetch_data_source(request) - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_fetch_data_source_rest_interceptors(null_interceptor): - transport = transports.DataSourcesServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DataSourcesServiceRestInterceptor(), - ) - client = DataSourcesServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DataSourcesServiceRestInterceptor, "pre_fetch_data_source") as pre: - pre.assert_not_called() - pb_message = datasources.FetchDataSourceRequest.pb(datasources.FetchDataSourceRequest()) - 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 = datasources.FetchDataSourceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.fetch_data_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - -def test_initialize_client_w_rest(): - client = DataSourcesServiceClient( - 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_data_source_empty_call_rest(): - client = DataSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_data_source), - '__call__') as call: - client.get_data_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = datasources.GetDataSourceRequest() - - assert args[0] == request_msg - - -# This 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_data_sources_empty_call_rest(): - client = DataSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_data_sources), - '__call__') as call: - client.list_data_sources(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = datasources.ListDataSourcesRequest() - - assert args[0] == request_msg - - -# This 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_data_source_empty_call_rest(): - client = DataSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_data_source), - '__call__') as call: - client.create_data_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = datasources.CreateDataSourceRequest() - - assert args[0] == request_msg - - -# This 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_data_source_empty_call_rest(): - client = DataSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_data_source), - '__call__') as call: - client.update_data_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = datasources.UpdateDataSourceRequest() - - assert args[0] == request_msg - - -# This 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_data_source_empty_call_rest(): - client = DataSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_data_source), - '__call__') as call: - client.delete_data_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = datasources.DeleteDataSourceRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_fetch_data_source_empty_call_rest(): - client = DataSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.fetch_data_source), - '__call__') as call: - client.fetch_data_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = datasources.FetchDataSourceRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = DataSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.DataSourcesServiceGrpcTransport, - ) - -def test_data_sources_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.DataSourcesServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_data_sources_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.shopping.merchant_datasources_v1beta.services.data_sources_service.transports.DataSourcesServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.DataSourcesServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'get_data_source', - 'list_data_sources', - 'create_data_source', - 'update_data_source', - 'delete_data_source', - 'fetch_data_source', - ) - 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_data_sources_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_datasources_v1beta.services.data_sources_service.transports.DataSourcesServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DataSourcesServiceTransport( - 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_data_sources_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_datasources_v1beta.services.data_sources_service.transports.DataSourcesServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DataSourcesServiceTransport() - adc.assert_called_once() - - -def test_data_sources_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) - DataSourcesServiceClient() - 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.DataSourcesServiceGrpcTransport, - transports.DataSourcesServiceGrpcAsyncIOTransport, - ], -) -def test_data_sources_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.DataSourcesServiceGrpcTransport, - transports.DataSourcesServiceGrpcAsyncIOTransport, - transports.DataSourcesServiceRestTransport, - ], -) -def test_data_sources_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.DataSourcesServiceGrpcTransport, grpc_helpers), - (transports.DataSourcesServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_data_sources_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.DataSourcesServiceGrpcTransport, transports.DataSourcesServiceGrpcAsyncIOTransport]) -def test_data_sources_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_data_sources_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.DataSourcesServiceRestTransport ( - 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_data_sources_service_host_no_port(transport_name): - client = DataSourcesServiceClient( - 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_data_sources_service_host_with_port(transport_name): - client = DataSourcesServiceClient( - 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_data_sources_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = DataSourcesServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = DataSourcesServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.get_data_source._session - session2 = client2.transport.get_data_source._session - assert session1 != session2 - session1 = client1.transport.list_data_sources._session - session2 = client2.transport.list_data_sources._session - assert session1 != session2 - session1 = client1.transport.create_data_source._session - session2 = client2.transport.create_data_source._session - assert session1 != session2 - session1 = client1.transport.update_data_source._session - session2 = client2.transport.update_data_source._session - assert session1 != session2 - session1 = client1.transport.delete_data_source._session - session2 = client2.transport.delete_data_source._session - assert session1 != session2 - session1 = client1.transport.fetch_data_source._session - session2 = client2.transport.fetch_data_source._session - assert session1 != session2 -def test_data_sources_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.DataSourcesServiceGrpcTransport( - 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_data_sources_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.DataSourcesServiceGrpcAsyncIOTransport( - 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.DataSourcesServiceGrpcTransport, transports.DataSourcesServiceGrpcAsyncIOTransport]) -def test_data_sources_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.DataSourcesServiceGrpcTransport, transports.DataSourcesServiceGrpcAsyncIOTransport]) -def test_data_sources_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_data_source_path(): - account = "squid" - datasource = "clam" - expected = "accounts/{account}/dataSources/{datasource}".format(account=account, datasource=datasource, ) - actual = DataSourcesServiceClient.data_source_path(account, datasource) - assert expected == actual - - -def test_parse_data_source_path(): - expected = { - "account": "whelk", - "datasource": "octopus", - } - path = DataSourcesServiceClient.data_source_path(**expected) - - # Check that the path construction is reversible. - actual = DataSourcesServiceClient.parse_data_source_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = DataSourcesServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = DataSourcesServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = DataSourcesServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = DataSourcesServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = DataSourcesServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = DataSourcesServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = DataSourcesServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = DataSourcesServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = DataSourcesServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = DataSourcesServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = DataSourcesServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = DataSourcesServiceClient.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 = DataSourcesServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = DataSourcesServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = DataSourcesServiceClient.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.DataSourcesServiceTransport, '_prep_wrapped_messages') as prep: - client = DataSourcesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.DataSourcesServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = DataSourcesServiceClient.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 = DataSourcesServiceClient( - 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 = DataSourcesServiceAsyncClient( - 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 = DataSourcesServiceClient( - 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 = DataSourcesServiceClient( - 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", [ - (DataSourcesServiceClient, transports.DataSourcesServiceGrpcTransport), - (DataSourcesServiceAsyncClient, transports.DataSourcesServiceGrpcAsyncIOTransport), -]) -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-datasources/v1beta/tests/unit/gapic/merchant_datasources_v1beta/test_file_uploads_service.py b/owl-bot-staging/google-shopping-merchant-datasources/v1beta/tests/unit/gapic/merchant_datasources_v1beta/test_file_uploads_service.py deleted file mode 100644 index ecc075be50ee..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/tests/unit/gapic/merchant_datasources_v1beta/test_file_uploads_service.py +++ /dev/null @@ -1,2121 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable, AsyncIterable -from google.protobuf import json_format -import json -import math -import pytest -from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -try: - from google.auth.aio import credentials as ga_credentials_async - HAS_GOOGLE_AUTH_AIO = True -except ImportError: # pragma: NO COVER - HAS_GOOGLE_AUTH_AIO = False - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.oauth2 import service_account -from google.protobuf import timestamp_pb2 # type: ignore -from google.shopping.merchant_datasources_v1beta.services.file_uploads_service import FileUploadsServiceAsyncClient -from google.shopping.merchant_datasources_v1beta.services.file_uploads_service import FileUploadsServiceClient -from google.shopping.merchant_datasources_v1beta.services.file_uploads_service import transports -from google.shopping.merchant_datasources_v1beta.types import fileuploads -import google.auth - - -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 FileUploadsServiceClient._get_default_mtls_endpoint(None) is None - assert FileUploadsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert FileUploadsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert FileUploadsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert FileUploadsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert FileUploadsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert FileUploadsServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert FileUploadsServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert FileUploadsServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - FileUploadsServiceClient._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 FileUploadsServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert FileUploadsServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert FileUploadsServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - FileUploadsServiceClient._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 FileUploadsServiceClient._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 FileUploadsServiceClient._get_client_cert_source(None, False) is None - assert FileUploadsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert FileUploadsServiceClient._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 FileUploadsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert FileUploadsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(FileUploadsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(FileUploadsServiceClient)) -@mock.patch.object(FileUploadsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(FileUploadsServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = FileUploadsServiceClient._DEFAULT_UNIVERSE - default_endpoint = FileUploadsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = FileUploadsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert FileUploadsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert FileUploadsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == FileUploadsServiceClient.DEFAULT_MTLS_ENDPOINT - assert FileUploadsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert FileUploadsServiceClient._get_api_endpoint(None, None, default_universe, "always") == FileUploadsServiceClient.DEFAULT_MTLS_ENDPOINT - assert FileUploadsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == FileUploadsServiceClient.DEFAULT_MTLS_ENDPOINT - assert FileUploadsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert FileUploadsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - FileUploadsServiceClient._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 FileUploadsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert FileUploadsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert FileUploadsServiceClient._get_universe_domain(None, None) == FileUploadsServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - FileUploadsServiceClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - - -@pytest.mark.parametrize("client_class,transport_name", [ - (FileUploadsServiceClient, "grpc"), - (FileUploadsServiceAsyncClient, "grpc_asyncio"), - (FileUploadsServiceClient, "rest"), -]) -def test_file_uploads_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.FileUploadsServiceGrpcTransport, "grpc"), - (transports.FileUploadsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.FileUploadsServiceRestTransport, "rest"), -]) -def test_file_uploads_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", [ - (FileUploadsServiceClient, "grpc"), - (FileUploadsServiceAsyncClient, "grpc_asyncio"), - (FileUploadsServiceClient, "rest"), -]) -def test_file_uploads_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_file_uploads_service_client_get_transport_class(): - transport = FileUploadsServiceClient.get_transport_class() - available_transports = [ - transports.FileUploadsServiceGrpcTransport, - transports.FileUploadsServiceRestTransport, - ] - assert transport in available_transports - - transport = FileUploadsServiceClient.get_transport_class("grpc") - assert transport == transports.FileUploadsServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (FileUploadsServiceClient, transports.FileUploadsServiceGrpcTransport, "grpc"), - (FileUploadsServiceAsyncClient, transports.FileUploadsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (FileUploadsServiceClient, transports.FileUploadsServiceRestTransport, "rest"), -]) -@mock.patch.object(FileUploadsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(FileUploadsServiceClient)) -@mock.patch.object(FileUploadsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(FileUploadsServiceAsyncClient)) -def test_file_uploads_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(FileUploadsServiceClient, '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(FileUploadsServiceClient, '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", [ - (FileUploadsServiceClient, transports.FileUploadsServiceGrpcTransport, "grpc", "true"), - (FileUploadsServiceAsyncClient, transports.FileUploadsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (FileUploadsServiceClient, transports.FileUploadsServiceGrpcTransport, "grpc", "false"), - (FileUploadsServiceAsyncClient, transports.FileUploadsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (FileUploadsServiceClient, transports.FileUploadsServiceRestTransport, "rest", "true"), - (FileUploadsServiceClient, transports.FileUploadsServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(FileUploadsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(FileUploadsServiceClient)) -@mock.patch.object(FileUploadsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(FileUploadsServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_file_uploads_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", [ - FileUploadsServiceClient, FileUploadsServiceAsyncClient -]) -@mock.patch.object(FileUploadsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FileUploadsServiceClient)) -@mock.patch.object(FileUploadsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FileUploadsServiceAsyncClient)) -def test_file_uploads_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", [ - FileUploadsServiceClient, FileUploadsServiceAsyncClient -]) -@mock.patch.object(FileUploadsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(FileUploadsServiceClient)) -@mock.patch.object(FileUploadsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(FileUploadsServiceAsyncClient)) -def test_file_uploads_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = FileUploadsServiceClient._DEFAULT_UNIVERSE - default_endpoint = FileUploadsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = FileUploadsServiceClient._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", [ - (FileUploadsServiceClient, transports.FileUploadsServiceGrpcTransport, "grpc"), - (FileUploadsServiceAsyncClient, transports.FileUploadsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (FileUploadsServiceClient, transports.FileUploadsServiceRestTransport, "rest"), -]) -def test_file_uploads_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", [ - (FileUploadsServiceClient, transports.FileUploadsServiceGrpcTransport, "grpc", grpc_helpers), - (FileUploadsServiceAsyncClient, transports.FileUploadsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (FileUploadsServiceClient, transports.FileUploadsServiceRestTransport, "rest", None), -]) -def test_file_uploads_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_file_uploads_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_datasources_v1beta.services.file_uploads_service.transports.FileUploadsServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = FileUploadsServiceClient( - 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", [ - (FileUploadsServiceClient, transports.FileUploadsServiceGrpcTransport, "grpc", grpc_helpers), - (FileUploadsServiceAsyncClient, transports.FileUploadsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_file_uploads_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", [ - fileuploads.GetFileUploadRequest, - dict, -]) -def test_get_file_upload(request_type, transport: str = 'grpc'): - client = FileUploadsServiceClient( - 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_file_upload), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = fileuploads.FileUpload( - name='name_value', - data_source_id=1462, - processing_state=fileuploads.FileUpload.ProcessingState.FAILED, - items_total=1189, - items_created=1369, - items_updated=1384, - ) - response = client.get_file_upload(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = fileuploads.GetFileUploadRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, fileuploads.FileUpload) - assert response.name == 'name_value' - assert response.data_source_id == 1462 - assert response.processing_state == fileuploads.FileUpload.ProcessingState.FAILED - assert response.items_total == 1189 - assert response.items_created == 1369 - assert response.items_updated == 1384 - - -def test_get_file_upload_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 = FileUploadsServiceClient( - 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 = fileuploads.GetFileUploadRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_file_upload), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_file_upload(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == fileuploads.GetFileUploadRequest( - name='name_value', - ) - -def test_get_file_upload_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = FileUploadsServiceClient( - 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_file_upload in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_file_upload] = mock_rpc - request = {} - client.get_file_upload(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_file_upload(request) - - # Establish that a new wrapper 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_file_upload_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = FileUploadsServiceAsyncClient( - 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_file_upload in client._client._transport._wrapped_methods - - # 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_file_upload] = mock_rpc - - request = {} - await client.get_file_upload(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_file_upload(request) - - # Establish that a new wrapper 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_file_upload_async(transport: str = 'grpc_asyncio', request_type=fileuploads.GetFileUploadRequest): - client = FileUploadsServiceAsyncClient( - 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_file_upload), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(fileuploads.FileUpload( - name='name_value', - data_source_id=1462, - processing_state=fileuploads.FileUpload.ProcessingState.FAILED, - items_total=1189, - items_created=1369, - items_updated=1384, - )) - response = await client.get_file_upload(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = fileuploads.GetFileUploadRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, fileuploads.FileUpload) - assert response.name == 'name_value' - assert response.data_source_id == 1462 - assert response.processing_state == fileuploads.FileUpload.ProcessingState.FAILED - assert response.items_total == 1189 - assert response.items_created == 1369 - assert response.items_updated == 1384 - - -@pytest.mark.asyncio -async def test_get_file_upload_async_from_dict(): - await test_get_file_upload_async(request_type=dict) - -def test_get_file_upload_field_headers(): - client = FileUploadsServiceClient( - 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 = fileuploads.GetFileUploadRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_file_upload), - '__call__') as call: - call.return_value = fileuploads.FileUpload() - client.get_file_upload(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_file_upload_field_headers_async(): - client = FileUploadsServiceAsyncClient( - 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 = fileuploads.GetFileUploadRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_file_upload), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(fileuploads.FileUpload()) - await client.get_file_upload(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_file_upload_flattened(): - client = FileUploadsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_file_upload), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = fileuploads.FileUpload() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_file_upload( - 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_file_upload_flattened_error(): - client = FileUploadsServiceClient( - 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_file_upload( - fileuploads.GetFileUploadRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_file_upload_flattened_async(): - client = FileUploadsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_file_upload), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = fileuploads.FileUpload() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(fileuploads.FileUpload()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_file_upload( - 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_file_upload_flattened_error_async(): - client = FileUploadsServiceAsyncClient( - 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_file_upload( - fileuploads.GetFileUploadRequest(), - name='name_value', - ) - - -def test_get_file_upload_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 = FileUploadsServiceClient( - 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_file_upload in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_file_upload] = mock_rpc - - request = {} - client.get_file_upload(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_file_upload(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_file_upload_rest_required_fields(request_type=fileuploads.GetFileUploadRequest): - transport_class = transports.FileUploadsServiceRestTransport - - 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_file_upload._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_file_upload._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 = FileUploadsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = fileuploads.FileUpload() - # 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 = fileuploads.FileUpload.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_file_upload(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_file_upload_rest_unset_required_fields(): - transport = transports.FileUploadsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_file_upload._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_file_upload_rest_flattened(): - client = FileUploadsServiceClient( - 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 = fileuploads.FileUpload() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/dataSources/sample2/fileUploads/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 = fileuploads.FileUpload.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_file_upload(**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/datasources/v1beta/{name=accounts/*/dataSources/*/fileUploads/*}" % client.transport._host, args[1]) - - -def test_get_file_upload_rest_flattened_error(transport: str = 'rest'): - client = FileUploadsServiceClient( - 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_file_upload( - fileuploads.GetFileUploadRequest(), - name='name_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.FileUploadsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = FileUploadsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.FileUploadsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = FileUploadsServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.FileUploadsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = FileUploadsServiceClient( - 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 = FileUploadsServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.FileUploadsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = FileUploadsServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.FileUploadsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = FileUploadsServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.FileUploadsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.FileUploadsServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.FileUploadsServiceGrpcTransport, - transports.FileUploadsServiceGrpcAsyncIOTransport, - transports.FileUploadsServiceRestTransport, -]) -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 = FileUploadsServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = FileUploadsServiceClient( - 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_file_upload_empty_call_grpc(): - client = FileUploadsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_file_upload), - '__call__') as call: - call.return_value = fileuploads.FileUpload() - client.get_file_upload(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = fileuploads.GetFileUploadRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = FileUploadsServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = FileUploadsServiceAsyncClient( - 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_file_upload_empty_call_grpc_asyncio(): - client = FileUploadsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_file_upload), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(fileuploads.FileUpload( - name='name_value', - data_source_id=1462, - processing_state=fileuploads.FileUpload.ProcessingState.FAILED, - items_total=1189, - items_created=1369, - items_updated=1384, - )) - await client.get_file_upload(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = fileuploads.GetFileUploadRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = FileUploadsServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_get_file_upload_rest_bad_request(request_type=fileuploads.GetFileUploadRequest): - client = FileUploadsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/dataSources/sample2/fileUploads/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.get_file_upload(request) - - -@pytest.mark.parametrize("request_type", [ - fileuploads.GetFileUploadRequest, - dict, -]) -def test_get_file_upload_rest_call_success(request_type): - client = FileUploadsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/dataSources/sample2/fileUploads/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 = fileuploads.FileUpload( - name='name_value', - data_source_id=1462, - processing_state=fileuploads.FileUpload.ProcessingState.FAILED, - items_total=1189, - items_created=1369, - items_updated=1384, - ) - - # 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 = fileuploads.FileUpload.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_file_upload(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, fileuploads.FileUpload) - assert response.name == 'name_value' - assert response.data_source_id == 1462 - assert response.processing_state == fileuploads.FileUpload.ProcessingState.FAILED - assert response.items_total == 1189 - assert response.items_created == 1369 - assert response.items_updated == 1384 - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_file_upload_rest_interceptors(null_interceptor): - transport = transports.FileUploadsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.FileUploadsServiceRestInterceptor(), - ) - client = FileUploadsServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.FileUploadsServiceRestInterceptor, "post_get_file_upload") as post, \ - mock.patch.object(transports.FileUploadsServiceRestInterceptor, "pre_get_file_upload") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = fileuploads.GetFileUploadRequest.pb(fileuploads.GetFileUploadRequest()) - 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 = fileuploads.FileUpload.to_json(fileuploads.FileUpload()) - req.return_value.content = return_value - - request = fileuploads.GetFileUploadRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = fileuploads.FileUpload() - - client.get_file_upload(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - -def test_initialize_client_w_rest(): - client = FileUploadsServiceClient( - 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_file_upload_empty_call_rest(): - client = FileUploadsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_file_upload), - '__call__') as call: - client.get_file_upload(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = fileuploads.GetFileUploadRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = FileUploadsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.FileUploadsServiceGrpcTransport, - ) - -def test_file_uploads_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.FileUploadsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_file_uploads_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.shopping.merchant_datasources_v1beta.services.file_uploads_service.transports.FileUploadsServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.FileUploadsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'get_file_upload', - ) - 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_file_uploads_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_datasources_v1beta.services.file_uploads_service.transports.FileUploadsServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.FileUploadsServiceTransport( - 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_file_uploads_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_datasources_v1beta.services.file_uploads_service.transports.FileUploadsServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.FileUploadsServiceTransport() - adc.assert_called_once() - - -def test_file_uploads_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) - FileUploadsServiceClient() - 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.FileUploadsServiceGrpcTransport, - transports.FileUploadsServiceGrpcAsyncIOTransport, - ], -) -def test_file_uploads_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.FileUploadsServiceGrpcTransport, - transports.FileUploadsServiceGrpcAsyncIOTransport, - transports.FileUploadsServiceRestTransport, - ], -) -def test_file_uploads_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.FileUploadsServiceGrpcTransport, grpc_helpers), - (transports.FileUploadsServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_file_uploads_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.FileUploadsServiceGrpcTransport, transports.FileUploadsServiceGrpcAsyncIOTransport]) -def test_file_uploads_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_file_uploads_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.FileUploadsServiceRestTransport ( - 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_file_uploads_service_host_no_port(transport_name): - client = FileUploadsServiceClient( - 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_file_uploads_service_host_with_port(transport_name): - client = FileUploadsServiceClient( - 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_file_uploads_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = FileUploadsServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = FileUploadsServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.get_file_upload._session - session2 = client2.transport.get_file_upload._session - assert session1 != session2 -def test_file_uploads_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.FileUploadsServiceGrpcTransport( - 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_file_uploads_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.FileUploadsServiceGrpcAsyncIOTransport( - 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.FileUploadsServiceGrpcTransport, transports.FileUploadsServiceGrpcAsyncIOTransport]) -def test_file_uploads_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.FileUploadsServiceGrpcTransport, transports.FileUploadsServiceGrpcAsyncIOTransport]) -def test_file_uploads_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_file_upload_path(): - account = "squid" - datasource = "clam" - fileupload = "whelk" - expected = "accounts/{account}/dataSources/{datasource}/fileUploads/{fileupload}".format(account=account, datasource=datasource, fileupload=fileupload, ) - actual = FileUploadsServiceClient.file_upload_path(account, datasource, fileupload) - assert expected == actual - - -def test_parse_file_upload_path(): - expected = { - "account": "octopus", - "datasource": "oyster", - "fileupload": "nudibranch", - } - path = FileUploadsServiceClient.file_upload_path(**expected) - - # Check that the path construction is reversible. - actual = FileUploadsServiceClient.parse_file_upload_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = FileUploadsServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = FileUploadsServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = FileUploadsServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = FileUploadsServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = FileUploadsServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = FileUploadsServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = FileUploadsServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = FileUploadsServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = FileUploadsServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = FileUploadsServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = FileUploadsServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = FileUploadsServiceClient.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 = FileUploadsServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = FileUploadsServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = FileUploadsServiceClient.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.FileUploadsServiceTransport, '_prep_wrapped_messages') as prep: - client = FileUploadsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.FileUploadsServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = FileUploadsServiceClient.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 = FileUploadsServiceClient( - 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 = FileUploadsServiceAsyncClient( - 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 = FileUploadsServiceClient( - 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 = FileUploadsServiceClient( - 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", [ - (FileUploadsServiceClient, transports.FileUploadsServiceGrpcTransport), - (FileUploadsServiceAsyncClient, transports.FileUploadsServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/.coveragerc b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/.coveragerc deleted file mode 100644 index b3835b541d48..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/shopping/merchant_inventories/__init__.py - google/shopping/merchant_inventories/gapic_version.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/.flake8 b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/MANIFEST.in b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/MANIFEST.in deleted file mode 100644 index 516108ef9a06..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/shopping/merchant_inventories *.py -recursive-include google/shopping/merchant_inventories_v1beta *.py diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/README.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/README.rst deleted file mode 100644 index 0f012bb0c42e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Shopping Merchant Inventories API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Shopping Merchant Inventories API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/_static/custom.css b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/_static/custom.css +++ /dev/null @@ -1,3 +0,0 @@ -dl.field-list > dt { - min-width: 100px -} diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/conf.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/conf.py deleted file mode 100644 index f71381a47a11..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-shopping-merchant-inventories documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# 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.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The root toctree document. -root_doc = "index" - -# General information about the project. -project = u"google-shopping-merchant-inventories" -copyright = u"2023, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# 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 = 'en' - -# 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"] - -# 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 Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-shopping-merchant-inventories-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - root_doc, - "google-shopping-merchant-inventories.tex", - u"google-shopping-merchant-inventories Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - root_doc, - "google-shopping-merchant-inventories", - u"Google Shopping Merchant Inventories Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - root_doc, - "google-shopping-merchant-inventories", - u"google-shopping-merchant-inventories Documentation", - author, - "google-shopping-merchant-inventories", - "GAPIC library for Google Shopping Merchant Inventories API", - "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": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/index.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/index.rst deleted file mode 100644 index 98ba4d129c6d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - merchant_inventories_v1beta/services_ - merchant_inventories_v1beta/types_ diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/local_inventory_service.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/local_inventory_service.rst deleted file mode 100644 index d8e5a2b05114..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/local_inventory_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -LocalInventoryService ---------------------------------------- - -.. automodule:: google.shopping.merchant_inventories_v1beta.services.local_inventory_service - :members: - :inherited-members: - -.. automodule:: google.shopping.merchant_inventories_v1beta.services.local_inventory_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/regional_inventory_service.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/regional_inventory_service.rst deleted file mode 100644 index d23b466a2398..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/regional_inventory_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -RegionalInventoryService ------------------------------------------- - -.. automodule:: google.shopping.merchant_inventories_v1beta.services.regional_inventory_service - :members: - :inherited-members: - -.. automodule:: google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/services_.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/services_.rst deleted file mode 100644 index 7bdd71de9b95..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/services_.rst +++ /dev/null @@ -1,7 +0,0 @@ -Services for Google Shopping Merchant Inventories v1beta API -============================================================ -.. toctree:: - :maxdepth: 2 - - local_inventory_service - regional_inventory_service diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/types_.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/types_.rst deleted file mode 100644 index 2bd5b6e3cb01..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Shopping Merchant Inventories v1beta API -========================================================= - -.. automodule:: google.shopping.merchant_inventories_v1beta.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/__init__.py deleted file mode 100644 index 642093b6a92f..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/__init__.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.shopping.merchant_inventories import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.shopping.merchant_inventories_v1beta.services.local_inventory_service.client import LocalInventoryServiceClient -from google.shopping.merchant_inventories_v1beta.services.local_inventory_service.async_client import LocalInventoryServiceAsyncClient -from google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.client import RegionalInventoryServiceClient -from google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.async_client import RegionalInventoryServiceAsyncClient - -from google.shopping.merchant_inventories_v1beta.types.localinventory import DeleteLocalInventoryRequest -from google.shopping.merchant_inventories_v1beta.types.localinventory import InsertLocalInventoryRequest -from google.shopping.merchant_inventories_v1beta.types.localinventory import ListLocalInventoriesRequest -from google.shopping.merchant_inventories_v1beta.types.localinventory import ListLocalInventoriesResponse -from google.shopping.merchant_inventories_v1beta.types.localinventory import LocalInventory -from google.shopping.merchant_inventories_v1beta.types.regionalinventory import DeleteRegionalInventoryRequest -from google.shopping.merchant_inventories_v1beta.types.regionalinventory import InsertRegionalInventoryRequest -from google.shopping.merchant_inventories_v1beta.types.regionalinventory import ListRegionalInventoriesRequest -from google.shopping.merchant_inventories_v1beta.types.regionalinventory import ListRegionalInventoriesResponse -from google.shopping.merchant_inventories_v1beta.types.regionalinventory import RegionalInventory - -__all__ = ('LocalInventoryServiceClient', - 'LocalInventoryServiceAsyncClient', - 'RegionalInventoryServiceClient', - 'RegionalInventoryServiceAsyncClient', - 'DeleteLocalInventoryRequest', - 'InsertLocalInventoryRequest', - 'ListLocalInventoriesRequest', - 'ListLocalInventoriesResponse', - 'LocalInventory', - 'DeleteRegionalInventoryRequest', - 'InsertRegionalInventoryRequest', - 'ListRegionalInventoriesRequest', - 'ListRegionalInventoriesResponse', - 'RegionalInventory', -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/gapic_version.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/py.typed b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/py.typed deleted file mode 100644 index 993f00a7e3c3..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-shopping-merchant-inventories package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/__init__.py deleted file mode 100644 index 3e759824ccdf..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/__init__.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.shopping.merchant_inventories_v1beta import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.local_inventory_service import LocalInventoryServiceClient -from .services.local_inventory_service import LocalInventoryServiceAsyncClient -from .services.regional_inventory_service import RegionalInventoryServiceClient -from .services.regional_inventory_service import RegionalInventoryServiceAsyncClient - -from .types.localinventory import DeleteLocalInventoryRequest -from .types.localinventory import InsertLocalInventoryRequest -from .types.localinventory import ListLocalInventoriesRequest -from .types.localinventory import ListLocalInventoriesResponse -from .types.localinventory import LocalInventory -from .types.regionalinventory import DeleteRegionalInventoryRequest -from .types.regionalinventory import InsertRegionalInventoryRequest -from .types.regionalinventory import ListRegionalInventoriesRequest -from .types.regionalinventory import ListRegionalInventoriesResponse -from .types.regionalinventory import RegionalInventory - -__all__ = ( - 'LocalInventoryServiceAsyncClient', - 'RegionalInventoryServiceAsyncClient', -'DeleteLocalInventoryRequest', -'DeleteRegionalInventoryRequest', -'InsertLocalInventoryRequest', -'InsertRegionalInventoryRequest', -'ListLocalInventoriesRequest', -'ListLocalInventoriesResponse', -'ListRegionalInventoriesRequest', -'ListRegionalInventoriesResponse', -'LocalInventory', -'LocalInventoryServiceClient', -'RegionalInventory', -'RegionalInventoryServiceClient', -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/gapic_metadata.json b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/gapic_metadata.json deleted file mode 100644 index dca053900305..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/gapic_metadata.json +++ /dev/null @@ -1,137 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.shopping.merchant_inventories_v1beta", - "protoPackage": "google.shopping.merchant.inventories.v1beta", - "schema": "1.0", - "services": { - "LocalInventoryService": { - "clients": { - "grpc": { - "libraryClient": "LocalInventoryServiceClient", - "rpcs": { - "DeleteLocalInventory": { - "methods": [ - "delete_local_inventory" - ] - }, - "InsertLocalInventory": { - "methods": [ - "insert_local_inventory" - ] - }, - "ListLocalInventories": { - "methods": [ - "list_local_inventories" - ] - } - } - }, - "grpc-async": { - "libraryClient": "LocalInventoryServiceAsyncClient", - "rpcs": { - "DeleteLocalInventory": { - "methods": [ - "delete_local_inventory" - ] - }, - "InsertLocalInventory": { - "methods": [ - "insert_local_inventory" - ] - }, - "ListLocalInventories": { - "methods": [ - "list_local_inventories" - ] - } - } - }, - "rest": { - "libraryClient": "LocalInventoryServiceClient", - "rpcs": { - "DeleteLocalInventory": { - "methods": [ - "delete_local_inventory" - ] - }, - "InsertLocalInventory": { - "methods": [ - "insert_local_inventory" - ] - }, - "ListLocalInventories": { - "methods": [ - "list_local_inventories" - ] - } - } - } - } - }, - "RegionalInventoryService": { - "clients": { - "grpc": { - "libraryClient": "RegionalInventoryServiceClient", - "rpcs": { - "DeleteRegionalInventory": { - "methods": [ - "delete_regional_inventory" - ] - }, - "InsertRegionalInventory": { - "methods": [ - "insert_regional_inventory" - ] - }, - "ListRegionalInventories": { - "methods": [ - "list_regional_inventories" - ] - } - } - }, - "grpc-async": { - "libraryClient": "RegionalInventoryServiceAsyncClient", - "rpcs": { - "DeleteRegionalInventory": { - "methods": [ - "delete_regional_inventory" - ] - }, - "InsertRegionalInventory": { - "methods": [ - "insert_regional_inventory" - ] - }, - "ListRegionalInventories": { - "methods": [ - "list_regional_inventories" - ] - } - } - }, - "rest": { - "libraryClient": "RegionalInventoryServiceClient", - "rpcs": { - "DeleteRegionalInventory": { - "methods": [ - "delete_regional_inventory" - ] - }, - "InsertRegionalInventory": { - "methods": [ - "insert_regional_inventory" - ] - }, - "ListRegionalInventories": { - "methods": [ - "list_regional_inventories" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/gapic_version.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/py.typed b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/py.typed deleted file mode 100644 index 993f00a7e3c3..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-shopping-merchant-inventories package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/__init__.py deleted file mode 100644 index fc4e82d6ff35..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import LocalInventoryServiceClient -from .async_client import LocalInventoryServiceAsyncClient - -__all__ = ( - 'LocalInventoryServiceClient', - 'LocalInventoryServiceAsyncClient', -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/async_client.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/async_client.py deleted file mode 100644 index ffcc5efbf5e0..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/async_client.py +++ /dev/null @@ -1,585 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import logging as std_logging -from collections import OrderedDict -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.shopping.merchant_inventories_v1beta import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - - -try: - OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore - -from google.shopping.merchant_inventories_v1beta.services.local_inventory_service import pagers -from google.shopping.merchant_inventories_v1beta.types import localinventory -from google.shopping.type.types import types -from google.type import interval_pb2 # type: ignore -from .transports.base import LocalInventoryServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import LocalInventoryServiceGrpcAsyncIOTransport -from .client import LocalInventoryServiceClient - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - -class LocalInventoryServiceAsyncClient: - """Service to manage local inventory for products""" - - _client: LocalInventoryServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = LocalInventoryServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = LocalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = LocalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = LocalInventoryServiceClient._DEFAULT_UNIVERSE - - local_inventory_path = staticmethod(LocalInventoryServiceClient.local_inventory_path) - parse_local_inventory_path = staticmethod(LocalInventoryServiceClient.parse_local_inventory_path) - common_billing_account_path = staticmethod(LocalInventoryServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(LocalInventoryServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(LocalInventoryServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(LocalInventoryServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(LocalInventoryServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(LocalInventoryServiceClient.parse_common_organization_path) - common_project_path = staticmethod(LocalInventoryServiceClient.common_project_path) - parse_common_project_path = staticmethod(LocalInventoryServiceClient.parse_common_project_path) - common_location_path = staticmethod(LocalInventoryServiceClient.common_location_path) - parse_common_location_path = staticmethod(LocalInventoryServiceClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - LocalInventoryServiceAsyncClient: The constructed client. - """ - return LocalInventoryServiceClient.from_service_account_info.__func__(LocalInventoryServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - LocalInventoryServiceAsyncClient: The constructed client. - """ - return LocalInventoryServiceClient.from_service_account_file.__func__(LocalInventoryServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return LocalInventoryServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> LocalInventoryServiceTransport: - """Returns the transport used by the client instance. - - Returns: - LocalInventoryServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._client._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used - by the client instance. - """ - return self._client._universe_domain - - get_transport_class = LocalInventoryServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, LocalInventoryServiceTransport, Callable[..., LocalInventoryServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the local inventory service async client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,LocalInventoryServiceTransport,Callable[..., LocalInventoryServiceTransport]]]): - The transport to use, or a Callable that constructs and returns a new transport to use. - If a Callable is given, it will be called with the same set of initialization - arguments as used in the LocalInventoryServiceTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = LocalInventoryServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER - _LOGGER.debug( - "Created client `google.shopping.merchant.inventories_v1beta.LocalInventoryServiceAsyncClient`.", - extra = { - "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", - "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), - "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._client._transport, "_credentials") else { - "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", - "credentialsType": None, - } - ) - - async def list_local_inventories(self, - request: Optional[Union[localinventory.ListLocalInventoriesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListLocalInventoriesAsyncPager: - r"""Lists the ``LocalInventory`` resources for the given product in - your merchant account. The response might contain fewer items - than specified by ``pageSize``. If ``pageToken`` was returned in - previous request, it can be used to obtain additional results. - - ``LocalInventory`` resources are listed per product for a given - account. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_inventories_v1beta - - async def sample_list_local_inventories(): - # Create a client - client = merchant_inventories_v1beta.LocalInventoryServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_inventories_v1beta.ListLocalInventoriesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_local_inventories(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesRequest, dict]]): - The request object. Request message for the ``ListLocalInventories`` method. - parent (:class:`str`): - Required. The ``name`` of the parent product to list - local inventories for. Format: - ``accounts/{account}/products/{product}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.shopping.merchant_inventories_v1beta.services.local_inventory_service.pagers.ListLocalInventoriesAsyncPager: - Response message for the ListLocalInventories method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, localinventory.ListLocalInventoriesRequest): - request = localinventory.ListLocalInventoriesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_local_inventories] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListLocalInventoriesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def insert_local_inventory(self, - request: Optional[Union[localinventory.InsertLocalInventoryRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> localinventory.LocalInventory: - r"""Inserts a ``LocalInventory`` resource to a product in your - merchant account. - - Replaces the full ``LocalInventory`` resource if an entry with - the same - [``storeCode``][google.shopping.merchant.inventories.v1beta.LocalInventory.store_code] - already exists for the product. - - It might take up to 30 minutes for the new or updated - ``LocalInventory`` resource to appear in products. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_inventories_v1beta - - async def sample_insert_local_inventory(): - # Create a client - client = merchant_inventories_v1beta.LocalInventoryServiceAsyncClient() - - # Initialize request argument(s) - local_inventory = merchant_inventories_v1beta.LocalInventory() - local_inventory.store_code = "store_code_value" - - request = merchant_inventories_v1beta.InsertLocalInventoryRequest( - parent="parent_value", - local_inventory=local_inventory, - ) - - # Make the request - response = await client.insert_local_inventory(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_inventories_v1beta.types.InsertLocalInventoryRequest, dict]]): - The request object. Request message for the ``InsertLocalInventory`` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.shopping.merchant_inventories_v1beta.types.LocalInventory: - Local inventory information for the product. Represents in-store information - for a specific product at the store specified by - [storeCode][google.shopping.merchant.inventories.v1beta.LocalInventory.store_code]. - For a list of all accepted attribute values, see the - [local product inventory data - specification](\ https://support.google.com/merchants/answer/3061342). - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, localinventory.InsertLocalInventoryRequest): - request = localinventory.InsertLocalInventoryRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.insert_local_inventory] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_local_inventory(self, - request: Optional[Union[localinventory.DeleteLocalInventoryRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: - r"""Deletes the specified ``LocalInventory`` from the given product - in your merchant account. It might take a up to an hour for the - ``LocalInventory`` to be deleted from the specific product. Once - you have received a successful delete response, wait for that - period before attempting a delete again. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_inventories_v1beta - - async def sample_delete_local_inventory(): - # Create a client - client = merchant_inventories_v1beta.LocalInventoryServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_inventories_v1beta.DeleteLocalInventoryRequest( - name="name_value", - ) - - # Make the request - await client.delete_local_inventory(request=request) - - Args: - request (Optional[Union[google.shopping.merchant_inventories_v1beta.types.DeleteLocalInventoryRequest, dict]]): - The request object. Request message for the ``DeleteLocalInventory`` method. - name (:class:`str`): - Required. The name of the local inventory for the given - product to delete. Format: - ``accounts/{account}/products/{product}/localInventories/{store_code}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, localinventory.DeleteLocalInventoryRequest): - request = localinventory.DeleteLocalInventoryRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_local_inventory] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def __aenter__(self) -> "LocalInventoryServiceAsyncClient": - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "LocalInventoryServiceAsyncClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/client.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/client.py deleted file mode 100644 index 4c93e36e7f8e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/client.py +++ /dev/null @@ -1,919 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -import logging as std_logging -import os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.shopping.merchant_inventories_v1beta import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - -from google.shopping.merchant_inventories_v1beta.services.local_inventory_service import pagers -from google.shopping.merchant_inventories_v1beta.types import localinventory -from google.shopping.type.types import types -from google.type import interval_pb2 # type: ignore -from .transports.base import LocalInventoryServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import LocalInventoryServiceGrpcTransport -from .transports.grpc_asyncio import LocalInventoryServiceGrpcAsyncIOTransport -from .transports.rest import LocalInventoryServiceRestTransport - - -class LocalInventoryServiceClientMeta(type): - """Metaclass for the LocalInventoryService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[LocalInventoryServiceTransport]] - _transport_registry["grpc"] = LocalInventoryServiceGrpcTransport - _transport_registry["grpc_asyncio"] = LocalInventoryServiceGrpcAsyncIOTransport - _transport_registry["rest"] = LocalInventoryServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[LocalInventoryServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class LocalInventoryServiceClient(metaclass=LocalInventoryServiceClientMeta): - """Service to manage local inventory for products""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = "merchantapi.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "merchantapi.{UNIVERSE_DOMAIN}" - _DEFAULT_UNIVERSE = "googleapis.com" - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - LocalInventoryServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - LocalInventoryServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> LocalInventoryServiceTransport: - """Returns the transport used by the client instance. - - Returns: - LocalInventoryServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def local_inventory_path(account: str,product: str,store_code: str,) -> str: - """Returns a fully-qualified local_inventory string.""" - return "accounts/{account}/products/{product}/localInventories/{store_code}".format(account=account, product=product, store_code=store_code, ) - - @staticmethod - def parse_local_inventory_path(path: str) -> Dict[str,str]: - """Parses a local_inventory path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/products/(?P.+?)/localInventories/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Deprecated. Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - @staticmethod - def _read_environment_variables(): - """Returns the environment variables used by the client. - - Returns: - Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, - GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. - - Raises: - ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not - any of ["true", "false"]. - google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT - is not any of ["auto", "never", "always"]. - """ - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() - universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env - - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - - @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): - """Return the API endpoint used by the client. - - Args: - api_override (str): The API endpoint override. If specified, this is always - the return value of this function and the other arguments are not used. - client_cert_source (bytes): The client certificate source used by the client. - universe_domain (str): The universe domain used by the client. - use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. - Possible values are "always", "auto", or "never". - - Returns: - str: The API endpoint to be used by the client. - """ - if api_override is not None: - api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - _default_universe = LocalInventoryServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = LocalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = LocalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) - return api_endpoint - - @staticmethod - def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: - """Return the universe domain used by the client. - - Args: - client_universe_domain (Optional[str]): The universe domain configured via the client options. - universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. - - Returns: - str: The universe domain to be used by the client. - - Raises: - ValueError: If the universe domain is an empty string. - """ - universe_domain = LocalInventoryServiceClient._DEFAULT_UNIVERSE - if client_universe_domain is not None: - universe_domain = client_universe_domain - elif universe_domain_env is not None: - universe_domain = universe_domain_env - if len(universe_domain.strip()) == 0: - raise ValueError("Universe Domain cannot be an empty string.") - return universe_domain - - def _validate_universe_domain(self): - """Validates client's and credentials' universe domains are consistent. - - Returns: - bool: True iff the configured universe domain is valid. - - Raises: - ValueError: If the configured universe domain is not valid. - """ - - # NOTE (b/349488459): universe validation is disabled until further notice. - return True - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used by the client instance. - """ - return self._universe_domain - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, LocalInventoryServiceTransport, Callable[..., LocalInventoryServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the local inventory service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,LocalInventoryServiceTransport,Callable[..., LocalInventoryServiceTransport]]]): - The transport to use, or a Callable that constructs and returns a new transport. - If a Callable is given, it will be called with the same set of initialization - arguments as used in the LocalInventoryServiceTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that the ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client_options = client_options - if isinstance(self._client_options, dict): - self._client_options = client_options_lib.from_dict(self._client_options) - if self._client_options is None: - self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = LocalInventoryServiceClient._read_environment_variables() - self._client_cert_source = LocalInventoryServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = LocalInventoryServiceClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) - self._api_endpoint = None # updated below, depending on `transport` - - # Initialize the universe domain validation. - self._is_universe_domain_valid = False - - if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER - # Setup logging. - client_logging.initialize_logging() - - api_key_value = getattr(self._client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - transport_provided = isinstance(transport, LocalInventoryServiceTransport) - if transport_provided: - # transport is a LocalInventoryServiceTransport instance. - if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if self._client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = cast(LocalInventoryServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - LocalInventoryServiceClient._get_api_endpoint( - self._client_options.api_endpoint, - self._client_cert_source, - self._universe_domain, - self._use_mtls_endpoint)) - - if not transport_provided: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - transport_init: Union[Type[LocalInventoryServiceTransport], Callable[..., LocalInventoryServiceTransport]] = ( - LocalInventoryServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., LocalInventoryServiceTransport], transport) - ) - # initialize with the provided callable or the passed in class - self._transport = transport_init( - credentials=credentials, - credentials_file=self._client_options.credentials_file, - host=self._api_endpoint, - scopes=self._client_options.scopes, - client_cert_source_for_mtls=self._client_cert_source, - quota_project_id=self._client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=self._client_options.api_audience, - ) - - if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER - _LOGGER.debug( - "Created client `google.shopping.merchant.inventories_v1beta.LocalInventoryServiceClient`.", - extra = { - "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", - "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), - "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._transport, "_credentials") else { - "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", - "credentialsType": None, - } - ) - - def list_local_inventories(self, - request: Optional[Union[localinventory.ListLocalInventoriesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListLocalInventoriesPager: - r"""Lists the ``LocalInventory`` resources for the given product in - your merchant account. The response might contain fewer items - than specified by ``pageSize``. If ``pageToken`` was returned in - previous request, it can be used to obtain additional results. - - ``LocalInventory`` resources are listed per product for a given - account. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_inventories_v1beta - - def sample_list_local_inventories(): - # Create a client - client = merchant_inventories_v1beta.LocalInventoryServiceClient() - - # Initialize request argument(s) - request = merchant_inventories_v1beta.ListLocalInventoriesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_local_inventories(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesRequest, dict]): - The request object. Request message for the ``ListLocalInventories`` method. - parent (str): - Required. The ``name`` of the parent product to list - local inventories for. Format: - ``accounts/{account}/products/{product}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.shopping.merchant_inventories_v1beta.services.local_inventory_service.pagers.ListLocalInventoriesPager: - Response message for the ListLocalInventories method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, localinventory.ListLocalInventoriesRequest): - request = localinventory.ListLocalInventoriesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_local_inventories] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListLocalInventoriesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def insert_local_inventory(self, - request: Optional[Union[localinventory.InsertLocalInventoryRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> localinventory.LocalInventory: - r"""Inserts a ``LocalInventory`` resource to a product in your - merchant account. - - Replaces the full ``LocalInventory`` resource if an entry with - the same - [``storeCode``][google.shopping.merchant.inventories.v1beta.LocalInventory.store_code] - already exists for the product. - - It might take up to 30 minutes for the new or updated - ``LocalInventory`` resource to appear in products. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_inventories_v1beta - - def sample_insert_local_inventory(): - # Create a client - client = merchant_inventories_v1beta.LocalInventoryServiceClient() - - # Initialize request argument(s) - local_inventory = merchant_inventories_v1beta.LocalInventory() - local_inventory.store_code = "store_code_value" - - request = merchant_inventories_v1beta.InsertLocalInventoryRequest( - parent="parent_value", - local_inventory=local_inventory, - ) - - # Make the request - response = client.insert_local_inventory(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_inventories_v1beta.types.InsertLocalInventoryRequest, dict]): - The request object. Request message for the ``InsertLocalInventory`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.shopping.merchant_inventories_v1beta.types.LocalInventory: - Local inventory information for the product. Represents in-store information - for a specific product at the store specified by - [storeCode][google.shopping.merchant.inventories.v1beta.LocalInventory.store_code]. - For a list of all accepted attribute values, see the - [local product inventory data - specification](\ https://support.google.com/merchants/answer/3061342). - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, localinventory.InsertLocalInventoryRequest): - request = localinventory.InsertLocalInventoryRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.insert_local_inventory] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_local_inventory(self, - request: Optional[Union[localinventory.DeleteLocalInventoryRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: - r"""Deletes the specified ``LocalInventory`` from the given product - in your merchant account. It might take a up to an hour for the - ``LocalInventory`` to be deleted from the specific product. Once - you have received a successful delete response, wait for that - period before attempting a delete again. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_inventories_v1beta - - def sample_delete_local_inventory(): - # Create a client - client = merchant_inventories_v1beta.LocalInventoryServiceClient() - - # Initialize request argument(s) - request = merchant_inventories_v1beta.DeleteLocalInventoryRequest( - name="name_value", - ) - - # Make the request - client.delete_local_inventory(request=request) - - Args: - request (Union[google.shopping.merchant_inventories_v1beta.types.DeleteLocalInventoryRequest, dict]): - The request object. Request message for the ``DeleteLocalInventory`` method. - name (str): - Required. The name of the local inventory for the given - product to delete. Format: - ``accounts/{account}/products/{product}/localInventories/{store_code}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, localinventory.DeleteLocalInventoryRequest): - request = localinventory.DeleteLocalInventoryRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_local_inventory] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def __enter__(self) -> "LocalInventoryServiceClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "LocalInventoryServiceClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/pagers.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/pagers.py deleted file mode 100644 index 185fea1c5d47..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/pagers.py +++ /dev/null @@ -1,166 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import retry_async as retries_async -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] - OptionalAsyncRetry = Union[retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore - -from google.shopping.merchant_inventories_v1beta.types import localinventory - - -class ListLocalInventoriesPager: - """A pager for iterating through ``list_local_inventories`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``local_inventories`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListLocalInventories`` requests and continue to iterate - through the ``local_inventories`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., localinventory.ListLocalInventoriesResponse], - request: localinventory.ListLocalInventoriesRequest, - response: localinventory.ListLocalInventoriesResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesRequest): - The initial request object. - response (google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesResponse): - The initial response object. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = localinventory.ListLocalInventoriesRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[localinventory.ListLocalInventoriesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[localinventory.LocalInventory]: - for page in self.pages: - yield from page.local_inventories - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListLocalInventoriesAsyncPager: - """A pager for iterating through ``list_local_inventories`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``local_inventories`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListLocalInventories`` requests and continue to iterate - through the ``local_inventories`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[localinventory.ListLocalInventoriesResponse]], - request: localinventory.ListLocalInventoriesRequest, - response: localinventory.ListLocalInventoriesResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesRequest): - The initial request object. - response (google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesResponse): - The initial response object. - retry (google.api_core.retry.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = localinventory.ListLocalInventoriesRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[localinventory.ListLocalInventoriesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[localinventory.LocalInventory]: - async def async_generator(): - async for page in self.pages: - for response in page.local_inventories: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/README.rst deleted file mode 100644 index 816e98eb5847..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`LocalInventoryServiceTransport` is the ABC for all transports. -- public child `LocalInventoryServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `LocalInventoryServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseLocalInventoryServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `LocalInventoryServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/__init__.py deleted file mode 100644 index 77e2551dd074..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import LocalInventoryServiceTransport -from .grpc import LocalInventoryServiceGrpcTransport -from .grpc_asyncio import LocalInventoryServiceGrpcAsyncIOTransport -from .rest import LocalInventoryServiceRestTransport -from .rest import LocalInventoryServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[LocalInventoryServiceTransport]] -_transport_registry['grpc'] = LocalInventoryServiceGrpcTransport -_transport_registry['grpc_asyncio'] = LocalInventoryServiceGrpcAsyncIOTransport -_transport_registry['rest'] = LocalInventoryServiceRestTransport - -__all__ = ( - 'LocalInventoryServiceTransport', - 'LocalInventoryServiceGrpcTransport', - 'LocalInventoryServiceGrpcAsyncIOTransport', - 'LocalInventoryServiceRestTransport', - 'LocalInventoryServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/base.py deleted file mode 100644 index 1e299a9a0ba8..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/base.py +++ /dev/null @@ -1,183 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.shopping.merchant_inventories_v1beta import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.protobuf import empty_pb2 # type: ignore -from google.shopping.merchant_inventories_v1beta.types import localinventory - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class LocalInventoryServiceTransport(abc.ABC): - """Abstract transport class for LocalInventoryService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/content', - ) - - DEFAULT_HOST: str = 'merchantapi.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'merchantapi.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - if not hasattr(self, "_ignore_credentials"): - self._ignore_credentials: bool = False - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - @property - def host(self): - return self._host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_local_inventories: gapic_v1.method.wrap_method( - self.list_local_inventories, - default_timeout=None, - client_info=client_info, - ), - self.insert_local_inventory: gapic_v1.method.wrap_method( - self.insert_local_inventory, - default_timeout=None, - client_info=client_info, - ), - self.delete_local_inventory: gapic_v1.method.wrap_method( - self.delete_local_inventory, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def list_local_inventories(self) -> Callable[ - [localinventory.ListLocalInventoriesRequest], - Union[ - localinventory.ListLocalInventoriesResponse, - Awaitable[localinventory.ListLocalInventoriesResponse] - ]]: - raise NotImplementedError() - - @property - def insert_local_inventory(self) -> Callable[ - [localinventory.InsertLocalInventoryRequest], - Union[ - localinventory.LocalInventory, - Awaitable[localinventory.LocalInventory] - ]]: - raise NotImplementedError() - - @property - def delete_local_inventory(self) -> Callable[ - [localinventory.DeleteLocalInventoryRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'LocalInventoryServiceTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/grpc.py deleted file mode 100644 index 21eb1b3e88ba..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/grpc.py +++ /dev/null @@ -1,419 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import json -import logging as std_logging -import pickle -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.protobuf.json_format import MessageToJson -import google.protobuf.message - -import grpc # type: ignore -import proto # type: ignore - -from google.protobuf import empty_pb2 # type: ignore -from google.shopping.merchant_inventories_v1beta.types import localinventory -from .base import LocalInventoryServiceTransport, DEFAULT_CLIENT_INFO - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - - -class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER - def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) - if logging_enabled: # pragma: NO COVER - request_metadata = client_call_details.metadata - if isinstance(request, proto.Message): - request_payload = type(request).to_json(request) - elif isinstance(request, google.protobuf.message.Message): - request_payload = MessageToJson(request) - else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" - - request_metadata = { - key: value.decode("utf-8") if isinstance(value, bytes) else value - for key, value in request_metadata - } - grpc_request = { - "payload": request_payload, - "requestMethod": "grpc", - "metadata": dict(request_metadata), - } - _LOGGER.debug( - f"Sending request for {client_call_details.method}", - extra = { - "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", - "rpcName": client_call_details.method, - "request": grpc_request, - "metadata": grpc_request["metadata"], - }, - ) - - response = continuation(client_call_details, request) - if logging_enabled: # pragma: NO COVER - response_metadata = response.trailing_metadata() - # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None - result = response.result() - if isinstance(result, proto.Message): - response_payload = type(result).to_json(result) - elif isinstance(result, google.protobuf.message.Message): - response_payload = MessageToJson(result) - else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" - grpc_response = { - "payload": response_payload, - "metadata": metadata, - "status": "OK", - } - _LOGGER.debug( - f"Received response for {client_call_details.method}.", - extra = { - "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class LocalInventoryServiceGrpcTransport(LocalInventoryServiceTransport): - """gRPC backend transport for LocalInventoryService. - - Service to manage local inventory for products - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'merchantapi.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'merchantapi.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if a ``channel`` instance is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if a ``channel`` instance is provided. - channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, grpc.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) - - # Wrap messages. This must be done after self._logged_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'merchantapi.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def list_local_inventories(self) -> Callable[ - [localinventory.ListLocalInventoriesRequest], - localinventory.ListLocalInventoriesResponse]: - r"""Return a callable for the list local inventories method over gRPC. - - Lists the ``LocalInventory`` resources for the given product in - your merchant account. The response might contain fewer items - than specified by ``pageSize``. If ``pageToken`` was returned in - previous request, it can be used to obtain additional results. - - ``LocalInventory`` resources are listed per product for a given - account. - - Returns: - Callable[[~.ListLocalInventoriesRequest], - ~.ListLocalInventoriesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_local_inventories' not in self._stubs: - self._stubs['list_local_inventories'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.inventories.v1beta.LocalInventoryService/ListLocalInventories', - request_serializer=localinventory.ListLocalInventoriesRequest.serialize, - response_deserializer=localinventory.ListLocalInventoriesResponse.deserialize, - ) - return self._stubs['list_local_inventories'] - - @property - def insert_local_inventory(self) -> Callable[ - [localinventory.InsertLocalInventoryRequest], - localinventory.LocalInventory]: - r"""Return a callable for the insert local inventory method over gRPC. - - Inserts a ``LocalInventory`` resource to a product in your - merchant account. - - Replaces the full ``LocalInventory`` resource if an entry with - the same - [``storeCode``][google.shopping.merchant.inventories.v1beta.LocalInventory.store_code] - already exists for the product. - - It might take up to 30 minutes for the new or updated - ``LocalInventory`` resource to appear in products. - - Returns: - Callable[[~.InsertLocalInventoryRequest], - ~.LocalInventory]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'insert_local_inventory' not in self._stubs: - self._stubs['insert_local_inventory'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.inventories.v1beta.LocalInventoryService/InsertLocalInventory', - request_serializer=localinventory.InsertLocalInventoryRequest.serialize, - response_deserializer=localinventory.LocalInventory.deserialize, - ) - return self._stubs['insert_local_inventory'] - - @property - def delete_local_inventory(self) -> Callable[ - [localinventory.DeleteLocalInventoryRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete local inventory method over gRPC. - - Deletes the specified ``LocalInventory`` from the given product - in your merchant account. It might take a up to an hour for the - ``LocalInventory`` to be deleted from the specific product. Once - you have received a successful delete response, wait for that - period before attempting a delete again. - - Returns: - Callable[[~.DeleteLocalInventoryRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_local_inventory' not in self._stubs: - self._stubs['delete_local_inventory'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.inventories.v1beta.LocalInventoryService/DeleteLocalInventory', - request_serializer=localinventory.DeleteLocalInventoryRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_local_inventory'] - - def close(self): - self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'LocalInventoryServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/grpc_asyncio.py deleted file mode 100644 index a29b3d0a28e3..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,449 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import inspect -import json -import pickle -import logging as std_logging -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import exceptions as core_exceptions -from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.protobuf.json_format import MessageToJson -import google.protobuf.message - -import grpc # type: ignore -import proto # type: ignore -from grpc.experimental import aio # type: ignore - -from google.protobuf import empty_pb2 # type: ignore -from google.shopping.merchant_inventories_v1beta.types import localinventory -from .base import LocalInventoryServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import LocalInventoryServiceGrpcTransport - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - - -class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER - async def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) - if logging_enabled: # pragma: NO COVER - request_metadata = client_call_details.metadata - if isinstance(request, proto.Message): - request_payload = type(request).to_json(request) - elif isinstance(request, google.protobuf.message.Message): - request_payload = MessageToJson(request) - else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" - - request_metadata = { - key: value.decode("utf-8") if isinstance(value, bytes) else value - for key, value in request_metadata - } - grpc_request = { - "payload": request_payload, - "requestMethod": "grpc", - "metadata": dict(request_metadata), - } - _LOGGER.debug( - f"Sending request for {client_call_details.method}", - extra = { - "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", - "rpcName": str(client_call_details.method), - "request": grpc_request, - "metadata": grpc_request["metadata"], - }, - ) - response = await continuation(client_call_details, request) - if logging_enabled: # pragma: NO COVER - response_metadata = await response.trailing_metadata() - # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None - result = await response - if isinstance(result, proto.Message): - response_payload = type(result).to_json(result) - elif isinstance(result, google.protobuf.message.Message): - response_payload = MessageToJson(result) - else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" - grpc_response = { - "payload": response_payload, - "metadata": metadata, - "status": "OK", - } - _LOGGER.debug( - f"Received response to rpc {client_call_details.method}.", - extra = { - "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class LocalInventoryServiceGrpcAsyncIOTransport(LocalInventoryServiceTransport): - """gRPC AsyncIO backend transport for LocalInventoryService. - - Service to manage local inventory for products - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'merchantapi.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'merchantapi.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'merchantapi.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if a ``channel`` instance is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, aio.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - self._interceptor = _LoggingClientAIOInterceptor() - self._grpc_channel._unary_unary_interceptors.append(self._interceptor) - self._logged_channel = self._grpc_channel - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - # Wrap messages. This must be done after self._logged_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def list_local_inventories(self) -> Callable[ - [localinventory.ListLocalInventoriesRequest], - Awaitable[localinventory.ListLocalInventoriesResponse]]: - r"""Return a callable for the list local inventories method over gRPC. - - Lists the ``LocalInventory`` resources for the given product in - your merchant account. The response might contain fewer items - than specified by ``pageSize``. If ``pageToken`` was returned in - previous request, it can be used to obtain additional results. - - ``LocalInventory`` resources are listed per product for a given - account. - - Returns: - Callable[[~.ListLocalInventoriesRequest], - Awaitable[~.ListLocalInventoriesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_local_inventories' not in self._stubs: - self._stubs['list_local_inventories'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.inventories.v1beta.LocalInventoryService/ListLocalInventories', - request_serializer=localinventory.ListLocalInventoriesRequest.serialize, - response_deserializer=localinventory.ListLocalInventoriesResponse.deserialize, - ) - return self._stubs['list_local_inventories'] - - @property - def insert_local_inventory(self) -> Callable[ - [localinventory.InsertLocalInventoryRequest], - Awaitable[localinventory.LocalInventory]]: - r"""Return a callable for the insert local inventory method over gRPC. - - Inserts a ``LocalInventory`` resource to a product in your - merchant account. - - Replaces the full ``LocalInventory`` resource if an entry with - the same - [``storeCode``][google.shopping.merchant.inventories.v1beta.LocalInventory.store_code] - already exists for the product. - - It might take up to 30 minutes for the new or updated - ``LocalInventory`` resource to appear in products. - - Returns: - Callable[[~.InsertLocalInventoryRequest], - Awaitable[~.LocalInventory]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'insert_local_inventory' not in self._stubs: - self._stubs['insert_local_inventory'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.inventories.v1beta.LocalInventoryService/InsertLocalInventory', - request_serializer=localinventory.InsertLocalInventoryRequest.serialize, - response_deserializer=localinventory.LocalInventory.deserialize, - ) - return self._stubs['insert_local_inventory'] - - @property - def delete_local_inventory(self) -> Callable[ - [localinventory.DeleteLocalInventoryRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete local inventory method over gRPC. - - Deletes the specified ``LocalInventory`` from the given product - in your merchant account. It might take a up to an hour for the - ``LocalInventory`` to be deleted from the specific product. Once - you have received a successful delete response, wait for that - period before attempting a delete again. - - Returns: - Callable[[~.DeleteLocalInventoryRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_local_inventory' not in self._stubs: - self._stubs['delete_local_inventory'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.inventories.v1beta.LocalInventoryService/DeleteLocalInventory', - request_serializer=localinventory.DeleteLocalInventoryRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_local_inventory'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.list_local_inventories: self._wrap_method( - self.list_local_inventories, - default_timeout=None, - client_info=client_info, - ), - self.insert_local_inventory: self._wrap_method( - self.insert_local_inventory, - default_timeout=None, - client_info=client_info, - ), - self.delete_local_inventory: self._wrap_method( - self.delete_local_inventory, - default_timeout=None, - client_info=client_info, - ), - } - - def _wrap_method(self, func, *args, **kwargs): - if self._wrap_with_kind: # pragma: NO COVER - kwargs["kind"] = self.kind - return gapic_v1.method_async.wrap_method(func, *args, **kwargs) - - def close(self): - return self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc_asyncio" - - -__all__ = ( - 'LocalInventoryServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/rest.py deleted file mode 100644 index 2a7b87a761c7..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/rest.py +++ /dev/null @@ -1,594 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -from google.protobuf import json_format - -from requests import __version__ as requests_version -import dataclasses -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - - -from google.protobuf import empty_pb2 # type: ignore -from google.shopping.merchant_inventories_v1beta.types import localinventory - - -from .rest_base import _BaseLocalInventoryServiceRestTransport -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = logging.getLogger(__name__) - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=f"requests@{requests_version}", -) - - -class LocalInventoryServiceRestInterceptor: - """Interceptor for LocalInventoryService. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the LocalInventoryServiceRestTransport. - - .. code-block:: python - class MyCustomLocalInventoryServiceInterceptor(LocalInventoryServiceRestInterceptor): - def pre_delete_local_inventory(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_insert_local_inventory(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_insert_local_inventory(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_local_inventories(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_local_inventories(self, response): - logging.log(f"Received response: {response}") - return response - - transport = LocalInventoryServiceRestTransport(interceptor=MyCustomLocalInventoryServiceInterceptor()) - client = LocalInventoryServiceClient(transport=transport) - - - """ - def pre_delete_local_inventory(self, request: localinventory.DeleteLocalInventoryRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[localinventory.DeleteLocalInventoryRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_local_inventory - - Override in a subclass to manipulate the request or metadata - before they are sent to the LocalInventoryService server. - """ - return request, metadata - - def pre_insert_local_inventory(self, request: localinventory.InsertLocalInventoryRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[localinventory.InsertLocalInventoryRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for insert_local_inventory - - Override in a subclass to manipulate the request or metadata - before they are sent to the LocalInventoryService server. - """ - return request, metadata - - def post_insert_local_inventory(self, response: localinventory.LocalInventory) -> localinventory.LocalInventory: - """Post-rpc interceptor for insert_local_inventory - - Override in a subclass to manipulate the response - after it is returned by the LocalInventoryService server but before - it is returned to user code. - """ - return response - - def pre_list_local_inventories(self, request: localinventory.ListLocalInventoriesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[localinventory.ListLocalInventoriesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_local_inventories - - Override in a subclass to manipulate the request or metadata - before they are sent to the LocalInventoryService server. - """ - return request, metadata - - def post_list_local_inventories(self, response: localinventory.ListLocalInventoriesResponse) -> localinventory.ListLocalInventoriesResponse: - """Post-rpc interceptor for list_local_inventories - - Override in a subclass to manipulate the response - after it is returned by the LocalInventoryService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class LocalInventoryServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: LocalInventoryServiceRestInterceptor - - -class LocalInventoryServiceRestTransport(_BaseLocalInventoryServiceRestTransport): - """REST backend synchronous transport for LocalInventoryService. - - Service to manage local inventory for products - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - """ - - def __init__(self, *, - host: str = 'merchantapi.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[LocalInventoryServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'merchantapi.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - url_scheme=url_scheme, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or LocalInventoryServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _DeleteLocalInventory(_BaseLocalInventoryServiceRestTransport._BaseDeleteLocalInventory, LocalInventoryServiceRestStub): - def __hash__(self): - return hash("LocalInventoryServiceRestTransport.DeleteLocalInventory") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: localinventory.DeleteLocalInventoryRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ): - r"""Call the delete local inventory method over HTTP. - - Args: - request (~.localinventory.DeleteLocalInventoryRequest): - The request object. Request message for the ``DeleteLocalInventory`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - - http_options = _BaseLocalInventoryServiceRestTransport._BaseDeleteLocalInventory._get_http_options() - - request, metadata = self._interceptor.pre_delete_local_inventory(request, metadata) - transcoded_request = _BaseLocalInventoryServiceRestTransport._BaseDeleteLocalInventory._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseLocalInventoryServiceRestTransport._BaseDeleteLocalInventory._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.shopping.merchant.inventories_v1beta.LocalInventoryServiceClient.DeleteLocalInventory", - extra = { - "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", - "rpcName": "DeleteLocalInventory", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = LocalInventoryServiceRestTransport._DeleteLocalInventory._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _InsertLocalInventory(_BaseLocalInventoryServiceRestTransport._BaseInsertLocalInventory, LocalInventoryServiceRestStub): - def __hash__(self): - return hash("LocalInventoryServiceRestTransport.InsertLocalInventory") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: localinventory.InsertLocalInventoryRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> localinventory.LocalInventory: - r"""Call the insert local inventory method over HTTP. - - Args: - request (~.localinventory.InsertLocalInventoryRequest): - The request object. Request message for the ``InsertLocalInventory`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.localinventory.LocalInventory: - Local inventory information for the product. Represents - in-store information for a specific product at the store - specified by - [``storeCode``][google.shopping.merchant.inventories.v1beta.LocalInventory.store_code]. - For a list of all accepted attribute values, see the - `local product inventory data - specification `__. - - """ - - http_options = _BaseLocalInventoryServiceRestTransport._BaseInsertLocalInventory._get_http_options() - - request, metadata = self._interceptor.pre_insert_local_inventory(request, metadata) - transcoded_request = _BaseLocalInventoryServiceRestTransport._BaseInsertLocalInventory._get_transcoded_request(http_options, request) - - body = _BaseLocalInventoryServiceRestTransport._BaseInsertLocalInventory._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseLocalInventoryServiceRestTransport._BaseInsertLocalInventory._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.shopping.merchant.inventories_v1beta.LocalInventoryServiceClient.InsertLocalInventory", - extra = { - "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", - "rpcName": "InsertLocalInventory", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = LocalInventoryServiceRestTransport._InsertLocalInventory._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = localinventory.LocalInventory() - pb_resp = localinventory.LocalInventory.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_insert_local_inventory(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = localinventory.LocalInventory.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.shopping.merchant.inventories_v1beta.LocalInventoryServiceClient.insert_local_inventory", - extra = { - "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", - "rpcName": "InsertLocalInventory", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListLocalInventories(_BaseLocalInventoryServiceRestTransport._BaseListLocalInventories, LocalInventoryServiceRestStub): - def __hash__(self): - return hash("LocalInventoryServiceRestTransport.ListLocalInventories") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: localinventory.ListLocalInventoriesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> localinventory.ListLocalInventoriesResponse: - r"""Call the list local inventories method over HTTP. - - Args: - request (~.localinventory.ListLocalInventoriesRequest): - The request object. Request message for the ``ListLocalInventories`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.localinventory.ListLocalInventoriesResponse: - Response message for the ``ListLocalInventories`` - method. - - """ - - http_options = _BaseLocalInventoryServiceRestTransport._BaseListLocalInventories._get_http_options() - - request, metadata = self._interceptor.pre_list_local_inventories(request, metadata) - transcoded_request = _BaseLocalInventoryServiceRestTransport._BaseListLocalInventories._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseLocalInventoryServiceRestTransport._BaseListLocalInventories._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.shopping.merchant.inventories_v1beta.LocalInventoryServiceClient.ListLocalInventories", - extra = { - "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", - "rpcName": "ListLocalInventories", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = LocalInventoryServiceRestTransport._ListLocalInventories._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = localinventory.ListLocalInventoriesResponse() - pb_resp = localinventory.ListLocalInventoriesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_local_inventories(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = localinventory.ListLocalInventoriesResponse.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.shopping.merchant.inventories_v1beta.LocalInventoryServiceClient.list_local_inventories", - extra = { - "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", - "rpcName": "ListLocalInventories", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def delete_local_inventory(self) -> Callable[ - [localinventory.DeleteLocalInventoryRequest], - empty_pb2.Empty]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteLocalInventory(self._session, self._host, self._interceptor) # type: ignore - - @property - def insert_local_inventory(self) -> Callable[ - [localinventory.InsertLocalInventoryRequest], - localinventory.LocalInventory]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._InsertLocalInventory(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_local_inventories(self) -> Callable[ - [localinventory.ListLocalInventoriesRequest], - localinventory.ListLocalInventoriesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListLocalInventories(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'LocalInventoryServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/rest_base.py deleted file mode 100644 index b032ed33070d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/rest_base.py +++ /dev/null @@ -1,213 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import json # type: ignore -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from .base import LocalInventoryServiceTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.protobuf import empty_pb2 # type: ignore -from google.shopping.merchant_inventories_v1beta.types import localinventory - - -class _BaseLocalInventoryServiceRestTransport(LocalInventoryServiceTransport): - """Base REST backend transport for LocalInventoryService. - - Note: This class is not meant to be used directly. Use its sync and - async sub-classes instead. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - """ - - def __init__(self, *, - host: str = 'merchantapi.googleapis.com', - credentials: Optional[Any] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - Args: - host (Optional[str]): - The hostname to connect to (default: 'merchantapi.googleapis.com'). - credentials (Optional[Any]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - - class _BaseDeleteLocalInventory: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/inventories/v1beta/{name=accounts/*/products/*/localInventories/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = localinventory.DeleteLocalInventoryRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseLocalInventoryServiceRestTransport._BaseDeleteLocalInventory._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseInsertLocalInventory: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/inventories/v1beta/{parent=accounts/*/products/*}/localInventories:insert', - 'body': 'local_inventory', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = localinventory.InsertLocalInventoryRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseLocalInventoryServiceRestTransport._BaseInsertLocalInventory._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListLocalInventories: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/inventories/v1beta/{parent=accounts/*/products/*}/localInventories', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = localinventory.ListLocalInventoriesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseLocalInventoryServiceRestTransport._BaseListLocalInventories._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseLocalInventoryServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/__init__.py deleted file mode 100644 index 1858a9e76b49..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import RegionalInventoryServiceClient -from .async_client import RegionalInventoryServiceAsyncClient - -__all__ = ( - 'RegionalInventoryServiceClient', - 'RegionalInventoryServiceAsyncClient', -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/async_client.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/async_client.py deleted file mode 100644 index cccbc1bdb3bc..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/async_client.py +++ /dev/null @@ -1,591 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import logging as std_logging -from collections import OrderedDict -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.shopping.merchant_inventories_v1beta import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - - -try: - OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore - -from google.shopping.merchant_inventories_v1beta.services.regional_inventory_service import pagers -from google.shopping.merchant_inventories_v1beta.types import regionalinventory -from google.shopping.type.types import types -from google.type import interval_pb2 # type: ignore -from .transports.base import RegionalInventoryServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import RegionalInventoryServiceGrpcAsyncIOTransport -from .client import RegionalInventoryServiceClient - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - -class RegionalInventoryServiceAsyncClient: - """Service to manage regional inventory for products. There is also - separate ``regions`` resource and API to manage regions definitions. - """ - - _client: RegionalInventoryServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = RegionalInventoryServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = RegionalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = RegionalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = RegionalInventoryServiceClient._DEFAULT_UNIVERSE - - regional_inventory_path = staticmethod(RegionalInventoryServiceClient.regional_inventory_path) - parse_regional_inventory_path = staticmethod(RegionalInventoryServiceClient.parse_regional_inventory_path) - common_billing_account_path = staticmethod(RegionalInventoryServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(RegionalInventoryServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(RegionalInventoryServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(RegionalInventoryServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(RegionalInventoryServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(RegionalInventoryServiceClient.parse_common_organization_path) - common_project_path = staticmethod(RegionalInventoryServiceClient.common_project_path) - parse_common_project_path = staticmethod(RegionalInventoryServiceClient.parse_common_project_path) - common_location_path = staticmethod(RegionalInventoryServiceClient.common_location_path) - parse_common_location_path = staticmethod(RegionalInventoryServiceClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - RegionalInventoryServiceAsyncClient: The constructed client. - """ - return RegionalInventoryServiceClient.from_service_account_info.__func__(RegionalInventoryServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - RegionalInventoryServiceAsyncClient: The constructed client. - """ - return RegionalInventoryServiceClient.from_service_account_file.__func__(RegionalInventoryServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return RegionalInventoryServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> RegionalInventoryServiceTransport: - """Returns the transport used by the client instance. - - Returns: - RegionalInventoryServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._client._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used - by the client instance. - """ - return self._client._universe_domain - - get_transport_class = RegionalInventoryServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, RegionalInventoryServiceTransport, Callable[..., RegionalInventoryServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the regional inventory service async client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,RegionalInventoryServiceTransport,Callable[..., RegionalInventoryServiceTransport]]]): - The transport to use, or a Callable that constructs and returns a new transport to use. - If a Callable is given, it will be called with the same set of initialization - arguments as used in the RegionalInventoryServiceTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = RegionalInventoryServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER - _LOGGER.debug( - "Created client `google.shopping.merchant.inventories_v1beta.RegionalInventoryServiceAsyncClient`.", - extra = { - "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", - "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), - "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._client._transport, "_credentials") else { - "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", - "credentialsType": None, - } - ) - - async def list_regional_inventories(self, - request: Optional[Union[regionalinventory.ListRegionalInventoriesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListRegionalInventoriesAsyncPager: - r"""Lists the ``RegionalInventory`` resources for the given product - in your merchant account. The response might contain fewer items - than specified by ``pageSize``. If ``pageToken`` was returned in - previous request, it can be used to obtain additional results. - - ``RegionalInventory`` resources are listed per product for a - given account. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_inventories_v1beta - - async def sample_list_regional_inventories(): - # Create a client - client = merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_inventories_v1beta.ListRegionalInventoriesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_regional_inventories(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesRequest, dict]]): - The request object. Request message for the ``ListRegionalInventories`` - method. - parent (:class:`str`): - Required. The ``name`` of the parent product to list - ``RegionalInventory`` resources for. Format: - ``accounts/{account}/products/{product}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.pagers.ListRegionalInventoriesAsyncPager: - Response message for the ListRegionalInventories method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, regionalinventory.ListRegionalInventoriesRequest): - request = regionalinventory.ListRegionalInventoriesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_regional_inventories] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListRegionalInventoriesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def insert_regional_inventory(self, - request: Optional[Union[regionalinventory.InsertRegionalInventoryRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> regionalinventory.RegionalInventory: - r"""Inserts a ``RegionalInventory`` to a given product in your - merchant account. - - Replaces the full ``RegionalInventory`` resource if an entry - with the same - [``region``][google.shopping.merchant.inventories.v1beta.RegionalInventory.region] - already exists for the product. - - It might take up to 30 minutes for the new or updated - ``RegionalInventory`` resource to appear in products. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_inventories_v1beta - - async def sample_insert_regional_inventory(): - # Create a client - client = merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient() - - # Initialize request argument(s) - regional_inventory = merchant_inventories_v1beta.RegionalInventory() - regional_inventory.region = "region_value" - - request = merchant_inventories_v1beta.InsertRegionalInventoryRequest( - parent="parent_value", - regional_inventory=regional_inventory, - ) - - # Make the request - response = await client.insert_regional_inventory(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_inventories_v1beta.types.InsertRegionalInventoryRequest, dict]]): - The request object. Request message for the ``InsertRegionalInventory`` - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.shopping.merchant_inventories_v1beta.types.RegionalInventory: - Regional inventory information for the product. Represents specific - information like price and availability for a given - product in a specific - [region][google.shopping.merchant.inventories.v1beta.RegionalInventory.region]. - For a list of all accepted attribute values, see the - [regional product inventory data - specification](\ https://support.google.com/merchants/answer/9698880). - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, regionalinventory.InsertRegionalInventoryRequest): - request = regionalinventory.InsertRegionalInventoryRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.insert_regional_inventory] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_regional_inventory(self, - request: Optional[Union[regionalinventory.DeleteRegionalInventoryRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: - r"""Deletes the specified ``RegionalInventory`` resource from the - given product in your merchant account. It might take up to an - hour for the ``RegionalInventory`` to be deleted from the - specific product. Once you have received a successful delete - response, wait for that period before attempting a delete again. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_inventories_v1beta - - async def sample_delete_regional_inventory(): - # Create a client - client = merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_inventories_v1beta.DeleteRegionalInventoryRequest( - name="name_value", - ) - - # Make the request - await client.delete_regional_inventory(request=request) - - Args: - request (Optional[Union[google.shopping.merchant_inventories_v1beta.types.DeleteRegionalInventoryRequest, dict]]): - The request object. Request message for the ``DeleteRegionalInventory`` - method. - name (:class:`str`): - Required. The name of the ``RegionalInventory`` resource - to delete. Format: - ``accounts/{account}/products/{product}/regionalInventories/{region}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, regionalinventory.DeleteRegionalInventoryRequest): - request = regionalinventory.DeleteRegionalInventoryRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_regional_inventory] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def __aenter__(self) -> "RegionalInventoryServiceAsyncClient": - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "RegionalInventoryServiceAsyncClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/client.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/client.py deleted file mode 100644 index 68f368040075..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/client.py +++ /dev/null @@ -1,925 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -import logging as std_logging -import os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.shopping.merchant_inventories_v1beta import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - -from google.shopping.merchant_inventories_v1beta.services.regional_inventory_service import pagers -from google.shopping.merchant_inventories_v1beta.types import regionalinventory -from google.shopping.type.types import types -from google.type import interval_pb2 # type: ignore -from .transports.base import RegionalInventoryServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import RegionalInventoryServiceGrpcTransport -from .transports.grpc_asyncio import RegionalInventoryServiceGrpcAsyncIOTransport -from .transports.rest import RegionalInventoryServiceRestTransport - - -class RegionalInventoryServiceClientMeta(type): - """Metaclass for the RegionalInventoryService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[RegionalInventoryServiceTransport]] - _transport_registry["grpc"] = RegionalInventoryServiceGrpcTransport - _transport_registry["grpc_asyncio"] = RegionalInventoryServiceGrpcAsyncIOTransport - _transport_registry["rest"] = RegionalInventoryServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[RegionalInventoryServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class RegionalInventoryServiceClient(metaclass=RegionalInventoryServiceClientMeta): - """Service to manage regional inventory for products. There is also - separate ``regions`` resource and API to manage regions definitions. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = "merchantapi.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "merchantapi.{UNIVERSE_DOMAIN}" - _DEFAULT_UNIVERSE = "googleapis.com" - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - RegionalInventoryServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - RegionalInventoryServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> RegionalInventoryServiceTransport: - """Returns the transport used by the client instance. - - Returns: - RegionalInventoryServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def regional_inventory_path(account: str,product: str,region: str,) -> str: - """Returns a fully-qualified regional_inventory string.""" - return "accounts/{account}/products/{product}/regionalInventories/{region}".format(account=account, product=product, region=region, ) - - @staticmethod - def parse_regional_inventory_path(path: str) -> Dict[str,str]: - """Parses a regional_inventory path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/products/(?P.+?)/regionalInventories/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Deprecated. Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - @staticmethod - def _read_environment_variables(): - """Returns the environment variables used by the client. - - Returns: - Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, - GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. - - Raises: - ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not - any of ["true", "false"]. - google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT - is not any of ["auto", "never", "always"]. - """ - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() - universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env - - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - - @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): - """Return the API endpoint used by the client. - - Args: - api_override (str): The API endpoint override. If specified, this is always - the return value of this function and the other arguments are not used. - client_cert_source (bytes): The client certificate source used by the client. - universe_domain (str): The universe domain used by the client. - use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. - Possible values are "always", "auto", or "never". - - Returns: - str: The API endpoint to be used by the client. - """ - if api_override is not None: - api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - _default_universe = RegionalInventoryServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = RegionalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = RegionalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) - return api_endpoint - - @staticmethod - def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: - """Return the universe domain used by the client. - - Args: - client_universe_domain (Optional[str]): The universe domain configured via the client options. - universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. - - Returns: - str: The universe domain to be used by the client. - - Raises: - ValueError: If the universe domain is an empty string. - """ - universe_domain = RegionalInventoryServiceClient._DEFAULT_UNIVERSE - if client_universe_domain is not None: - universe_domain = client_universe_domain - elif universe_domain_env is not None: - universe_domain = universe_domain_env - if len(universe_domain.strip()) == 0: - raise ValueError("Universe Domain cannot be an empty string.") - return universe_domain - - def _validate_universe_domain(self): - """Validates client's and credentials' universe domains are consistent. - - Returns: - bool: True iff the configured universe domain is valid. - - Raises: - ValueError: If the configured universe domain is not valid. - """ - - # NOTE (b/349488459): universe validation is disabled until further notice. - return True - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used by the client instance. - """ - return self._universe_domain - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, RegionalInventoryServiceTransport, Callable[..., RegionalInventoryServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the regional inventory service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,RegionalInventoryServiceTransport,Callable[..., RegionalInventoryServiceTransport]]]): - The transport to use, or a Callable that constructs and returns a new transport. - If a Callable is given, it will be called with the same set of initialization - arguments as used in the RegionalInventoryServiceTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that the ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client_options = client_options - if isinstance(self._client_options, dict): - self._client_options = client_options_lib.from_dict(self._client_options) - if self._client_options is None: - self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = RegionalInventoryServiceClient._read_environment_variables() - self._client_cert_source = RegionalInventoryServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = RegionalInventoryServiceClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) - self._api_endpoint = None # updated below, depending on `transport` - - # Initialize the universe domain validation. - self._is_universe_domain_valid = False - - if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER - # Setup logging. - client_logging.initialize_logging() - - api_key_value = getattr(self._client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - transport_provided = isinstance(transport, RegionalInventoryServiceTransport) - if transport_provided: - # transport is a RegionalInventoryServiceTransport instance. - if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if self._client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = cast(RegionalInventoryServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - RegionalInventoryServiceClient._get_api_endpoint( - self._client_options.api_endpoint, - self._client_cert_source, - self._universe_domain, - self._use_mtls_endpoint)) - - if not transport_provided: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - transport_init: Union[Type[RegionalInventoryServiceTransport], Callable[..., RegionalInventoryServiceTransport]] = ( - RegionalInventoryServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., RegionalInventoryServiceTransport], transport) - ) - # initialize with the provided callable or the passed in class - self._transport = transport_init( - credentials=credentials, - credentials_file=self._client_options.credentials_file, - host=self._api_endpoint, - scopes=self._client_options.scopes, - client_cert_source_for_mtls=self._client_cert_source, - quota_project_id=self._client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=self._client_options.api_audience, - ) - - if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER - _LOGGER.debug( - "Created client `google.shopping.merchant.inventories_v1beta.RegionalInventoryServiceClient`.", - extra = { - "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", - "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), - "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._transport, "_credentials") else { - "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", - "credentialsType": None, - } - ) - - def list_regional_inventories(self, - request: Optional[Union[regionalinventory.ListRegionalInventoriesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListRegionalInventoriesPager: - r"""Lists the ``RegionalInventory`` resources for the given product - in your merchant account. The response might contain fewer items - than specified by ``pageSize``. If ``pageToken`` was returned in - previous request, it can be used to obtain additional results. - - ``RegionalInventory`` resources are listed per product for a - given account. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_inventories_v1beta - - def sample_list_regional_inventories(): - # Create a client - client = merchant_inventories_v1beta.RegionalInventoryServiceClient() - - # Initialize request argument(s) - request = merchant_inventories_v1beta.ListRegionalInventoriesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_regional_inventories(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesRequest, dict]): - The request object. Request message for the ``ListRegionalInventories`` - method. - parent (str): - Required. The ``name`` of the parent product to list - ``RegionalInventory`` resources for. Format: - ``accounts/{account}/products/{product}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.pagers.ListRegionalInventoriesPager: - Response message for the ListRegionalInventories method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, regionalinventory.ListRegionalInventoriesRequest): - request = regionalinventory.ListRegionalInventoriesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_regional_inventories] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListRegionalInventoriesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def insert_regional_inventory(self, - request: Optional[Union[regionalinventory.InsertRegionalInventoryRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> regionalinventory.RegionalInventory: - r"""Inserts a ``RegionalInventory`` to a given product in your - merchant account. - - Replaces the full ``RegionalInventory`` resource if an entry - with the same - [``region``][google.shopping.merchant.inventories.v1beta.RegionalInventory.region] - already exists for the product. - - It might take up to 30 minutes for the new or updated - ``RegionalInventory`` resource to appear in products. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_inventories_v1beta - - def sample_insert_regional_inventory(): - # Create a client - client = merchant_inventories_v1beta.RegionalInventoryServiceClient() - - # Initialize request argument(s) - regional_inventory = merchant_inventories_v1beta.RegionalInventory() - regional_inventory.region = "region_value" - - request = merchant_inventories_v1beta.InsertRegionalInventoryRequest( - parent="parent_value", - regional_inventory=regional_inventory, - ) - - # Make the request - response = client.insert_regional_inventory(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_inventories_v1beta.types.InsertRegionalInventoryRequest, dict]): - The request object. Request message for the ``InsertRegionalInventory`` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.shopping.merchant_inventories_v1beta.types.RegionalInventory: - Regional inventory information for the product. Represents specific - information like price and availability for a given - product in a specific - [region][google.shopping.merchant.inventories.v1beta.RegionalInventory.region]. - For a list of all accepted attribute values, see the - [regional product inventory data - specification](\ https://support.google.com/merchants/answer/9698880). - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, regionalinventory.InsertRegionalInventoryRequest): - request = regionalinventory.InsertRegionalInventoryRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.insert_regional_inventory] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_regional_inventory(self, - request: Optional[Union[regionalinventory.DeleteRegionalInventoryRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: - r"""Deletes the specified ``RegionalInventory`` resource from the - given product in your merchant account. It might take up to an - hour for the ``RegionalInventory`` to be deleted from the - specific product. Once you have received a successful delete - response, wait for that period before attempting a delete again. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_inventories_v1beta - - def sample_delete_regional_inventory(): - # Create a client - client = merchant_inventories_v1beta.RegionalInventoryServiceClient() - - # Initialize request argument(s) - request = merchant_inventories_v1beta.DeleteRegionalInventoryRequest( - name="name_value", - ) - - # Make the request - client.delete_regional_inventory(request=request) - - Args: - request (Union[google.shopping.merchant_inventories_v1beta.types.DeleteRegionalInventoryRequest, dict]): - The request object. Request message for the ``DeleteRegionalInventory`` - method. - name (str): - Required. The name of the ``RegionalInventory`` resource - to delete. Format: - ``accounts/{account}/products/{product}/regionalInventories/{region}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, regionalinventory.DeleteRegionalInventoryRequest): - request = regionalinventory.DeleteRegionalInventoryRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_regional_inventory] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def __enter__(self) -> "RegionalInventoryServiceClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "RegionalInventoryServiceClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/pagers.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/pagers.py deleted file mode 100644 index e993198f8953..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/pagers.py +++ /dev/null @@ -1,166 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import retry_async as retries_async -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] - OptionalAsyncRetry = Union[retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore - -from google.shopping.merchant_inventories_v1beta.types import regionalinventory - - -class ListRegionalInventoriesPager: - """A pager for iterating through ``list_regional_inventories`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``regional_inventories`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListRegionalInventories`` requests and continue to iterate - through the ``regional_inventories`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., regionalinventory.ListRegionalInventoriesResponse], - request: regionalinventory.ListRegionalInventoriesRequest, - response: regionalinventory.ListRegionalInventoriesResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesRequest): - The initial request object. - response (google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesResponse): - The initial response object. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = regionalinventory.ListRegionalInventoriesRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[regionalinventory.ListRegionalInventoriesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[regionalinventory.RegionalInventory]: - for page in self.pages: - yield from page.regional_inventories - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListRegionalInventoriesAsyncPager: - """A pager for iterating through ``list_regional_inventories`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``regional_inventories`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListRegionalInventories`` requests and continue to iterate - through the ``regional_inventories`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[regionalinventory.ListRegionalInventoriesResponse]], - request: regionalinventory.ListRegionalInventoriesRequest, - response: regionalinventory.ListRegionalInventoriesResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesRequest): - The initial request object. - response (google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesResponse): - The initial response object. - retry (google.api_core.retry.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = regionalinventory.ListRegionalInventoriesRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[regionalinventory.ListRegionalInventoriesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[regionalinventory.RegionalInventory]: - async def async_generator(): - async for page in self.pages: - for response in page.regional_inventories: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/README.rst deleted file mode 100644 index 0b66f48dbd0c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`RegionalInventoryServiceTransport` is the ABC for all transports. -- public child `RegionalInventoryServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `RegionalInventoryServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseRegionalInventoryServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `RegionalInventoryServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/__init__.py deleted file mode 100644 index 8e46523d873a..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import RegionalInventoryServiceTransport -from .grpc import RegionalInventoryServiceGrpcTransport -from .grpc_asyncio import RegionalInventoryServiceGrpcAsyncIOTransport -from .rest import RegionalInventoryServiceRestTransport -from .rest import RegionalInventoryServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[RegionalInventoryServiceTransport]] -_transport_registry['grpc'] = RegionalInventoryServiceGrpcTransport -_transport_registry['grpc_asyncio'] = RegionalInventoryServiceGrpcAsyncIOTransport -_transport_registry['rest'] = RegionalInventoryServiceRestTransport - -__all__ = ( - 'RegionalInventoryServiceTransport', - 'RegionalInventoryServiceGrpcTransport', - 'RegionalInventoryServiceGrpcAsyncIOTransport', - 'RegionalInventoryServiceRestTransport', - 'RegionalInventoryServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/base.py deleted file mode 100644 index 415c38742b8b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/base.py +++ /dev/null @@ -1,183 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.shopping.merchant_inventories_v1beta import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.protobuf import empty_pb2 # type: ignore -from google.shopping.merchant_inventories_v1beta.types import regionalinventory - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class RegionalInventoryServiceTransport(abc.ABC): - """Abstract transport class for RegionalInventoryService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/content', - ) - - DEFAULT_HOST: str = 'merchantapi.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'merchantapi.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - if not hasattr(self, "_ignore_credentials"): - self._ignore_credentials: bool = False - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - @property - def host(self): - return self._host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_regional_inventories: gapic_v1.method.wrap_method( - self.list_regional_inventories, - default_timeout=None, - client_info=client_info, - ), - self.insert_regional_inventory: gapic_v1.method.wrap_method( - self.insert_regional_inventory, - default_timeout=None, - client_info=client_info, - ), - self.delete_regional_inventory: gapic_v1.method.wrap_method( - self.delete_regional_inventory, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def list_regional_inventories(self) -> Callable[ - [regionalinventory.ListRegionalInventoriesRequest], - Union[ - regionalinventory.ListRegionalInventoriesResponse, - Awaitable[regionalinventory.ListRegionalInventoriesResponse] - ]]: - raise NotImplementedError() - - @property - def insert_regional_inventory(self) -> Callable[ - [regionalinventory.InsertRegionalInventoryRequest], - Union[ - regionalinventory.RegionalInventory, - Awaitable[regionalinventory.RegionalInventory] - ]]: - raise NotImplementedError() - - @property - def delete_regional_inventory(self) -> Callable[ - [regionalinventory.DeleteRegionalInventoryRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'RegionalInventoryServiceTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/grpc.py deleted file mode 100644 index 00d8041052a3..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/grpc.py +++ /dev/null @@ -1,420 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import json -import logging as std_logging -import pickle -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.protobuf.json_format import MessageToJson -import google.protobuf.message - -import grpc # type: ignore -import proto # type: ignore - -from google.protobuf import empty_pb2 # type: ignore -from google.shopping.merchant_inventories_v1beta.types import regionalinventory -from .base import RegionalInventoryServiceTransport, DEFAULT_CLIENT_INFO - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - - -class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER - def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) - if logging_enabled: # pragma: NO COVER - request_metadata = client_call_details.metadata - if isinstance(request, proto.Message): - request_payload = type(request).to_json(request) - elif isinstance(request, google.protobuf.message.Message): - request_payload = MessageToJson(request) - else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" - - request_metadata = { - key: value.decode("utf-8") if isinstance(value, bytes) else value - for key, value in request_metadata - } - grpc_request = { - "payload": request_payload, - "requestMethod": "grpc", - "metadata": dict(request_metadata), - } - _LOGGER.debug( - f"Sending request for {client_call_details.method}", - extra = { - "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", - "rpcName": client_call_details.method, - "request": grpc_request, - "metadata": grpc_request["metadata"], - }, - ) - - response = continuation(client_call_details, request) - if logging_enabled: # pragma: NO COVER - response_metadata = response.trailing_metadata() - # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None - result = response.result() - if isinstance(result, proto.Message): - response_payload = type(result).to_json(result) - elif isinstance(result, google.protobuf.message.Message): - response_payload = MessageToJson(result) - else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" - grpc_response = { - "payload": response_payload, - "metadata": metadata, - "status": "OK", - } - _LOGGER.debug( - f"Received response for {client_call_details.method}.", - extra = { - "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class RegionalInventoryServiceGrpcTransport(RegionalInventoryServiceTransport): - """gRPC backend transport for RegionalInventoryService. - - Service to manage regional inventory for products. There is also - separate ``regions`` resource and API to manage regions definitions. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'merchantapi.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'merchantapi.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if a ``channel`` instance is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if a ``channel`` instance is provided. - channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, grpc.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) - - # Wrap messages. This must be done after self._logged_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'merchantapi.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def list_regional_inventories(self) -> Callable[ - [regionalinventory.ListRegionalInventoriesRequest], - regionalinventory.ListRegionalInventoriesResponse]: - r"""Return a callable for the list regional inventories method over gRPC. - - Lists the ``RegionalInventory`` resources for the given product - in your merchant account. The response might contain fewer items - than specified by ``pageSize``. If ``pageToken`` was returned in - previous request, it can be used to obtain additional results. - - ``RegionalInventory`` resources are listed per product for a - given account. - - Returns: - Callable[[~.ListRegionalInventoriesRequest], - ~.ListRegionalInventoriesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_regional_inventories' not in self._stubs: - self._stubs['list_regional_inventories'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.inventories.v1beta.RegionalInventoryService/ListRegionalInventories', - request_serializer=regionalinventory.ListRegionalInventoriesRequest.serialize, - response_deserializer=regionalinventory.ListRegionalInventoriesResponse.deserialize, - ) - return self._stubs['list_regional_inventories'] - - @property - def insert_regional_inventory(self) -> Callable[ - [regionalinventory.InsertRegionalInventoryRequest], - regionalinventory.RegionalInventory]: - r"""Return a callable for the insert regional inventory method over gRPC. - - Inserts a ``RegionalInventory`` to a given product in your - merchant account. - - Replaces the full ``RegionalInventory`` resource if an entry - with the same - [``region``][google.shopping.merchant.inventories.v1beta.RegionalInventory.region] - already exists for the product. - - It might take up to 30 minutes for the new or updated - ``RegionalInventory`` resource to appear in products. - - Returns: - Callable[[~.InsertRegionalInventoryRequest], - ~.RegionalInventory]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'insert_regional_inventory' not in self._stubs: - self._stubs['insert_regional_inventory'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.inventories.v1beta.RegionalInventoryService/InsertRegionalInventory', - request_serializer=regionalinventory.InsertRegionalInventoryRequest.serialize, - response_deserializer=regionalinventory.RegionalInventory.deserialize, - ) - return self._stubs['insert_regional_inventory'] - - @property - def delete_regional_inventory(self) -> Callable[ - [regionalinventory.DeleteRegionalInventoryRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete regional inventory method over gRPC. - - Deletes the specified ``RegionalInventory`` resource from the - given product in your merchant account. It might take up to an - hour for the ``RegionalInventory`` to be deleted from the - specific product. Once you have received a successful delete - response, wait for that period before attempting a delete again. - - Returns: - Callable[[~.DeleteRegionalInventoryRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_regional_inventory' not in self._stubs: - self._stubs['delete_regional_inventory'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.inventories.v1beta.RegionalInventoryService/DeleteRegionalInventory', - request_serializer=regionalinventory.DeleteRegionalInventoryRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_regional_inventory'] - - def close(self): - self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'RegionalInventoryServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/grpc_asyncio.py deleted file mode 100644 index 22f4431d5d53..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,450 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import inspect -import json -import pickle -import logging as std_logging -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import exceptions as core_exceptions -from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.protobuf.json_format import MessageToJson -import google.protobuf.message - -import grpc # type: ignore -import proto # type: ignore -from grpc.experimental import aio # type: ignore - -from google.protobuf import empty_pb2 # type: ignore -from google.shopping.merchant_inventories_v1beta.types import regionalinventory -from .base import RegionalInventoryServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import RegionalInventoryServiceGrpcTransport - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - - -class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER - async def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) - if logging_enabled: # pragma: NO COVER - request_metadata = client_call_details.metadata - if isinstance(request, proto.Message): - request_payload = type(request).to_json(request) - elif isinstance(request, google.protobuf.message.Message): - request_payload = MessageToJson(request) - else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" - - request_metadata = { - key: value.decode("utf-8") if isinstance(value, bytes) else value - for key, value in request_metadata - } - grpc_request = { - "payload": request_payload, - "requestMethod": "grpc", - "metadata": dict(request_metadata), - } - _LOGGER.debug( - f"Sending request for {client_call_details.method}", - extra = { - "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", - "rpcName": str(client_call_details.method), - "request": grpc_request, - "metadata": grpc_request["metadata"], - }, - ) - response = await continuation(client_call_details, request) - if logging_enabled: # pragma: NO COVER - response_metadata = await response.trailing_metadata() - # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None - result = await response - if isinstance(result, proto.Message): - response_payload = type(result).to_json(result) - elif isinstance(result, google.protobuf.message.Message): - response_payload = MessageToJson(result) - else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" - grpc_response = { - "payload": response_payload, - "metadata": metadata, - "status": "OK", - } - _LOGGER.debug( - f"Received response to rpc {client_call_details.method}.", - extra = { - "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class RegionalInventoryServiceGrpcAsyncIOTransport(RegionalInventoryServiceTransport): - """gRPC AsyncIO backend transport for RegionalInventoryService. - - Service to manage regional inventory for products. There is also - separate ``regions`` resource and API to manage regions definitions. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'merchantapi.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'merchantapi.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'merchantapi.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if a ``channel`` instance is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, aio.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - self._interceptor = _LoggingClientAIOInterceptor() - self._grpc_channel._unary_unary_interceptors.append(self._interceptor) - self._logged_channel = self._grpc_channel - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - # Wrap messages. This must be done after self._logged_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def list_regional_inventories(self) -> Callable[ - [regionalinventory.ListRegionalInventoriesRequest], - Awaitable[regionalinventory.ListRegionalInventoriesResponse]]: - r"""Return a callable for the list regional inventories method over gRPC. - - Lists the ``RegionalInventory`` resources for the given product - in your merchant account. The response might contain fewer items - than specified by ``pageSize``. If ``pageToken`` was returned in - previous request, it can be used to obtain additional results. - - ``RegionalInventory`` resources are listed per product for a - given account. - - Returns: - Callable[[~.ListRegionalInventoriesRequest], - Awaitable[~.ListRegionalInventoriesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_regional_inventories' not in self._stubs: - self._stubs['list_regional_inventories'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.inventories.v1beta.RegionalInventoryService/ListRegionalInventories', - request_serializer=regionalinventory.ListRegionalInventoriesRequest.serialize, - response_deserializer=regionalinventory.ListRegionalInventoriesResponse.deserialize, - ) - return self._stubs['list_regional_inventories'] - - @property - def insert_regional_inventory(self) -> Callable[ - [regionalinventory.InsertRegionalInventoryRequest], - Awaitable[regionalinventory.RegionalInventory]]: - r"""Return a callable for the insert regional inventory method over gRPC. - - Inserts a ``RegionalInventory`` to a given product in your - merchant account. - - Replaces the full ``RegionalInventory`` resource if an entry - with the same - [``region``][google.shopping.merchant.inventories.v1beta.RegionalInventory.region] - already exists for the product. - - It might take up to 30 minutes for the new or updated - ``RegionalInventory`` resource to appear in products. - - Returns: - Callable[[~.InsertRegionalInventoryRequest], - Awaitable[~.RegionalInventory]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'insert_regional_inventory' not in self._stubs: - self._stubs['insert_regional_inventory'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.inventories.v1beta.RegionalInventoryService/InsertRegionalInventory', - request_serializer=regionalinventory.InsertRegionalInventoryRequest.serialize, - response_deserializer=regionalinventory.RegionalInventory.deserialize, - ) - return self._stubs['insert_regional_inventory'] - - @property - def delete_regional_inventory(self) -> Callable[ - [regionalinventory.DeleteRegionalInventoryRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete regional inventory method over gRPC. - - Deletes the specified ``RegionalInventory`` resource from the - given product in your merchant account. It might take up to an - hour for the ``RegionalInventory`` to be deleted from the - specific product. Once you have received a successful delete - response, wait for that period before attempting a delete again. - - Returns: - Callable[[~.DeleteRegionalInventoryRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_regional_inventory' not in self._stubs: - self._stubs['delete_regional_inventory'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.inventories.v1beta.RegionalInventoryService/DeleteRegionalInventory', - request_serializer=regionalinventory.DeleteRegionalInventoryRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_regional_inventory'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.list_regional_inventories: self._wrap_method( - self.list_regional_inventories, - default_timeout=None, - client_info=client_info, - ), - self.insert_regional_inventory: self._wrap_method( - self.insert_regional_inventory, - default_timeout=None, - client_info=client_info, - ), - self.delete_regional_inventory: self._wrap_method( - self.delete_regional_inventory, - default_timeout=None, - client_info=client_info, - ), - } - - def _wrap_method(self, func, *args, **kwargs): - if self._wrap_with_kind: # pragma: NO COVER - kwargs["kind"] = self.kind - return gapic_v1.method_async.wrap_method(func, *args, **kwargs) - - def close(self): - return self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc_asyncio" - - -__all__ = ( - 'RegionalInventoryServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/rest.py deleted file mode 100644 index cb2352f27d10..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/rest.py +++ /dev/null @@ -1,598 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -from google.protobuf import json_format - -from requests import __version__ as requests_version -import dataclasses -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - - -from google.protobuf import empty_pb2 # type: ignore -from google.shopping.merchant_inventories_v1beta.types import regionalinventory - - -from .rest_base import _BaseRegionalInventoryServiceRestTransport -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = logging.getLogger(__name__) - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=f"requests@{requests_version}", -) - - -class RegionalInventoryServiceRestInterceptor: - """Interceptor for RegionalInventoryService. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the RegionalInventoryServiceRestTransport. - - .. code-block:: python - class MyCustomRegionalInventoryServiceInterceptor(RegionalInventoryServiceRestInterceptor): - def pre_delete_regional_inventory(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_insert_regional_inventory(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_insert_regional_inventory(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_regional_inventories(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_regional_inventories(self, response): - logging.log(f"Received response: {response}") - return response - - transport = RegionalInventoryServiceRestTransport(interceptor=MyCustomRegionalInventoryServiceInterceptor()) - client = RegionalInventoryServiceClient(transport=transport) - - - """ - def pre_delete_regional_inventory(self, request: regionalinventory.DeleteRegionalInventoryRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regionalinventory.DeleteRegionalInventoryRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_regional_inventory - - Override in a subclass to manipulate the request or metadata - before they are sent to the RegionalInventoryService server. - """ - return request, metadata - - def pre_insert_regional_inventory(self, request: regionalinventory.InsertRegionalInventoryRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regionalinventory.InsertRegionalInventoryRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for insert_regional_inventory - - Override in a subclass to manipulate the request or metadata - before they are sent to the RegionalInventoryService server. - """ - return request, metadata - - def post_insert_regional_inventory(self, response: regionalinventory.RegionalInventory) -> regionalinventory.RegionalInventory: - """Post-rpc interceptor for insert_regional_inventory - - Override in a subclass to manipulate the response - after it is returned by the RegionalInventoryService server but before - it is returned to user code. - """ - return response - - def pre_list_regional_inventories(self, request: regionalinventory.ListRegionalInventoriesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regionalinventory.ListRegionalInventoriesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_regional_inventories - - Override in a subclass to manipulate the request or metadata - before they are sent to the RegionalInventoryService server. - """ - return request, metadata - - def post_list_regional_inventories(self, response: regionalinventory.ListRegionalInventoriesResponse) -> regionalinventory.ListRegionalInventoriesResponse: - """Post-rpc interceptor for list_regional_inventories - - Override in a subclass to manipulate the response - after it is returned by the RegionalInventoryService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class RegionalInventoryServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: RegionalInventoryServiceRestInterceptor - - -class RegionalInventoryServiceRestTransport(_BaseRegionalInventoryServiceRestTransport): - """REST backend synchronous transport for RegionalInventoryService. - - Service to manage regional inventory for products. There is also - separate ``regions`` resource and API to manage regions definitions. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - """ - - def __init__(self, *, - host: str = 'merchantapi.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[RegionalInventoryServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'merchantapi.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - url_scheme=url_scheme, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or RegionalInventoryServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _DeleteRegionalInventory(_BaseRegionalInventoryServiceRestTransport._BaseDeleteRegionalInventory, RegionalInventoryServiceRestStub): - def __hash__(self): - return hash("RegionalInventoryServiceRestTransport.DeleteRegionalInventory") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: regionalinventory.DeleteRegionalInventoryRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ): - r"""Call the delete regional inventory method over HTTP. - - Args: - request (~.regionalinventory.DeleteRegionalInventoryRequest): - The request object. Request message for the ``DeleteRegionalInventory`` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - - http_options = _BaseRegionalInventoryServiceRestTransport._BaseDeleteRegionalInventory._get_http_options() - - request, metadata = self._interceptor.pre_delete_regional_inventory(request, metadata) - transcoded_request = _BaseRegionalInventoryServiceRestTransport._BaseDeleteRegionalInventory._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseRegionalInventoryServiceRestTransport._BaseDeleteRegionalInventory._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.shopping.merchant.inventories_v1beta.RegionalInventoryServiceClient.DeleteRegionalInventory", - extra = { - "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", - "rpcName": "DeleteRegionalInventory", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = RegionalInventoryServiceRestTransport._DeleteRegionalInventory._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _InsertRegionalInventory(_BaseRegionalInventoryServiceRestTransport._BaseInsertRegionalInventory, RegionalInventoryServiceRestStub): - def __hash__(self): - return hash("RegionalInventoryServiceRestTransport.InsertRegionalInventory") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: regionalinventory.InsertRegionalInventoryRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> regionalinventory.RegionalInventory: - r"""Call the insert regional inventory method over HTTP. - - Args: - request (~.regionalinventory.InsertRegionalInventoryRequest): - The request object. Request message for the ``InsertRegionalInventory`` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.regionalinventory.RegionalInventory: - Regional inventory information for the product. - Represents specific information like price and - availability for a given product in a specific - [``region``][google.shopping.merchant.inventories.v1beta.RegionalInventory.region]. - For a list of all accepted attribute values, see the - `regional product inventory data - specification `__. - - """ - - http_options = _BaseRegionalInventoryServiceRestTransport._BaseInsertRegionalInventory._get_http_options() - - request, metadata = self._interceptor.pre_insert_regional_inventory(request, metadata) - transcoded_request = _BaseRegionalInventoryServiceRestTransport._BaseInsertRegionalInventory._get_transcoded_request(http_options, request) - - body = _BaseRegionalInventoryServiceRestTransport._BaseInsertRegionalInventory._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseRegionalInventoryServiceRestTransport._BaseInsertRegionalInventory._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.shopping.merchant.inventories_v1beta.RegionalInventoryServiceClient.InsertRegionalInventory", - extra = { - "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", - "rpcName": "InsertRegionalInventory", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = RegionalInventoryServiceRestTransport._InsertRegionalInventory._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = regionalinventory.RegionalInventory() - pb_resp = regionalinventory.RegionalInventory.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_insert_regional_inventory(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = regionalinventory.RegionalInventory.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.shopping.merchant.inventories_v1beta.RegionalInventoryServiceClient.insert_regional_inventory", - extra = { - "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", - "rpcName": "InsertRegionalInventory", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListRegionalInventories(_BaseRegionalInventoryServiceRestTransport._BaseListRegionalInventories, RegionalInventoryServiceRestStub): - def __hash__(self): - return hash("RegionalInventoryServiceRestTransport.ListRegionalInventories") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: regionalinventory.ListRegionalInventoriesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> regionalinventory.ListRegionalInventoriesResponse: - r"""Call the list regional inventories method over HTTP. - - Args: - request (~.regionalinventory.ListRegionalInventoriesRequest): - The request object. Request message for the ``ListRegionalInventories`` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.regionalinventory.ListRegionalInventoriesResponse: - Response message for the ``ListRegionalInventories`` - method. - - """ - - http_options = _BaseRegionalInventoryServiceRestTransport._BaseListRegionalInventories._get_http_options() - - request, metadata = self._interceptor.pre_list_regional_inventories(request, metadata) - transcoded_request = _BaseRegionalInventoryServiceRestTransport._BaseListRegionalInventories._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseRegionalInventoryServiceRestTransport._BaseListRegionalInventories._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.shopping.merchant.inventories_v1beta.RegionalInventoryServiceClient.ListRegionalInventories", - extra = { - "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", - "rpcName": "ListRegionalInventories", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = RegionalInventoryServiceRestTransport._ListRegionalInventories._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = regionalinventory.ListRegionalInventoriesResponse() - pb_resp = regionalinventory.ListRegionalInventoriesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_regional_inventories(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = regionalinventory.ListRegionalInventoriesResponse.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.shopping.merchant.inventories_v1beta.RegionalInventoryServiceClient.list_regional_inventories", - extra = { - "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", - "rpcName": "ListRegionalInventories", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def delete_regional_inventory(self) -> Callable[ - [regionalinventory.DeleteRegionalInventoryRequest], - empty_pb2.Empty]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteRegionalInventory(self._session, self._host, self._interceptor) # type: ignore - - @property - def insert_regional_inventory(self) -> Callable[ - [regionalinventory.InsertRegionalInventoryRequest], - regionalinventory.RegionalInventory]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._InsertRegionalInventory(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_regional_inventories(self) -> Callable[ - [regionalinventory.ListRegionalInventoriesRequest], - regionalinventory.ListRegionalInventoriesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListRegionalInventories(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'RegionalInventoryServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/rest_base.py deleted file mode 100644 index c2a7417ff9c0..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/rest_base.py +++ /dev/null @@ -1,213 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import json # type: ignore -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from .base import RegionalInventoryServiceTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.protobuf import empty_pb2 # type: ignore -from google.shopping.merchant_inventories_v1beta.types import regionalinventory - - -class _BaseRegionalInventoryServiceRestTransport(RegionalInventoryServiceTransport): - """Base REST backend transport for RegionalInventoryService. - - Note: This class is not meant to be used directly. Use its sync and - async sub-classes instead. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - """ - - def __init__(self, *, - host: str = 'merchantapi.googleapis.com', - credentials: Optional[Any] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - Args: - host (Optional[str]): - The hostname to connect to (default: 'merchantapi.googleapis.com'). - credentials (Optional[Any]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - - class _BaseDeleteRegionalInventory: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/inventories/v1beta/{name=accounts/*/products/*/regionalInventories/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = regionalinventory.DeleteRegionalInventoryRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseRegionalInventoryServiceRestTransport._BaseDeleteRegionalInventory._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseInsertRegionalInventory: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/inventories/v1beta/{parent=accounts/*/products/*}/regionalInventories:insert', - 'body': 'regional_inventory', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = regionalinventory.InsertRegionalInventoryRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseRegionalInventoryServiceRestTransport._BaseInsertRegionalInventory._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListRegionalInventories: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/inventories/v1beta/{parent=accounts/*/products/*}/regionalInventories', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = regionalinventory.ListRegionalInventoriesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseRegionalInventoryServiceRestTransport._BaseListRegionalInventories._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseRegionalInventoryServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/__init__.py deleted file mode 100644 index e9443375bc16..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/__init__.py +++ /dev/null @@ -1,42 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .localinventory import ( - DeleteLocalInventoryRequest, - InsertLocalInventoryRequest, - ListLocalInventoriesRequest, - ListLocalInventoriesResponse, - LocalInventory, -) -from .regionalinventory import ( - DeleteRegionalInventoryRequest, - InsertRegionalInventoryRequest, - ListRegionalInventoriesRequest, - ListRegionalInventoriesResponse, - RegionalInventory, -) - -__all__ = ( - 'DeleteLocalInventoryRequest', - 'InsertLocalInventoryRequest', - 'ListLocalInventoriesRequest', - 'ListLocalInventoriesResponse', - 'LocalInventory', - 'DeleteRegionalInventoryRequest', - 'InsertRegionalInventoryRequest', - 'ListRegionalInventoriesRequest', - 'ListRegionalInventoriesResponse', - 'RegionalInventory', -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/localinventory.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/localinventory.py deleted file mode 100644 index ce4ed8566637..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/localinventory.py +++ /dev/null @@ -1,281 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.shopping.type.types import types -from google.type import interval_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.shopping.merchant.inventories.v1beta', - manifest={ - 'LocalInventory', - 'ListLocalInventoriesRequest', - 'ListLocalInventoriesResponse', - 'InsertLocalInventoryRequest', - 'DeleteLocalInventoryRequest', - }, -) - - -class LocalInventory(proto.Message): - r"""Local inventory information for the product. Represents in-store - information for a specific product at the store specified by - [``storeCode``][google.shopping.merchant.inventories.v1beta.LocalInventory.store_code]. - For a list of all accepted attribute values, see the `local product - inventory data - specification `__. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - Output only. The name of the ``LocalInventory`` resource. - Format: - ``accounts/{account}/products/{product}/localInventories/{store_code}`` - account (int): - Output only. The account that owns the - product. This field will be ignored if set by - the client. - store_code (str): - Required. Immutable. Store code (the store ID from your - Business Profile) of the physical store the product is sold - in. See the `Local product inventory data - specification `__ - for more information. - price (google.shopping.type.types.Price): - Price of the product at this store. - sale_price (google.shopping.type.types.Price): - Sale price of the product at this store. Mandatory if - [``salePriceEffectiveDate``][google.shopping.merchant.inventories.v1beta.LocalInventory.sale_price_effective_date] - is defined. - sale_price_effective_date (google.type.interval_pb2.Interval): - The ``TimePeriod`` of the sale at this store. - availability (str): - Availability of the product at this store. For accepted - attribute values, see the `local product inventory data - specification `__ - - This field is a member of `oneof`_ ``_availability``. - quantity (int): - Quantity of the product available at this - store. Must be greater than or equal to zero. - - This field is a member of `oneof`_ ``_quantity``. - pickup_method (str): - Supported pickup method for this product. Unless the value - is ``"not supported"``, this field must be submitted - together with ``pickupSla``. For accepted attribute values, - see the `local product inventory data - specification `__ - - This field is a member of `oneof`_ ``_pickup_method``. - pickup_sla (str): - Relative time period from the order date for an order for - this product, from this store, to be ready for pickup. Must - be submitted with ``pickupMethod``. For accepted attribute - values, see the `local product inventory data - specification `__ - - This field is a member of `oneof`_ ``_pickup_sla``. - instore_product_location (str): - Location of the product inside the store. - Maximum length is 20 bytes. - - This field is a member of `oneof`_ ``_instore_product_location``. - custom_attributes (MutableSequence[google.shopping.type.types.CustomAttribute]): - A list of custom (merchant-provided) attributes. You can - also use ``CustomAttribute`` to submit any attribute of the - data specification in its generic form. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - account: int = proto.Field( - proto.INT64, - number=2, - ) - store_code: str = proto.Field( - proto.STRING, - number=3, - ) - price: types.Price = proto.Field( - proto.MESSAGE, - number=4, - message=types.Price, - ) - sale_price: types.Price = proto.Field( - proto.MESSAGE, - number=5, - message=types.Price, - ) - sale_price_effective_date: interval_pb2.Interval = proto.Field( - proto.MESSAGE, - number=6, - message=interval_pb2.Interval, - ) - availability: str = proto.Field( - proto.STRING, - number=7, - optional=True, - ) - quantity: int = proto.Field( - proto.INT64, - number=8, - optional=True, - ) - pickup_method: str = proto.Field( - proto.STRING, - number=9, - optional=True, - ) - pickup_sla: str = proto.Field( - proto.STRING, - number=10, - optional=True, - ) - instore_product_location: str = proto.Field( - proto.STRING, - number=11, - optional=True, - ) - custom_attributes: MutableSequence[types.CustomAttribute] = proto.RepeatedField( - proto.MESSAGE, - number=12, - message=types.CustomAttribute, - ) - - -class ListLocalInventoriesRequest(proto.Message): - r"""Request message for the ``ListLocalInventories`` method. - - Attributes: - parent (str): - Required. The ``name`` of the parent product to list local - inventories for. Format: - ``accounts/{account}/products/{product}`` - page_size (int): - The maximum number of ``LocalInventory`` resources for the - given product to return. The service returns fewer than this - value if the number of inventories for the given product is - less that than the ``pageSize``. The default value is 25000. - The maximum value is 25000; If a value higher than the - maximum is specified, then the ``pageSize`` will default to - the maximum - page_token (str): - A page token, received from a previous - ``ListLocalInventories`` call. Provide the page token to - retrieve the subsequent page. - - When paginating, all other parameters provided to - ``ListLocalInventories`` must match the call that provided - the page token. The token returned as - [nextPageToken][google.shopping.merchant.inventories.v1beta.ListLocalInventoriesResponse.next_page_token] - in the response to the previous request. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListLocalInventoriesResponse(proto.Message): - r"""Response message for the ``ListLocalInventories`` method. - - Attributes: - local_inventories (MutableSequence[google.shopping.merchant_inventories_v1beta.types.LocalInventory]): - The ``LocalInventory`` resources for the given product from - the specified account. - next_page_token (str): - A token, which can be sent as ``pageToken`` to retrieve the - next page. If this field is omitted, there are no subsequent - pages. - """ - - @property - def raw_page(self): - return self - - local_inventories: MutableSequence['LocalInventory'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='LocalInventory', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class InsertLocalInventoryRequest(proto.Message): - r"""Request message for the ``InsertLocalInventory`` method. - - Attributes: - parent (str): - Required. The account and product where this inventory will - be inserted. Format: - ``accounts/{account}/products/{product}`` - local_inventory (google.shopping.merchant_inventories_v1beta.types.LocalInventory): - Required. Local inventory information of the product. If the - product already has a ``LocalInventory`` resource for the - same ``storeCode``, full replacement of the - ``LocalInventory`` resource is performed. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - local_inventory: 'LocalInventory' = proto.Field( - proto.MESSAGE, - number=2, - message='LocalInventory', - ) - - -class DeleteLocalInventoryRequest(proto.Message): - r"""Request message for the ``DeleteLocalInventory`` method. - - Attributes: - name (str): - Required. The name of the local inventory for the given - product to delete. Format: - ``accounts/{account}/products/{product}/localInventories/{store_code}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/regionalinventory.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/regionalinventory.py deleted file mode 100644 index d5a18381605f..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/regionalinventory.py +++ /dev/null @@ -1,236 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.shopping.type.types import types -from google.type import interval_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.shopping.merchant.inventories.v1beta', - manifest={ - 'RegionalInventory', - 'ListRegionalInventoriesRequest', - 'ListRegionalInventoriesResponse', - 'InsertRegionalInventoryRequest', - 'DeleteRegionalInventoryRequest', - }, -) - - -class RegionalInventory(proto.Message): - r"""Regional inventory information for the product. Represents specific - information like price and availability for a given product in a - specific - [``region``][google.shopping.merchant.inventories.v1beta.RegionalInventory.region]. - For a list of all accepted attribute values, see the `regional - product inventory data - specification `__. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - Output only. The name of the ``RegionalInventory`` resource. - Format: - ``{regional_inventory.name=accounts/{account}/products/{product}/regionalInventories/{region}`` - account (int): - Output only. The account that owns the - product. This field will be ignored if set by - the client. - region (str): - Required. Immutable. ID of the region for this - ``RegionalInventory`` resource. See the `Regional - availability and - pricing `__ - for more details. - price (google.shopping.type.types.Price): - Price of the product in this region. - sale_price (google.shopping.type.types.Price): - Sale price of the product in this region. Mandatory if - [``salePriceEffectiveDate``][google.shopping.merchant.inventories.v1beta.RegionalInventory.sale_price_effective_date] - is defined. - sale_price_effective_date (google.type.interval_pb2.Interval): - The ``TimePeriod`` of the sale price in this region. - availability (str): - Availability of the product in this region. For accepted - attribute values, see the `regional product inventory data - specification `__ - - This field is a member of `oneof`_ ``_availability``. - custom_attributes (MutableSequence[google.shopping.type.types.CustomAttribute]): - A list of custom (merchant-provided) attributes. You can - also use ``CustomAttribute`` to submit any attribute of the - data specification in its generic form. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - account: int = proto.Field( - proto.INT64, - number=2, - ) - region: str = proto.Field( - proto.STRING, - number=3, - ) - price: types.Price = proto.Field( - proto.MESSAGE, - number=4, - message=types.Price, - ) - sale_price: types.Price = proto.Field( - proto.MESSAGE, - number=5, - message=types.Price, - ) - sale_price_effective_date: interval_pb2.Interval = proto.Field( - proto.MESSAGE, - number=6, - message=interval_pb2.Interval, - ) - availability: str = proto.Field( - proto.STRING, - number=7, - optional=True, - ) - custom_attributes: MutableSequence[types.CustomAttribute] = proto.RepeatedField( - proto.MESSAGE, - number=8, - message=types.CustomAttribute, - ) - - -class ListRegionalInventoriesRequest(proto.Message): - r"""Request message for the ``ListRegionalInventories`` method. - - Attributes: - parent (str): - Required. The ``name`` of the parent product to list - ``RegionalInventory`` resources for. Format: - ``accounts/{account}/products/{product}`` - page_size (int): - The maximum number of ``RegionalInventory`` resources for - the given product to return. The service returns fewer than - this value if the number of inventories for the given - product is less that than the ``pageSize``. The default - value is 25000. The maximum value is 100000; If a value - higher than the maximum is specified, then the ``pageSize`` - will default to the maximum. - page_token (str): - A page token, received from a previous - ``ListRegionalInventories`` call. Provide the page token to - retrieve the subsequent page. - - When paginating, all other parameters provided to - ``ListRegionalInventories`` must match the call that - provided the page token. The token returned as - [nextPageToken][google.shopping.merchant.inventories.v1beta.ListRegionalInventoriesResponse.next_page_token] - in the response to the previous request. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListRegionalInventoriesResponse(proto.Message): - r"""Response message for the ``ListRegionalInventories`` method. - - Attributes: - regional_inventories (MutableSequence[google.shopping.merchant_inventories_v1beta.types.RegionalInventory]): - The ``RegionalInventory`` resources for the given product - from the specified account. - next_page_token (str): - A token, which can be sent as ``pageToken`` to retrieve the - next page. If this field is omitted, there are no subsequent - pages. - """ - - @property - def raw_page(self): - return self - - regional_inventories: MutableSequence['RegionalInventory'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='RegionalInventory', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class InsertRegionalInventoryRequest(proto.Message): - r"""Request message for the ``InsertRegionalInventory`` method. - - Attributes: - parent (str): - Required. The account and product where this inventory will - be inserted. Format: - ``accounts/{account}/products/{product}`` - regional_inventory (google.shopping.merchant_inventories_v1beta.types.RegionalInventory): - Required. Regional inventory information to add to the - product. If the product already has a ``RegionalInventory`` - resource for the same ``region``, full replacement of the - ``RegionalInventory`` resource is performed. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - regional_inventory: 'RegionalInventory' = proto.Field( - proto.MESSAGE, - number=2, - message='RegionalInventory', - ) - - -class DeleteRegionalInventoryRequest(proto.Message): - r"""Request message for the ``DeleteRegionalInventory`` method. - - Attributes: - name (str): - Required. The name of the ``RegionalInventory`` resource to - delete. Format: - ``accounts/{account}/products/{product}/regionalInventories/{region}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/mypy.ini b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/noxfile.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/noxfile.py deleted file mode 100644 index 103e86007356..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/noxfile.py +++ /dev/null @@ -1,280 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", - "3.12", - "3.13", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = 'google-shopping-merchant-inventories' - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.13" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "prerelease_deps", -] - -@nox.session(python=ALL_PYTHON) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def unit(session, protobuf_implementation): - """Run the unit test suite.""" - - 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+") - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") - - # 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") - - session.run( - 'py.test', - '--quiet', - '--cov=google/shopping/merchant_inventories_v1beta/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - -@nox.session(python=ALL_PYTHON[-1]) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def prerelease_deps(session, protobuf_implementation): - """Run the unit test suite against pre-release versions of dependencies.""" - - 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 test environment dependencies - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - - # Install the package without dependencies - session.install('-e', '.', '--no-deps') - - # We test the minimum dependency versions using the minimum Python - # version so the lowest python runtime that we test has a corresponding constraints - # file, located at `testing/constraints--.txt`, which contains all of the - # 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 - ) - ] - - session.install(*constraints_deps) - - prerel_deps = [ - "googleapis-common-protos", - "google-api-core", - "google-auth", - # Exclude grpcio!=1.67.0rc1 which does not support python 3.13 - "grpcio!=1.67.0rc1", - "grpcio-status", - "protobuf", - "proto-plus", - ] - - for dep in prerel_deps: - session.install("--pre", "--no-deps", "--upgrade", dep) - - # Remaining dependencies - other_deps = [ - "requests", - ] - session.install(*other_deps) - - # Print out prerelease package versions - - session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") - session.run("python", "-c", "import google.auth; print(google.auth.__version__)") - session.run("python", "-c", "import grpc; print(grpc.__version__)") - session.run( - "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" - ) - session.run( - "python", "-c", "import proto; print(proto.__version__)" - ) - - session.run( - 'py.test', - '--quiet', - '--cov=google/shopping/merchant_inventories_v1beta/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - - -@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=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 docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==7.0.1", "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=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", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_async.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_async.py deleted file mode 100644 index c2b887fa74b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteLocalInventory -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-inventories - - -# [START merchantapi_v1beta_generated_LocalInventoryService_DeleteLocalInventory_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.shopping import merchant_inventories_v1beta - - -async def sample_delete_local_inventory(): - # Create a client - client = merchant_inventories_v1beta.LocalInventoryServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_inventories_v1beta.DeleteLocalInventoryRequest( - name="name_value", - ) - - # Make the request - await client.delete_local_inventory(request=request) - - -# [END merchantapi_v1beta_generated_LocalInventoryService_DeleteLocalInventory_async] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_sync.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_sync.py deleted file mode 100644 index f7987bde6168..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteLocalInventory -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-inventories - - -# [START merchantapi_v1beta_generated_LocalInventoryService_DeleteLocalInventory_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.shopping import merchant_inventories_v1beta - - -def sample_delete_local_inventory(): - # Create a client - client = merchant_inventories_v1beta.LocalInventoryServiceClient() - - # Initialize request argument(s) - request = merchant_inventories_v1beta.DeleteLocalInventoryRequest( - name="name_value", - ) - - # Make the request - client.delete_local_inventory(request=request) - - -# [END merchantapi_v1beta_generated_LocalInventoryService_DeleteLocalInventory_sync] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_async.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_async.py deleted file mode 100644 index 8fd3fb0cd942..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for InsertLocalInventory -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-inventories - - -# [START merchantapi_v1beta_generated_LocalInventoryService_InsertLocalInventory_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.shopping import merchant_inventories_v1beta - - -async def sample_insert_local_inventory(): - # Create a client - client = merchant_inventories_v1beta.LocalInventoryServiceAsyncClient() - - # Initialize request argument(s) - local_inventory = merchant_inventories_v1beta.LocalInventory() - local_inventory.store_code = "store_code_value" - - request = merchant_inventories_v1beta.InsertLocalInventoryRequest( - parent="parent_value", - local_inventory=local_inventory, - ) - - # Make the request - response = await client.insert_local_inventory(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_LocalInventoryService_InsertLocalInventory_async] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_sync.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_sync.py deleted file mode 100644 index 27ff97c03bb3..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for InsertLocalInventory -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-inventories - - -# [START merchantapi_v1beta_generated_LocalInventoryService_InsertLocalInventory_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.shopping import merchant_inventories_v1beta - - -def sample_insert_local_inventory(): - # Create a client - client = merchant_inventories_v1beta.LocalInventoryServiceClient() - - # Initialize request argument(s) - local_inventory = merchant_inventories_v1beta.LocalInventory() - local_inventory.store_code = "store_code_value" - - request = merchant_inventories_v1beta.InsertLocalInventoryRequest( - parent="parent_value", - local_inventory=local_inventory, - ) - - # Make the request - response = client.insert_local_inventory(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_LocalInventoryService_InsertLocalInventory_sync] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_async.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_async.py deleted file mode 100644 index 0401ce499705..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListLocalInventories -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-inventories - - -# [START merchantapi_v1beta_generated_LocalInventoryService_ListLocalInventories_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.shopping import merchant_inventories_v1beta - - -async def sample_list_local_inventories(): - # Create a client - client = merchant_inventories_v1beta.LocalInventoryServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_inventories_v1beta.ListLocalInventoriesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_local_inventories(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_LocalInventoryService_ListLocalInventories_async] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_sync.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_sync.py deleted file mode 100644 index f6a35200c618..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListLocalInventories -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-inventories - - -# [START merchantapi_v1beta_generated_LocalInventoryService_ListLocalInventories_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.shopping import merchant_inventories_v1beta - - -def sample_list_local_inventories(): - # Create a client - client = merchant_inventories_v1beta.LocalInventoryServiceClient() - - # Initialize request argument(s) - request = merchant_inventories_v1beta.ListLocalInventoriesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_local_inventories(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_LocalInventoryService_ListLocalInventories_sync] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_async.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_async.py deleted file mode 100644 index baecc3b1f705..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteRegionalInventory -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-inventories - - -# [START merchantapi_v1beta_generated_RegionalInventoryService_DeleteRegionalInventory_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.shopping import merchant_inventories_v1beta - - -async def sample_delete_regional_inventory(): - # Create a client - client = merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_inventories_v1beta.DeleteRegionalInventoryRequest( - name="name_value", - ) - - # Make the request - await client.delete_regional_inventory(request=request) - - -# [END merchantapi_v1beta_generated_RegionalInventoryService_DeleteRegionalInventory_async] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_sync.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_sync.py deleted file mode 100644 index 785fea0a8519..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteRegionalInventory -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-inventories - - -# [START merchantapi_v1beta_generated_RegionalInventoryService_DeleteRegionalInventory_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.shopping import merchant_inventories_v1beta - - -def sample_delete_regional_inventory(): - # Create a client - client = merchant_inventories_v1beta.RegionalInventoryServiceClient() - - # Initialize request argument(s) - request = merchant_inventories_v1beta.DeleteRegionalInventoryRequest( - name="name_value", - ) - - # Make the request - client.delete_regional_inventory(request=request) - - -# [END merchantapi_v1beta_generated_RegionalInventoryService_DeleteRegionalInventory_sync] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_async.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_async.py deleted file mode 100644 index 0cfcfe596291..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for InsertRegionalInventory -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-inventories - - -# [START merchantapi_v1beta_generated_RegionalInventoryService_InsertRegionalInventory_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.shopping import merchant_inventories_v1beta - - -async def sample_insert_regional_inventory(): - # Create a client - client = merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient() - - # Initialize request argument(s) - regional_inventory = merchant_inventories_v1beta.RegionalInventory() - regional_inventory.region = "region_value" - - request = merchant_inventories_v1beta.InsertRegionalInventoryRequest( - parent="parent_value", - regional_inventory=regional_inventory, - ) - - # Make the request - response = await client.insert_regional_inventory(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_RegionalInventoryService_InsertRegionalInventory_async] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_sync.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_sync.py deleted file mode 100644 index 04912cc719d2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for InsertRegionalInventory -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-inventories - - -# [START merchantapi_v1beta_generated_RegionalInventoryService_InsertRegionalInventory_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.shopping import merchant_inventories_v1beta - - -def sample_insert_regional_inventory(): - # Create a client - client = merchant_inventories_v1beta.RegionalInventoryServiceClient() - - # Initialize request argument(s) - regional_inventory = merchant_inventories_v1beta.RegionalInventory() - regional_inventory.region = "region_value" - - request = merchant_inventories_v1beta.InsertRegionalInventoryRequest( - parent="parent_value", - regional_inventory=regional_inventory, - ) - - # Make the request - response = client.insert_regional_inventory(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_RegionalInventoryService_InsertRegionalInventory_sync] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_async.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_async.py deleted file mode 100644 index ea04c9082f2a..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListRegionalInventories -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-inventories - - -# [START merchantapi_v1beta_generated_RegionalInventoryService_ListRegionalInventories_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.shopping import merchant_inventories_v1beta - - -async def sample_list_regional_inventories(): - # Create a client - client = merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_inventories_v1beta.ListRegionalInventoriesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_regional_inventories(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_RegionalInventoryService_ListRegionalInventories_async] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_sync.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_sync.py deleted file mode 100644 index 6136c4ff08ba..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListRegionalInventories -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-inventories - - -# [START merchantapi_v1beta_generated_RegionalInventoryService_ListRegionalInventories_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.shopping import merchant_inventories_v1beta - - -def sample_list_regional_inventories(): - # Create a client - client = merchant_inventories_v1beta.RegionalInventoryServiceClient() - - # Initialize request argument(s) - request = merchant_inventories_v1beta.ListRegionalInventoriesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_regional_inventories(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_RegionalInventoryService_ListRegionalInventories_sync] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.inventories.v1beta.json b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.inventories.v1beta.json deleted file mode 100644 index 73ddfcf94070..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.inventories.v1beta.json +++ /dev/null @@ -1,953 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.shopping.merchant.inventories.v1beta", - "version": "v1beta" - } - ], - "language": "PYTHON", - "name": "google-shopping-merchant-inventories", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceAsyncClient", - "shortName": "LocalInventoryServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceAsyncClient.delete_local_inventory", - "method": { - "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService.DeleteLocalInventory", - "service": { - "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", - "shortName": "LocalInventoryService" - }, - "shortName": "DeleteLocalInventory" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_inventories_v1beta.types.DeleteLocalInventoryRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "shortName": "delete_local_inventory" - }, - "description": "Sample for DeleteLocalInventory", - "file": "merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_LocalInventoryService_DeleteLocalInventory_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceClient", - "shortName": "LocalInventoryServiceClient" - }, - "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceClient.delete_local_inventory", - "method": { - "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService.DeleteLocalInventory", - "service": { - "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", - "shortName": "LocalInventoryService" - }, - "shortName": "DeleteLocalInventory" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_inventories_v1beta.types.DeleteLocalInventoryRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "shortName": "delete_local_inventory" - }, - "description": "Sample for DeleteLocalInventory", - "file": "merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_LocalInventoryService_DeleteLocalInventory_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceAsyncClient", - "shortName": "LocalInventoryServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceAsyncClient.insert_local_inventory", - "method": { - "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService.InsertLocalInventory", - "service": { - "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", - "shortName": "LocalInventoryService" - }, - "shortName": "InsertLocalInventory" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_inventories_v1beta.types.InsertLocalInventoryRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.shopping.merchant_inventories_v1beta.types.LocalInventory", - "shortName": "insert_local_inventory" - }, - "description": "Sample for InsertLocalInventory", - "file": "merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_LocalInventoryService_InsertLocalInventory_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceClient", - "shortName": "LocalInventoryServiceClient" - }, - "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceClient.insert_local_inventory", - "method": { - "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService.InsertLocalInventory", - "service": { - "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", - "shortName": "LocalInventoryService" - }, - "shortName": "InsertLocalInventory" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_inventories_v1beta.types.InsertLocalInventoryRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.shopping.merchant_inventories_v1beta.types.LocalInventory", - "shortName": "insert_local_inventory" - }, - "description": "Sample for InsertLocalInventory", - "file": "merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_LocalInventoryService_InsertLocalInventory_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceAsyncClient", - "shortName": "LocalInventoryServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceAsyncClient.list_local_inventories", - "method": { - "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService.ListLocalInventories", - "service": { - "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", - "shortName": "LocalInventoryService" - }, - "shortName": "ListLocalInventories" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.shopping.merchant_inventories_v1beta.services.local_inventory_service.pagers.ListLocalInventoriesAsyncPager", - "shortName": "list_local_inventories" - }, - "description": "Sample for ListLocalInventories", - "file": "merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_LocalInventoryService_ListLocalInventories_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceClient", - "shortName": "LocalInventoryServiceClient" - }, - "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceClient.list_local_inventories", - "method": { - "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService.ListLocalInventories", - "service": { - "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", - "shortName": "LocalInventoryService" - }, - "shortName": "ListLocalInventories" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.shopping.merchant_inventories_v1beta.services.local_inventory_service.pagers.ListLocalInventoriesPager", - "shortName": "list_local_inventories" - }, - "description": "Sample for ListLocalInventories", - "file": "merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_LocalInventoryService_ListLocalInventories_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient", - "shortName": "RegionalInventoryServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient.delete_regional_inventory", - "method": { - "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService.DeleteRegionalInventory", - "service": { - "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", - "shortName": "RegionalInventoryService" - }, - "shortName": "DeleteRegionalInventory" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_inventories_v1beta.types.DeleteRegionalInventoryRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "shortName": "delete_regional_inventory" - }, - "description": "Sample for DeleteRegionalInventory", - "file": "merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_RegionalInventoryService_DeleteRegionalInventory_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceClient", - "shortName": "RegionalInventoryServiceClient" - }, - "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceClient.delete_regional_inventory", - "method": { - "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService.DeleteRegionalInventory", - "service": { - "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", - "shortName": "RegionalInventoryService" - }, - "shortName": "DeleteRegionalInventory" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_inventories_v1beta.types.DeleteRegionalInventoryRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "shortName": "delete_regional_inventory" - }, - "description": "Sample for DeleteRegionalInventory", - "file": "merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_RegionalInventoryService_DeleteRegionalInventory_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient", - "shortName": "RegionalInventoryServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient.insert_regional_inventory", - "method": { - "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService.InsertRegionalInventory", - "service": { - "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", - "shortName": "RegionalInventoryService" - }, - "shortName": "InsertRegionalInventory" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_inventories_v1beta.types.InsertRegionalInventoryRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.shopping.merchant_inventories_v1beta.types.RegionalInventory", - "shortName": "insert_regional_inventory" - }, - "description": "Sample for InsertRegionalInventory", - "file": "merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_RegionalInventoryService_InsertRegionalInventory_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceClient", - "shortName": "RegionalInventoryServiceClient" - }, - "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceClient.insert_regional_inventory", - "method": { - "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService.InsertRegionalInventory", - "service": { - "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", - "shortName": "RegionalInventoryService" - }, - "shortName": "InsertRegionalInventory" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_inventories_v1beta.types.InsertRegionalInventoryRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.shopping.merchant_inventories_v1beta.types.RegionalInventory", - "shortName": "insert_regional_inventory" - }, - "description": "Sample for InsertRegionalInventory", - "file": "merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_RegionalInventoryService_InsertRegionalInventory_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient", - "shortName": "RegionalInventoryServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient.list_regional_inventories", - "method": { - "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService.ListRegionalInventories", - "service": { - "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", - "shortName": "RegionalInventoryService" - }, - "shortName": "ListRegionalInventories" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.pagers.ListRegionalInventoriesAsyncPager", - "shortName": "list_regional_inventories" - }, - "description": "Sample for ListRegionalInventories", - "file": "merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_RegionalInventoryService_ListRegionalInventories_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceClient", - "shortName": "RegionalInventoryServiceClient" - }, - "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceClient.list_regional_inventories", - "method": { - "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService.ListRegionalInventories", - "service": { - "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", - "shortName": "RegionalInventoryService" - }, - "shortName": "ListRegionalInventories" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.pagers.ListRegionalInventoriesPager", - "shortName": "list_regional_inventories" - }, - "description": "Sample for ListRegionalInventories", - "file": "merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_RegionalInventoryService_ListRegionalInventories_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/scripts/fixup_merchant_inventories_v1beta_keywords.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/scripts/fixup_merchant_inventories_v1beta_keywords.py deleted file mode 100644 index f3a43869aa74..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/scripts/fixup_merchant_inventories_v1beta_keywords.py +++ /dev/null @@ -1,181 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class merchant_inventoriesCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'delete_local_inventory': ('name', ), - 'delete_regional_inventory': ('name', ), - 'insert_local_inventory': ('parent', 'local_inventory', ), - 'insert_regional_inventory': ('parent', 'regional_inventory', ), - 'list_local_inventories': ('parent', 'page_size', 'page_token', ), - 'list_regional_inventories': ('parent', 'page_size', 'page_token', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=merchant_inventoriesCallTransformer(), -): - """Duplicate the input dir to the output dir, fixing file method calls. - - Preconditions: - * in_dir is a real directory - * out_dir is a real, empty directory - """ - pyfile_gen = ( - pathlib.Path(os.path.join(root, f)) - for root, _, files in os.walk(in_dir) - for f in files if os.path.splitext(f)[1] == ".py" - ) - - for fpath in pyfile_gen: - with open(fpath, 'r') as f: - src = f.read() - - # Parse the code and insert method call fixes. - tree = cst.parse_module(src) - updated = tree.visit(transformer) - - # Create the path and directory structure for the new file. - updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) - updated_path.parent.mkdir(parents=True, exist_ok=True) - - # Generate the updated source file at the corresponding path. - with open(updated_path, 'w') as f: - f.write(updated.code) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description="""Fix up source that uses the merchant_inventories client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/setup.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/setup.py deleted file mode 100644 index 70bf2bb6e0f2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/setup.py +++ /dev/null @@ -1,99 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os -import re - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-shopping-merchant-inventories' - - -description = "Google Shopping Merchant Inventories API client library" - -version = None - -with open(os.path.join(package_root, 'google/shopping/merchant_inventories/gapic_version.py')) as fp: - version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) - assert (len(version_candidates) == 1) - version = version_candidates[0] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -dependencies = [ - "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=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.0dev,!=2.24.0,!=2.25.0", - "proto-plus >= 1.22.3, <2.0.0dev", - "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'", - "protobuf>=3.20.2,<6.0.0dev,!=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.0dev", -] -extras = { -} -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-inventories" - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, "README.rst") -with io.open(readme_filename, encoding="utf-8") as readme_file: - readme = readme_file.read() - -packages = [ - package - for package in setuptools.find_namespace_packages() - if package.startswith("google") -] - -setuptools.setup( - name=name, - version=version, - description=description, - long_description=readme, - author="Google LLC", - author_email="googleapis-packages@google.com", - license="Apache 2.0", - url=url, - classifiers=[ - release_status, - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Programming Language :: Python :: 3.12", - "Programming Language :: Python :: 3.13", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - install_requires=dependencies, - extras_require=extras, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.10.txt b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.10.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.10.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -google-shopping-type diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.11.txt b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.11.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.11.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -google-shopping-type diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.12.txt b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.12.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.12.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -google-shopping-type diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.13.txt b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.13.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.13.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -google-shopping-type diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.7.txt b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.7.txt deleted file mode 100644 index 130a0c0f80ab..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.7.txt +++ /dev/null @@ -1,11 +0,0 @@ -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file. -# Pin the version to the lower bound. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", -# Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.34.1 -google-auth==2.14.1 -proto-plus==1.22.3 -protobuf==3.20.2 -google-shopping-type==0.1.6 diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.8.txt b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.8.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.8.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -google-shopping-type diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.9.txt b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.9.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.9.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -google-shopping-type diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/test_local_inventory_service.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/test_local_inventory_service.py deleted file mode 100644 index dd862b8b1671..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/test_local_inventory_service.py +++ /dev/null @@ -1,3612 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable, AsyncIterable -from google.protobuf import json_format -import json -import math -import pytest -from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -try: - from google.auth.aio import credentials as ga_credentials_async - HAS_GOOGLE_AUTH_AIO = True -except ImportError: # pragma: NO COVER - HAS_GOOGLE_AUTH_AIO = False - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.oauth2 import service_account -from google.protobuf import timestamp_pb2 # type: ignore -from google.shopping.merchant_inventories_v1beta.services.local_inventory_service import LocalInventoryServiceAsyncClient -from google.shopping.merchant_inventories_v1beta.services.local_inventory_service import LocalInventoryServiceClient -from google.shopping.merchant_inventories_v1beta.services.local_inventory_service import pagers -from google.shopping.merchant_inventories_v1beta.services.local_inventory_service import transports -from google.shopping.merchant_inventories_v1beta.types import localinventory -from google.shopping.type.types import types -from google.type import interval_pb2 # type: ignore -import google.auth - - -async def mock_async_gen(data, chunk_size=1): - for i in range(0, len(data)): # pragma: NO COVER - chunk = data[i : i + chunk_size] - yield chunk.encode("utf-8") - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - -# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. -# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. -def async_anonymous_credentials(): - if HAS_GOOGLE_AUTH_AIO: - return ga_credentials_async.AnonymousCredentials() - return ga_credentials.AnonymousCredentials() - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - -# If default endpoint template is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint template so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint_template(client): - return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert LocalInventoryServiceClient._get_default_mtls_endpoint(None) is None - assert LocalInventoryServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert LocalInventoryServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert LocalInventoryServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert LocalInventoryServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert LocalInventoryServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert LocalInventoryServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert LocalInventoryServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert LocalInventoryServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - LocalInventoryServiceClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - assert LocalInventoryServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert LocalInventoryServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert LocalInventoryServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - LocalInventoryServiceClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): - assert LocalInventoryServiceClient._read_environment_variables() == (False, "auto", "foo.com") - -def test__get_client_cert_source(): - mock_provided_cert_source = mock.Mock() - mock_default_cert_source = mock.Mock() - - assert LocalInventoryServiceClient._get_client_cert_source(None, False) is None - assert LocalInventoryServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert LocalInventoryServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): - assert LocalInventoryServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert LocalInventoryServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(LocalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceClient)) -@mock.patch.object(LocalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = LocalInventoryServiceClient._DEFAULT_UNIVERSE - default_endpoint = LocalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = LocalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert LocalInventoryServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert LocalInventoryServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == LocalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT - assert LocalInventoryServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert LocalInventoryServiceClient._get_api_endpoint(None, None, default_universe, "always") == LocalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT - assert LocalInventoryServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == LocalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT - assert LocalInventoryServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert LocalInventoryServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - LocalInventoryServiceClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") - assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." - - -def test__get_universe_domain(): - client_universe_domain = "foo.com" - universe_domain_env = "bar.com" - - assert LocalInventoryServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert LocalInventoryServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert LocalInventoryServiceClient._get_universe_domain(None, None) == LocalInventoryServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - LocalInventoryServiceClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - - -@pytest.mark.parametrize("client_class,transport_name", [ - (LocalInventoryServiceClient, "grpc"), - (LocalInventoryServiceAsyncClient, "grpc_asyncio"), - (LocalInventoryServiceClient, "rest"), -]) -def test_local_inventory_service_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'merchantapi.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://merchantapi.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.LocalInventoryServiceGrpcTransport, "grpc"), - (transports.LocalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.LocalInventoryServiceRestTransport, "rest"), -]) -def test_local_inventory_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (LocalInventoryServiceClient, "grpc"), - (LocalInventoryServiceAsyncClient, "grpc_asyncio"), - (LocalInventoryServiceClient, "rest"), -]) -def test_local_inventory_service_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'merchantapi.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://merchantapi.googleapis.com' - ) - - -def test_local_inventory_service_client_get_transport_class(): - transport = LocalInventoryServiceClient.get_transport_class() - available_transports = [ - transports.LocalInventoryServiceGrpcTransport, - transports.LocalInventoryServiceRestTransport, - ] - assert transport in available_transports - - transport = LocalInventoryServiceClient.get_transport_class("grpc") - assert transport == transports.LocalInventoryServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (LocalInventoryServiceClient, transports.LocalInventoryServiceGrpcTransport, "grpc"), - (LocalInventoryServiceAsyncClient, transports.LocalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (LocalInventoryServiceClient, transports.LocalInventoryServiceRestTransport, "rest"), -]) -@mock.patch.object(LocalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceClient)) -@mock.patch.object(LocalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceAsyncClient)) -def test_local_inventory_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(LocalInventoryServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(LocalInventoryServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (LocalInventoryServiceClient, transports.LocalInventoryServiceGrpcTransport, "grpc", "true"), - (LocalInventoryServiceAsyncClient, transports.LocalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (LocalInventoryServiceClient, transports.LocalInventoryServiceGrpcTransport, "grpc", "false"), - (LocalInventoryServiceAsyncClient, transports.LocalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (LocalInventoryServiceClient, transports.LocalInventoryServiceRestTransport, "rest", "true"), - (LocalInventoryServiceClient, transports.LocalInventoryServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(LocalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceClient)) -@mock.patch.object(LocalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_local_inventory_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - LocalInventoryServiceClient, LocalInventoryServiceAsyncClient -]) -@mock.patch.object(LocalInventoryServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LocalInventoryServiceClient)) -@mock.patch.object(LocalInventoryServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LocalInventoryServiceAsyncClient)) -def test_local_inventory_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - -@pytest.mark.parametrize("client_class", [ - LocalInventoryServiceClient, LocalInventoryServiceAsyncClient -]) -@mock.patch.object(LocalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceClient)) -@mock.patch.object(LocalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceAsyncClient)) -def test_local_inventory_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = LocalInventoryServiceClient._DEFAULT_UNIVERSE - default_endpoint = LocalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = LocalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", - # use ClientOptions.api_endpoint as the api endpoint regardless. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == api_override - - # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class(credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == default_endpoint - - # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", - # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - client = client_class(credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - - # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), - # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, - # and ClientOptions.universe_domain="bar.com", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. - options = client_options.ClientOptions() - universe_exists = hasattr(options, "universe_domain") - if universe_exists: - options = client_options.ClientOptions(universe_domain=mock_universe) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - else: - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) - assert client.universe_domain == (mock_universe if universe_exists else default_universe) - - # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. - options = client_options.ClientOptions() - if hasattr(options, "universe_domain"): - delattr(options, "universe_domain") - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == default_endpoint - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (LocalInventoryServiceClient, transports.LocalInventoryServiceGrpcTransport, "grpc"), - (LocalInventoryServiceAsyncClient, transports.LocalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (LocalInventoryServiceClient, transports.LocalInventoryServiceRestTransport, "rest"), -]) -def test_local_inventory_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (LocalInventoryServiceClient, transports.LocalInventoryServiceGrpcTransport, "grpc", grpc_helpers), - (LocalInventoryServiceAsyncClient, transports.LocalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (LocalInventoryServiceClient, transports.LocalInventoryServiceRestTransport, "rest", None), -]) -def test_local_inventory_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_local_inventory_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_inventories_v1beta.services.local_inventory_service.transports.LocalInventoryServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = LocalInventoryServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (LocalInventoryServiceClient, transports.LocalInventoryServiceGrpcTransport, "grpc", grpc_helpers), - (LocalInventoryServiceAsyncClient, transports.LocalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_local_inventory_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "merchantapi.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/content', -), - scopes=None, - default_host="merchantapi.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - localinventory.ListLocalInventoriesRequest, - dict, -]) -def test_list_local_inventories(request_type, transport: str = 'grpc'): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_local_inventories), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = localinventory.ListLocalInventoriesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = localinventory.ListLocalInventoriesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListLocalInventoriesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_local_inventories_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = localinventory.ListLocalInventoriesRequest( - parent='parent_value', - page_token='page_token_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_local_inventories), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_local_inventories(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == localinventory.ListLocalInventoriesRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_local_inventories_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_local_inventories in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_local_inventories] = mock_rpc - request = {} - client.list_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_local_inventories(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_local_inventories_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = LocalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.list_local_inventories in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.list_local_inventories] = mock_rpc - - request = {} - await client.list_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_local_inventories(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_local_inventories_async(transport: str = 'grpc_asyncio', request_type=localinventory.ListLocalInventoriesRequest): - client = LocalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_local_inventories), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(localinventory.ListLocalInventoriesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = localinventory.ListLocalInventoriesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListLocalInventoriesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_local_inventories_async_from_dict(): - await test_list_local_inventories_async(request_type=dict) - -def test_list_local_inventories_field_headers(): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = localinventory.ListLocalInventoriesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_local_inventories), - '__call__') as call: - call.return_value = localinventory.ListLocalInventoriesResponse() - client.list_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_local_inventories_field_headers_async(): - client = LocalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = localinventory.ListLocalInventoriesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_local_inventories), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(localinventory.ListLocalInventoriesResponse()) - await client.list_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_list_local_inventories_flattened(): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_local_inventories), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = localinventory.ListLocalInventoriesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_local_inventories( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_local_inventories_flattened_error(): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_local_inventories( - localinventory.ListLocalInventoriesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_local_inventories_flattened_async(): - client = LocalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_local_inventories), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = localinventory.ListLocalInventoriesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(localinventory.ListLocalInventoriesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_local_inventories( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_local_inventories_flattened_error_async(): - client = LocalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_local_inventories( - localinventory.ListLocalInventoriesRequest(), - parent='parent_value', - ) - - -def test_list_local_inventories_pager(transport_name: str = "grpc"): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_local_inventories), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - localinventory.ListLocalInventoriesResponse( - local_inventories=[ - localinventory.LocalInventory(), - localinventory.LocalInventory(), - localinventory.LocalInventory(), - ], - next_page_token='abc', - ), - localinventory.ListLocalInventoriesResponse( - local_inventories=[], - next_page_token='def', - ), - localinventory.ListLocalInventoriesResponse( - local_inventories=[ - localinventory.LocalInventory(), - ], - next_page_token='ghi', - ), - localinventory.ListLocalInventoriesResponse( - local_inventories=[ - localinventory.LocalInventory(), - localinventory.LocalInventory(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_local_inventories(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, localinventory.LocalInventory) - for i in results) -def test_list_local_inventories_pages(transport_name: str = "grpc"): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_local_inventories), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - localinventory.ListLocalInventoriesResponse( - local_inventories=[ - localinventory.LocalInventory(), - localinventory.LocalInventory(), - localinventory.LocalInventory(), - ], - next_page_token='abc', - ), - localinventory.ListLocalInventoriesResponse( - local_inventories=[], - next_page_token='def', - ), - localinventory.ListLocalInventoriesResponse( - local_inventories=[ - localinventory.LocalInventory(), - ], - next_page_token='ghi', - ), - localinventory.ListLocalInventoriesResponse( - local_inventories=[ - localinventory.LocalInventory(), - localinventory.LocalInventory(), - ], - ), - RuntimeError, - ) - pages = list(client.list_local_inventories(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_local_inventories_async_pager(): - client = LocalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_local_inventories), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - localinventory.ListLocalInventoriesResponse( - local_inventories=[ - localinventory.LocalInventory(), - localinventory.LocalInventory(), - localinventory.LocalInventory(), - ], - next_page_token='abc', - ), - localinventory.ListLocalInventoriesResponse( - local_inventories=[], - next_page_token='def', - ), - localinventory.ListLocalInventoriesResponse( - local_inventories=[ - localinventory.LocalInventory(), - ], - next_page_token='ghi', - ), - localinventory.ListLocalInventoriesResponse( - local_inventories=[ - localinventory.LocalInventory(), - localinventory.LocalInventory(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_local_inventories(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, localinventory.LocalInventory) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_local_inventories_async_pages(): - client = LocalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_local_inventories), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - localinventory.ListLocalInventoriesResponse( - local_inventories=[ - localinventory.LocalInventory(), - localinventory.LocalInventory(), - localinventory.LocalInventory(), - ], - next_page_token='abc', - ), - localinventory.ListLocalInventoriesResponse( - local_inventories=[], - next_page_token='def', - ), - localinventory.ListLocalInventoriesResponse( - local_inventories=[ - localinventory.LocalInventory(), - ], - next_page_token='ghi', - ), - localinventory.ListLocalInventoriesResponse( - local_inventories=[ - localinventory.LocalInventory(), - localinventory.LocalInventory(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_local_inventories(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - localinventory.InsertLocalInventoryRequest, - dict, -]) -def test_insert_local_inventory(request_type, transport: str = 'grpc'): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.insert_local_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = localinventory.LocalInventory( - name='name_value', - account=749, - store_code='store_code_value', - availability='availability_value', - quantity=895, - pickup_method='pickup_method_value', - pickup_sla='pickup_sla_value', - instore_product_location='instore_product_location_value', - ) - response = client.insert_local_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = localinventory.InsertLocalInventoryRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, localinventory.LocalInventory) - assert response.name == 'name_value' - assert response.account == 749 - assert response.store_code == 'store_code_value' - assert response.availability == 'availability_value' - assert response.quantity == 895 - assert response.pickup_method == 'pickup_method_value' - assert response.pickup_sla == 'pickup_sla_value' - assert response.instore_product_location == 'instore_product_location_value' - - -def test_insert_local_inventory_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = localinventory.InsertLocalInventoryRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.insert_local_inventory), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.insert_local_inventory(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == localinventory.InsertLocalInventoryRequest( - parent='parent_value', - ) - -def test_insert_local_inventory_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.insert_local_inventory in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.insert_local_inventory] = mock_rpc - request = {} - client.insert_local_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.insert_local_inventory(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_insert_local_inventory_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = LocalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.insert_local_inventory in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.insert_local_inventory] = mock_rpc - - request = {} - await client.insert_local_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.insert_local_inventory(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_insert_local_inventory_async(transport: str = 'grpc_asyncio', request_type=localinventory.InsertLocalInventoryRequest): - client = LocalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.insert_local_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(localinventory.LocalInventory( - name='name_value', - account=749, - store_code='store_code_value', - availability='availability_value', - quantity=895, - pickup_method='pickup_method_value', - pickup_sla='pickup_sla_value', - instore_product_location='instore_product_location_value', - )) - response = await client.insert_local_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = localinventory.InsertLocalInventoryRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, localinventory.LocalInventory) - assert response.name == 'name_value' - assert response.account == 749 - assert response.store_code == 'store_code_value' - assert response.availability == 'availability_value' - assert response.quantity == 895 - assert response.pickup_method == 'pickup_method_value' - assert response.pickup_sla == 'pickup_sla_value' - assert response.instore_product_location == 'instore_product_location_value' - - -@pytest.mark.asyncio -async def test_insert_local_inventory_async_from_dict(): - await test_insert_local_inventory_async(request_type=dict) - -def test_insert_local_inventory_field_headers(): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = localinventory.InsertLocalInventoryRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.insert_local_inventory), - '__call__') as call: - call.return_value = localinventory.LocalInventory() - client.insert_local_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_insert_local_inventory_field_headers_async(): - client = LocalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = localinventory.InsertLocalInventoryRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.insert_local_inventory), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(localinventory.LocalInventory()) - await client.insert_local_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - localinventory.DeleteLocalInventoryRequest, - dict, -]) -def test_delete_local_inventory(request_type, transport: str = 'grpc'): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_local_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_local_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = localinventory.DeleteLocalInventoryRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_local_inventory_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = localinventory.DeleteLocalInventoryRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_local_inventory), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_local_inventory(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == localinventory.DeleteLocalInventoryRequest( - name='name_value', - ) - -def test_delete_local_inventory_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.delete_local_inventory in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.delete_local_inventory] = mock_rpc - request = {} - client.delete_local_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_local_inventory(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_local_inventory_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = LocalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.delete_local_inventory in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.delete_local_inventory] = mock_rpc - - request = {} - await client.delete_local_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.delete_local_inventory(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_local_inventory_async(transport: str = 'grpc_asyncio', request_type=localinventory.DeleteLocalInventoryRequest): - client = LocalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_local_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_local_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = localinventory.DeleteLocalInventoryRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_local_inventory_async_from_dict(): - await test_delete_local_inventory_async(request_type=dict) - -def test_delete_local_inventory_field_headers(): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = localinventory.DeleteLocalInventoryRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_local_inventory), - '__call__') as call: - call.return_value = None - client.delete_local_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_local_inventory_field_headers_async(): - client = LocalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = localinventory.DeleteLocalInventoryRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_local_inventory), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_local_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_delete_local_inventory_flattened(): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_local_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_local_inventory( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_local_inventory_flattened_error(): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_local_inventory( - localinventory.DeleteLocalInventoryRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_local_inventory_flattened_async(): - client = LocalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_local_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_local_inventory( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_local_inventory_flattened_error_async(): - client = LocalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_local_inventory( - localinventory.DeleteLocalInventoryRequest(), - name='name_value', - ) - - -def test_list_local_inventories_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_local_inventories in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_local_inventories] = mock_rpc - - request = {} - client.list_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_local_inventories(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_list_local_inventories_rest_required_fields(request_type=localinventory.ListLocalInventoriesRequest): - transport_class = transports.LocalInventoryServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_local_inventories._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_local_inventories._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = localinventory.ListLocalInventoriesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = localinventory.ListLocalInventoriesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.list_local_inventories(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_local_inventories_rest_unset_required_fields(): - transport = transports.LocalInventoryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_local_inventories._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_local_inventories_rest_flattened(): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = localinventory.ListLocalInventoriesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'accounts/sample1/products/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = localinventory.ListLocalInventoriesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.list_local_inventories(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/inventories/v1beta/{parent=accounts/*/products/*}/localInventories" % client.transport._host, args[1]) - - -def test_list_local_inventories_rest_flattened_error(transport: str = 'rest'): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_local_inventories( - localinventory.ListLocalInventoriesRequest(), - parent='parent_value', - ) - - -def test_list_local_inventories_rest_pager(transport: str = 'rest'): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - localinventory.ListLocalInventoriesResponse( - local_inventories=[ - localinventory.LocalInventory(), - localinventory.LocalInventory(), - localinventory.LocalInventory(), - ], - next_page_token='abc', - ), - localinventory.ListLocalInventoriesResponse( - local_inventories=[], - next_page_token='def', - ), - localinventory.ListLocalInventoriesResponse( - local_inventories=[ - localinventory.LocalInventory(), - ], - next_page_token='ghi', - ), - localinventory.ListLocalInventoriesResponse( - local_inventories=[ - localinventory.LocalInventory(), - localinventory.LocalInventory(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(localinventory.ListLocalInventoriesResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'accounts/sample1/products/sample2'} - - pager = client.list_local_inventories(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, localinventory.LocalInventory) - for i in results) - - pages = list(client.list_local_inventories(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_insert_local_inventory_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.insert_local_inventory in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.insert_local_inventory] = mock_rpc - - request = {} - client.insert_local_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.insert_local_inventory(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_insert_local_inventory_rest_required_fields(request_type=localinventory.InsertLocalInventoryRequest): - transport_class = transports.LocalInventoryServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).insert_local_inventory._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).insert_local_inventory._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = localinventory.LocalInventory() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = localinventory.LocalInventory.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.insert_local_inventory(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_insert_local_inventory_rest_unset_required_fields(): - transport = transports.LocalInventoryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.insert_local_inventory._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "localInventory", ))) - - -def test_delete_local_inventory_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.delete_local_inventory in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.delete_local_inventory] = mock_rpc - - request = {} - client.delete_local_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_local_inventory(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_delete_local_inventory_rest_required_fields(request_type=localinventory.DeleteLocalInventoryRequest): - transport_class = transports.LocalInventoryServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_local_inventory._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_local_inventory._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = None - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.delete_local_inventory(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_local_inventory_rest_unset_required_fields(): - transport = transports.LocalInventoryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_local_inventory._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_delete_local_inventory_rest_flattened(): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/products/sample2/localInventories/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.delete_local_inventory(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/inventories/v1beta/{name=accounts/*/products/*/localInventories/*}" % client.transport._host, args[1]) - - -def test_delete_local_inventory_rest_flattened_error(transport: str = 'rest'): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_local_inventory( - localinventory.DeleteLocalInventoryRequest(), - name='name_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.LocalInventoryServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.LocalInventoryServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = LocalInventoryServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.LocalInventoryServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = LocalInventoryServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = LocalInventoryServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.LocalInventoryServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = LocalInventoryServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.LocalInventoryServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = LocalInventoryServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.LocalInventoryServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.LocalInventoryServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.LocalInventoryServiceGrpcTransport, - transports.LocalInventoryServiceGrpcAsyncIOTransport, - transports.LocalInventoryServiceRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_kind_grpc(): - transport = LocalInventoryServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_local_inventories_empty_call_grpc(): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_local_inventories), - '__call__') as call: - call.return_value = localinventory.ListLocalInventoriesResponse() - client.list_local_inventories(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = localinventory.ListLocalInventoriesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_insert_local_inventory_empty_call_grpc(): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.insert_local_inventory), - '__call__') as call: - call.return_value = localinventory.LocalInventory() - client.insert_local_inventory(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = localinventory.InsertLocalInventoryRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_local_inventory_empty_call_grpc(): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_local_inventory), - '__call__') as call: - call.return_value = None - client.delete_local_inventory(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = localinventory.DeleteLocalInventoryRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = LocalInventoryServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = LocalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_local_inventories_empty_call_grpc_asyncio(): - client = LocalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_local_inventories), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(localinventory.ListLocalInventoriesResponse( - next_page_token='next_page_token_value', - )) - await client.list_local_inventories(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = localinventory.ListLocalInventoriesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_insert_local_inventory_empty_call_grpc_asyncio(): - client = LocalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.insert_local_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(localinventory.LocalInventory( - name='name_value', - account=749, - store_code='store_code_value', - availability='availability_value', - quantity=895, - pickup_method='pickup_method_value', - pickup_sla='pickup_sla_value', - instore_product_location='instore_product_location_value', - )) - await client.insert_local_inventory(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = localinventory.InsertLocalInventoryRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_delete_local_inventory_empty_call_grpc_asyncio(): - client = LocalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_local_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_local_inventory(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = localinventory.DeleteLocalInventoryRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = LocalInventoryServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_list_local_inventories_rest_bad_request(request_type=localinventory.ListLocalInventoriesRequest): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1/products/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_local_inventories(request) - - -@pytest.mark.parametrize("request_type", [ - localinventory.ListLocalInventoriesRequest, - dict, -]) -def test_list_local_inventories_rest_call_success(request_type): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1/products/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = localinventory.ListLocalInventoriesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = localinventory.ListLocalInventoriesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_local_inventories(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListLocalInventoriesPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_local_inventories_rest_interceptors(null_interceptor): - transport = transports.LocalInventoryServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.LocalInventoryServiceRestInterceptor(), - ) - client = LocalInventoryServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.LocalInventoryServiceRestInterceptor, "post_list_local_inventories") as post, \ - mock.patch.object(transports.LocalInventoryServiceRestInterceptor, "pre_list_local_inventories") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = localinventory.ListLocalInventoriesRequest.pb(localinventory.ListLocalInventoriesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = localinventory.ListLocalInventoriesResponse.to_json(localinventory.ListLocalInventoriesResponse()) - req.return_value.content = return_value - - request = localinventory.ListLocalInventoriesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = localinventory.ListLocalInventoriesResponse() - - client.list_local_inventories(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_insert_local_inventory_rest_bad_request(request_type=localinventory.InsertLocalInventoryRequest): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1/products/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.insert_local_inventory(request) - - -@pytest.mark.parametrize("request_type", [ - localinventory.InsertLocalInventoryRequest, - dict, -]) -def test_insert_local_inventory_rest_call_success(request_type): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1/products/sample2'} - request_init["local_inventory"] = {'name': 'name_value', 'account': 749, 'store_code': 'store_code_value', 'price': {'amount_micros': 1408, 'currency_code': 'currency_code_value'}, 'sale_price': {}, 'sale_price_effective_date': {'start_time': {'seconds': 751, 'nanos': 543}, 'end_time': {}}, 'availability': 'availability_value', 'quantity': 895, 'pickup_method': 'pickup_method_value', 'pickup_sla': 'pickup_sla_value', 'instore_product_location': 'instore_product_location_value', 'custom_attributes': [{'name': 'name_value', 'value': 'value_value', 'group_values': {}}]} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = localinventory.InsertLocalInventoryRequest.meta.fields["local_inventory"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["local_inventory"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["local_inventory"][field])): - del request_init["local_inventory"][field][i][subfield] - else: - del request_init["local_inventory"][field][subfield] - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = localinventory.LocalInventory( - name='name_value', - account=749, - store_code='store_code_value', - availability='availability_value', - quantity=895, - pickup_method='pickup_method_value', - pickup_sla='pickup_sla_value', - instore_product_location='instore_product_location_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = localinventory.LocalInventory.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.insert_local_inventory(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, localinventory.LocalInventory) - assert response.name == 'name_value' - assert response.account == 749 - assert response.store_code == 'store_code_value' - assert response.availability == 'availability_value' - assert response.quantity == 895 - assert response.pickup_method == 'pickup_method_value' - assert response.pickup_sla == 'pickup_sla_value' - assert response.instore_product_location == 'instore_product_location_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_insert_local_inventory_rest_interceptors(null_interceptor): - transport = transports.LocalInventoryServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.LocalInventoryServiceRestInterceptor(), - ) - client = LocalInventoryServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.LocalInventoryServiceRestInterceptor, "post_insert_local_inventory") as post, \ - mock.patch.object(transports.LocalInventoryServiceRestInterceptor, "pre_insert_local_inventory") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = localinventory.InsertLocalInventoryRequest.pb(localinventory.InsertLocalInventoryRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = localinventory.LocalInventory.to_json(localinventory.LocalInventory()) - req.return_value.content = return_value - - request = localinventory.InsertLocalInventoryRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = localinventory.LocalInventory() - - client.insert_local_inventory(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_local_inventory_rest_bad_request(request_type=localinventory.DeleteLocalInventoryRequest): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/products/sample2/localInventories/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_local_inventory(request) - - -@pytest.mark.parametrize("request_type", [ - localinventory.DeleteLocalInventoryRequest, - dict, -]) -def test_delete_local_inventory_rest_call_success(request_type): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/products/sample2/localInventories/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = '' - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_local_inventory(request) - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_local_inventory_rest_interceptors(null_interceptor): - transport = transports.LocalInventoryServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.LocalInventoryServiceRestInterceptor(), - ) - client = LocalInventoryServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.LocalInventoryServiceRestInterceptor, "pre_delete_local_inventory") as pre: - pre.assert_not_called() - pb_message = localinventory.DeleteLocalInventoryRequest.pb(localinventory.DeleteLocalInventoryRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - request = localinventory.DeleteLocalInventoryRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_local_inventory(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - -def test_initialize_client_w_rest(): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_local_inventories_empty_call_rest(): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_local_inventories), - '__call__') as call: - client.list_local_inventories(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = localinventory.ListLocalInventoriesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_insert_local_inventory_empty_call_rest(): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.insert_local_inventory), - '__call__') as call: - client.insert_local_inventory(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = localinventory.InsertLocalInventoryRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_local_inventory_empty_call_rest(): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_local_inventory), - '__call__') as call: - client.delete_local_inventory(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = localinventory.DeleteLocalInventoryRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.LocalInventoryServiceGrpcTransport, - ) - -def test_local_inventory_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.LocalInventoryServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_local_inventory_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.shopping.merchant_inventories_v1beta.services.local_inventory_service.transports.LocalInventoryServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.LocalInventoryServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_local_inventories', - 'insert_local_inventory', - 'delete_local_inventory', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_local_inventory_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.shopping.merchant_inventories_v1beta.services.local_inventory_service.transports.LocalInventoryServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.LocalInventoryServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/content', -), - quota_project_id="octopus", - ) - - -def test_local_inventory_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.shopping.merchant_inventories_v1beta.services.local_inventory_service.transports.LocalInventoryServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.LocalInventoryServiceTransport() - adc.assert_called_once() - - -def test_local_inventory_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - LocalInventoryServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/content', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.LocalInventoryServiceGrpcTransport, - transports.LocalInventoryServiceGrpcAsyncIOTransport, - ], -) -def test_local_inventory_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/content',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.LocalInventoryServiceGrpcTransport, - transports.LocalInventoryServiceGrpcAsyncIOTransport, - transports.LocalInventoryServiceRestTransport, - ], -) -def test_local_inventory_service_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.LocalInventoryServiceGrpcTransport, grpc_helpers), - (transports.LocalInventoryServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_local_inventory_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "merchantapi.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/content', -), - scopes=["1", "2"], - default_host="merchantapi.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.LocalInventoryServiceGrpcTransport, transports.LocalInventoryServiceGrpcAsyncIOTransport]) -def test_local_inventory_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_local_inventory_service_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.LocalInventoryServiceRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_local_inventory_service_host_no_port(transport_name): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='merchantapi.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'merchantapi.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://merchantapi.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_local_inventory_service_host_with_port(transport_name): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='merchantapi.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'merchantapi.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://merchantapi.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_local_inventory_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = LocalInventoryServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = LocalInventoryServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_local_inventories._session - session2 = client2.transport.list_local_inventories._session - assert session1 != session2 - session1 = client1.transport.insert_local_inventory._session - session2 = client2.transport.insert_local_inventory._session - assert session1 != session2 - session1 = client1.transport.delete_local_inventory._session - session2 = client2.transport.delete_local_inventory._session - assert session1 != session2 -def test_local_inventory_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.LocalInventoryServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_local_inventory_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.LocalInventoryServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.LocalInventoryServiceGrpcTransport, transports.LocalInventoryServiceGrpcAsyncIOTransport]) -def test_local_inventory_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.LocalInventoryServiceGrpcTransport, transports.LocalInventoryServiceGrpcAsyncIOTransport]) -def test_local_inventory_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_local_inventory_path(): - account = "squid" - product = "clam" - store_code = "whelk" - expected = "accounts/{account}/products/{product}/localInventories/{store_code}".format(account=account, product=product, store_code=store_code, ) - actual = LocalInventoryServiceClient.local_inventory_path(account, product, store_code) - assert expected == actual - - -def test_parse_local_inventory_path(): - expected = { - "account": "octopus", - "product": "oyster", - "store_code": "nudibranch", - } - path = LocalInventoryServiceClient.local_inventory_path(**expected) - - # Check that the path construction is reversible. - actual = LocalInventoryServiceClient.parse_local_inventory_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = LocalInventoryServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = LocalInventoryServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = LocalInventoryServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = LocalInventoryServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = LocalInventoryServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = LocalInventoryServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = LocalInventoryServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = LocalInventoryServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = LocalInventoryServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = LocalInventoryServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = LocalInventoryServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = LocalInventoryServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = LocalInventoryServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = LocalInventoryServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = LocalInventoryServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.LocalInventoryServiceTransport, '_prep_wrapped_messages') as prep: - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.LocalInventoryServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = LocalInventoryServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -def test_transport_close_grpc(): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" - ) - with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - - -@pytest.mark.asyncio -async def test_transport_close_grpc_asyncio(): - client = LocalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" - ) - with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close_rest(): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - with mock.patch.object(type(getattr(client.transport, "_session")), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (LocalInventoryServiceClient, transports.LocalInventoryServiceGrpcTransport), - (LocalInventoryServiceAsyncClient, transports.LocalInventoryServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/test_regional_inventory_service.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/test_regional_inventory_service.py deleted file mode 100644 index 59f1d9c2b29c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/test_regional_inventory_service.py +++ /dev/null @@ -1,3584 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable, AsyncIterable -from google.protobuf import json_format -import json -import math -import pytest -from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -try: - from google.auth.aio import credentials as ga_credentials_async - HAS_GOOGLE_AUTH_AIO = True -except ImportError: # pragma: NO COVER - HAS_GOOGLE_AUTH_AIO = False - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.oauth2 import service_account -from google.protobuf import timestamp_pb2 # type: ignore -from google.shopping.merchant_inventories_v1beta.services.regional_inventory_service import RegionalInventoryServiceAsyncClient -from google.shopping.merchant_inventories_v1beta.services.regional_inventory_service import RegionalInventoryServiceClient -from google.shopping.merchant_inventories_v1beta.services.regional_inventory_service import pagers -from google.shopping.merchant_inventories_v1beta.services.regional_inventory_service import transports -from google.shopping.merchant_inventories_v1beta.types import regionalinventory -from google.shopping.type.types import types -from google.type import interval_pb2 # type: ignore -import google.auth - - -async def mock_async_gen(data, chunk_size=1): - for i in range(0, len(data)): # pragma: NO COVER - chunk = data[i : i + chunk_size] - yield chunk.encode("utf-8") - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - -# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. -# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. -def async_anonymous_credentials(): - if HAS_GOOGLE_AUTH_AIO: - return ga_credentials_async.AnonymousCredentials() - return ga_credentials.AnonymousCredentials() - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - -# If default endpoint template is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint template so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint_template(client): - return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert RegionalInventoryServiceClient._get_default_mtls_endpoint(None) is None - assert RegionalInventoryServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert RegionalInventoryServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert RegionalInventoryServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert RegionalInventoryServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert RegionalInventoryServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert RegionalInventoryServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert RegionalInventoryServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert RegionalInventoryServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - RegionalInventoryServiceClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - assert RegionalInventoryServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert RegionalInventoryServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert RegionalInventoryServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - RegionalInventoryServiceClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): - assert RegionalInventoryServiceClient._read_environment_variables() == (False, "auto", "foo.com") - -def test__get_client_cert_source(): - mock_provided_cert_source = mock.Mock() - mock_default_cert_source = mock.Mock() - - assert RegionalInventoryServiceClient._get_client_cert_source(None, False) is None - assert RegionalInventoryServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert RegionalInventoryServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): - assert RegionalInventoryServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert RegionalInventoryServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(RegionalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceClient)) -@mock.patch.object(RegionalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = RegionalInventoryServiceClient._DEFAULT_UNIVERSE - default_endpoint = RegionalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = RegionalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert RegionalInventoryServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert RegionalInventoryServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == RegionalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT - assert RegionalInventoryServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert RegionalInventoryServiceClient._get_api_endpoint(None, None, default_universe, "always") == RegionalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT - assert RegionalInventoryServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == RegionalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT - assert RegionalInventoryServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert RegionalInventoryServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - RegionalInventoryServiceClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") - assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." - - -def test__get_universe_domain(): - client_universe_domain = "foo.com" - universe_domain_env = "bar.com" - - assert RegionalInventoryServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert RegionalInventoryServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert RegionalInventoryServiceClient._get_universe_domain(None, None) == RegionalInventoryServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - RegionalInventoryServiceClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - - -@pytest.mark.parametrize("client_class,transport_name", [ - (RegionalInventoryServiceClient, "grpc"), - (RegionalInventoryServiceAsyncClient, "grpc_asyncio"), - (RegionalInventoryServiceClient, "rest"), -]) -def test_regional_inventory_service_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'merchantapi.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://merchantapi.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.RegionalInventoryServiceGrpcTransport, "grpc"), - (transports.RegionalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.RegionalInventoryServiceRestTransport, "rest"), -]) -def test_regional_inventory_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (RegionalInventoryServiceClient, "grpc"), - (RegionalInventoryServiceAsyncClient, "grpc_asyncio"), - (RegionalInventoryServiceClient, "rest"), -]) -def test_regional_inventory_service_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'merchantapi.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://merchantapi.googleapis.com' - ) - - -def test_regional_inventory_service_client_get_transport_class(): - transport = RegionalInventoryServiceClient.get_transport_class() - available_transports = [ - transports.RegionalInventoryServiceGrpcTransport, - transports.RegionalInventoryServiceRestTransport, - ] - assert transport in available_transports - - transport = RegionalInventoryServiceClient.get_transport_class("grpc") - assert transport == transports.RegionalInventoryServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (RegionalInventoryServiceClient, transports.RegionalInventoryServiceGrpcTransport, "grpc"), - (RegionalInventoryServiceAsyncClient, transports.RegionalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (RegionalInventoryServiceClient, transports.RegionalInventoryServiceRestTransport, "rest"), -]) -@mock.patch.object(RegionalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceClient)) -@mock.patch.object(RegionalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceAsyncClient)) -def test_regional_inventory_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(RegionalInventoryServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(RegionalInventoryServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (RegionalInventoryServiceClient, transports.RegionalInventoryServiceGrpcTransport, "grpc", "true"), - (RegionalInventoryServiceAsyncClient, transports.RegionalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (RegionalInventoryServiceClient, transports.RegionalInventoryServiceGrpcTransport, "grpc", "false"), - (RegionalInventoryServiceAsyncClient, transports.RegionalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (RegionalInventoryServiceClient, transports.RegionalInventoryServiceRestTransport, "rest", "true"), - (RegionalInventoryServiceClient, transports.RegionalInventoryServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(RegionalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceClient)) -@mock.patch.object(RegionalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_regional_inventory_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - RegionalInventoryServiceClient, RegionalInventoryServiceAsyncClient -]) -@mock.patch.object(RegionalInventoryServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegionalInventoryServiceClient)) -@mock.patch.object(RegionalInventoryServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegionalInventoryServiceAsyncClient)) -def test_regional_inventory_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - -@pytest.mark.parametrize("client_class", [ - RegionalInventoryServiceClient, RegionalInventoryServiceAsyncClient -]) -@mock.patch.object(RegionalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceClient)) -@mock.patch.object(RegionalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceAsyncClient)) -def test_regional_inventory_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = RegionalInventoryServiceClient._DEFAULT_UNIVERSE - default_endpoint = RegionalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = RegionalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", - # use ClientOptions.api_endpoint as the api endpoint regardless. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == api_override - - # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class(credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == default_endpoint - - # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", - # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - client = client_class(credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - - # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), - # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, - # and ClientOptions.universe_domain="bar.com", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. - options = client_options.ClientOptions() - universe_exists = hasattr(options, "universe_domain") - if universe_exists: - options = client_options.ClientOptions(universe_domain=mock_universe) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - else: - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) - assert client.universe_domain == (mock_universe if universe_exists else default_universe) - - # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. - options = client_options.ClientOptions() - if hasattr(options, "universe_domain"): - delattr(options, "universe_domain") - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == default_endpoint - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (RegionalInventoryServiceClient, transports.RegionalInventoryServiceGrpcTransport, "grpc"), - (RegionalInventoryServiceAsyncClient, transports.RegionalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (RegionalInventoryServiceClient, transports.RegionalInventoryServiceRestTransport, "rest"), -]) -def test_regional_inventory_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (RegionalInventoryServiceClient, transports.RegionalInventoryServiceGrpcTransport, "grpc", grpc_helpers), - (RegionalInventoryServiceAsyncClient, transports.RegionalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (RegionalInventoryServiceClient, transports.RegionalInventoryServiceRestTransport, "rest", None), -]) -def test_regional_inventory_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_regional_inventory_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.transports.RegionalInventoryServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = RegionalInventoryServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (RegionalInventoryServiceClient, transports.RegionalInventoryServiceGrpcTransport, "grpc", grpc_helpers), - (RegionalInventoryServiceAsyncClient, transports.RegionalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_regional_inventory_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "merchantapi.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/content', -), - scopes=None, - default_host="merchantapi.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - regionalinventory.ListRegionalInventoriesRequest, - dict, -]) -def test_list_regional_inventories(request_type, transport: str = 'grpc'): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_regional_inventories), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = regionalinventory.ListRegionalInventoriesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_regional_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = regionalinventory.ListRegionalInventoriesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListRegionalInventoriesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_regional_inventories_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = regionalinventory.ListRegionalInventoriesRequest( - parent='parent_value', - page_token='page_token_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_regional_inventories), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_regional_inventories(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == regionalinventory.ListRegionalInventoriesRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_regional_inventories_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_regional_inventories in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_regional_inventories] = mock_rpc - request = {} - client.list_regional_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_regional_inventories(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_regional_inventories_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = RegionalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.list_regional_inventories in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.list_regional_inventories] = mock_rpc - - request = {} - await client.list_regional_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_regional_inventories(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_regional_inventories_async(transport: str = 'grpc_asyncio', request_type=regionalinventory.ListRegionalInventoriesRequest): - client = RegionalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_regional_inventories), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(regionalinventory.ListRegionalInventoriesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_regional_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = regionalinventory.ListRegionalInventoriesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListRegionalInventoriesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_regional_inventories_async_from_dict(): - await test_list_regional_inventories_async(request_type=dict) - -def test_list_regional_inventories_field_headers(): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = regionalinventory.ListRegionalInventoriesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_regional_inventories), - '__call__') as call: - call.return_value = regionalinventory.ListRegionalInventoriesResponse() - client.list_regional_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_regional_inventories_field_headers_async(): - client = RegionalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = regionalinventory.ListRegionalInventoriesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_regional_inventories), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regionalinventory.ListRegionalInventoriesResponse()) - await client.list_regional_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_list_regional_inventories_flattened(): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_regional_inventories), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = regionalinventory.ListRegionalInventoriesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_regional_inventories( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_regional_inventories_flattened_error(): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_regional_inventories( - regionalinventory.ListRegionalInventoriesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_regional_inventories_flattened_async(): - client = RegionalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_regional_inventories), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = regionalinventory.ListRegionalInventoriesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regionalinventory.ListRegionalInventoriesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_regional_inventories( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_regional_inventories_flattened_error_async(): - client = RegionalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_regional_inventories( - regionalinventory.ListRegionalInventoriesRequest(), - parent='parent_value', - ) - - -def test_list_regional_inventories_pager(transport_name: str = "grpc"): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_regional_inventories), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - regionalinventory.ListRegionalInventoriesResponse( - regional_inventories=[ - regionalinventory.RegionalInventory(), - regionalinventory.RegionalInventory(), - regionalinventory.RegionalInventory(), - ], - next_page_token='abc', - ), - regionalinventory.ListRegionalInventoriesResponse( - regional_inventories=[], - next_page_token='def', - ), - regionalinventory.ListRegionalInventoriesResponse( - regional_inventories=[ - regionalinventory.RegionalInventory(), - ], - next_page_token='ghi', - ), - regionalinventory.ListRegionalInventoriesResponse( - regional_inventories=[ - regionalinventory.RegionalInventory(), - regionalinventory.RegionalInventory(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_regional_inventories(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, regionalinventory.RegionalInventory) - for i in results) -def test_list_regional_inventories_pages(transport_name: str = "grpc"): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_regional_inventories), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - regionalinventory.ListRegionalInventoriesResponse( - regional_inventories=[ - regionalinventory.RegionalInventory(), - regionalinventory.RegionalInventory(), - regionalinventory.RegionalInventory(), - ], - next_page_token='abc', - ), - regionalinventory.ListRegionalInventoriesResponse( - regional_inventories=[], - next_page_token='def', - ), - regionalinventory.ListRegionalInventoriesResponse( - regional_inventories=[ - regionalinventory.RegionalInventory(), - ], - next_page_token='ghi', - ), - regionalinventory.ListRegionalInventoriesResponse( - regional_inventories=[ - regionalinventory.RegionalInventory(), - regionalinventory.RegionalInventory(), - ], - ), - RuntimeError, - ) - pages = list(client.list_regional_inventories(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_regional_inventories_async_pager(): - client = RegionalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_regional_inventories), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - regionalinventory.ListRegionalInventoriesResponse( - regional_inventories=[ - regionalinventory.RegionalInventory(), - regionalinventory.RegionalInventory(), - regionalinventory.RegionalInventory(), - ], - next_page_token='abc', - ), - regionalinventory.ListRegionalInventoriesResponse( - regional_inventories=[], - next_page_token='def', - ), - regionalinventory.ListRegionalInventoriesResponse( - regional_inventories=[ - regionalinventory.RegionalInventory(), - ], - next_page_token='ghi', - ), - regionalinventory.ListRegionalInventoriesResponse( - regional_inventories=[ - regionalinventory.RegionalInventory(), - regionalinventory.RegionalInventory(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_regional_inventories(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, regionalinventory.RegionalInventory) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_regional_inventories_async_pages(): - client = RegionalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_regional_inventories), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - regionalinventory.ListRegionalInventoriesResponse( - regional_inventories=[ - regionalinventory.RegionalInventory(), - regionalinventory.RegionalInventory(), - regionalinventory.RegionalInventory(), - ], - next_page_token='abc', - ), - regionalinventory.ListRegionalInventoriesResponse( - regional_inventories=[], - next_page_token='def', - ), - regionalinventory.ListRegionalInventoriesResponse( - regional_inventories=[ - regionalinventory.RegionalInventory(), - ], - next_page_token='ghi', - ), - regionalinventory.ListRegionalInventoriesResponse( - regional_inventories=[ - regionalinventory.RegionalInventory(), - regionalinventory.RegionalInventory(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_regional_inventories(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - regionalinventory.InsertRegionalInventoryRequest, - dict, -]) -def test_insert_regional_inventory(request_type, transport: str = 'grpc'): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.insert_regional_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = regionalinventory.RegionalInventory( - name='name_value', - account=749, - region='region_value', - availability='availability_value', - ) - response = client.insert_regional_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = regionalinventory.InsertRegionalInventoryRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, regionalinventory.RegionalInventory) - assert response.name == 'name_value' - assert response.account == 749 - assert response.region == 'region_value' - assert response.availability == 'availability_value' - - -def test_insert_regional_inventory_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = regionalinventory.InsertRegionalInventoryRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.insert_regional_inventory), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.insert_regional_inventory(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == regionalinventory.InsertRegionalInventoryRequest( - parent='parent_value', - ) - -def test_insert_regional_inventory_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.insert_regional_inventory in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.insert_regional_inventory] = mock_rpc - request = {} - client.insert_regional_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.insert_regional_inventory(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_insert_regional_inventory_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = RegionalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.insert_regional_inventory in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.insert_regional_inventory] = mock_rpc - - request = {} - await client.insert_regional_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.insert_regional_inventory(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_insert_regional_inventory_async(transport: str = 'grpc_asyncio', request_type=regionalinventory.InsertRegionalInventoryRequest): - client = RegionalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.insert_regional_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(regionalinventory.RegionalInventory( - name='name_value', - account=749, - region='region_value', - availability='availability_value', - )) - response = await client.insert_regional_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = regionalinventory.InsertRegionalInventoryRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, regionalinventory.RegionalInventory) - assert response.name == 'name_value' - assert response.account == 749 - assert response.region == 'region_value' - assert response.availability == 'availability_value' - - -@pytest.mark.asyncio -async def test_insert_regional_inventory_async_from_dict(): - await test_insert_regional_inventory_async(request_type=dict) - -def test_insert_regional_inventory_field_headers(): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = regionalinventory.InsertRegionalInventoryRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.insert_regional_inventory), - '__call__') as call: - call.return_value = regionalinventory.RegionalInventory() - client.insert_regional_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_insert_regional_inventory_field_headers_async(): - client = RegionalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = regionalinventory.InsertRegionalInventoryRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.insert_regional_inventory), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regionalinventory.RegionalInventory()) - await client.insert_regional_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - regionalinventory.DeleteRegionalInventoryRequest, - dict, -]) -def test_delete_regional_inventory(request_type, transport: str = 'grpc'): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_regional_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_regional_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = regionalinventory.DeleteRegionalInventoryRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_regional_inventory_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = regionalinventory.DeleteRegionalInventoryRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_regional_inventory), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_regional_inventory(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == regionalinventory.DeleteRegionalInventoryRequest( - name='name_value', - ) - -def test_delete_regional_inventory_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.delete_regional_inventory in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.delete_regional_inventory] = mock_rpc - request = {} - client.delete_regional_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_regional_inventory(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_regional_inventory_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = RegionalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.delete_regional_inventory in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.delete_regional_inventory] = mock_rpc - - request = {} - await client.delete_regional_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.delete_regional_inventory(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_regional_inventory_async(transport: str = 'grpc_asyncio', request_type=regionalinventory.DeleteRegionalInventoryRequest): - client = RegionalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_regional_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_regional_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = regionalinventory.DeleteRegionalInventoryRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_regional_inventory_async_from_dict(): - await test_delete_regional_inventory_async(request_type=dict) - -def test_delete_regional_inventory_field_headers(): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = regionalinventory.DeleteRegionalInventoryRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_regional_inventory), - '__call__') as call: - call.return_value = None - client.delete_regional_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_regional_inventory_field_headers_async(): - client = RegionalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = regionalinventory.DeleteRegionalInventoryRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_regional_inventory), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_regional_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_delete_regional_inventory_flattened(): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_regional_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_regional_inventory( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_regional_inventory_flattened_error(): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_regional_inventory( - regionalinventory.DeleteRegionalInventoryRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_regional_inventory_flattened_async(): - client = RegionalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_regional_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_regional_inventory( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_regional_inventory_flattened_error_async(): - client = RegionalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_regional_inventory( - regionalinventory.DeleteRegionalInventoryRequest(), - name='name_value', - ) - - -def test_list_regional_inventories_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_regional_inventories in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_regional_inventories] = mock_rpc - - request = {} - client.list_regional_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_regional_inventories(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_list_regional_inventories_rest_required_fields(request_type=regionalinventory.ListRegionalInventoriesRequest): - transport_class = transports.RegionalInventoryServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_regional_inventories._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_regional_inventories._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = regionalinventory.ListRegionalInventoriesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = regionalinventory.ListRegionalInventoriesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.list_regional_inventories(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_regional_inventories_rest_unset_required_fields(): - transport = transports.RegionalInventoryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_regional_inventories._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_regional_inventories_rest_flattened(): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = regionalinventory.ListRegionalInventoriesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'accounts/sample1/products/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = regionalinventory.ListRegionalInventoriesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.list_regional_inventories(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/inventories/v1beta/{parent=accounts/*/products/*}/regionalInventories" % client.transport._host, args[1]) - - -def test_list_regional_inventories_rest_flattened_error(transport: str = 'rest'): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_regional_inventories( - regionalinventory.ListRegionalInventoriesRequest(), - parent='parent_value', - ) - - -def test_list_regional_inventories_rest_pager(transport: str = 'rest'): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - regionalinventory.ListRegionalInventoriesResponse( - regional_inventories=[ - regionalinventory.RegionalInventory(), - regionalinventory.RegionalInventory(), - regionalinventory.RegionalInventory(), - ], - next_page_token='abc', - ), - regionalinventory.ListRegionalInventoriesResponse( - regional_inventories=[], - next_page_token='def', - ), - regionalinventory.ListRegionalInventoriesResponse( - regional_inventories=[ - regionalinventory.RegionalInventory(), - ], - next_page_token='ghi', - ), - regionalinventory.ListRegionalInventoriesResponse( - regional_inventories=[ - regionalinventory.RegionalInventory(), - regionalinventory.RegionalInventory(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(regionalinventory.ListRegionalInventoriesResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'accounts/sample1/products/sample2'} - - pager = client.list_regional_inventories(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, regionalinventory.RegionalInventory) - for i in results) - - pages = list(client.list_regional_inventories(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_insert_regional_inventory_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.insert_regional_inventory in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.insert_regional_inventory] = mock_rpc - - request = {} - client.insert_regional_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.insert_regional_inventory(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_insert_regional_inventory_rest_required_fields(request_type=regionalinventory.InsertRegionalInventoryRequest): - transport_class = transports.RegionalInventoryServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).insert_regional_inventory._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).insert_regional_inventory._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = regionalinventory.RegionalInventory() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = regionalinventory.RegionalInventory.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.insert_regional_inventory(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_insert_regional_inventory_rest_unset_required_fields(): - transport = transports.RegionalInventoryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.insert_regional_inventory._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "regionalInventory", ))) - - -def test_delete_regional_inventory_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.delete_regional_inventory in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.delete_regional_inventory] = mock_rpc - - request = {} - client.delete_regional_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_regional_inventory(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_delete_regional_inventory_rest_required_fields(request_type=regionalinventory.DeleteRegionalInventoryRequest): - transport_class = transports.RegionalInventoryServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_regional_inventory._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_regional_inventory._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = None - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.delete_regional_inventory(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_regional_inventory_rest_unset_required_fields(): - transport = transports.RegionalInventoryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_regional_inventory._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_delete_regional_inventory_rest_flattened(): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/products/sample2/regionalInventories/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.delete_regional_inventory(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/inventories/v1beta/{name=accounts/*/products/*/regionalInventories/*}" % client.transport._host, args[1]) - - -def test_delete_regional_inventory_rest_flattened_error(transport: str = 'rest'): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_regional_inventory( - regionalinventory.DeleteRegionalInventoryRequest(), - name='name_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.RegionalInventoryServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.RegionalInventoryServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RegionalInventoryServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.RegionalInventoryServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = RegionalInventoryServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = RegionalInventoryServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.RegionalInventoryServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RegionalInventoryServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.RegionalInventoryServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = RegionalInventoryServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.RegionalInventoryServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.RegionalInventoryServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.RegionalInventoryServiceGrpcTransport, - transports.RegionalInventoryServiceGrpcAsyncIOTransport, - transports.RegionalInventoryServiceRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_kind_grpc(): - transport = RegionalInventoryServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_regional_inventories_empty_call_grpc(): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_regional_inventories), - '__call__') as call: - call.return_value = regionalinventory.ListRegionalInventoriesResponse() - client.list_regional_inventories(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = regionalinventory.ListRegionalInventoriesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_insert_regional_inventory_empty_call_grpc(): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.insert_regional_inventory), - '__call__') as call: - call.return_value = regionalinventory.RegionalInventory() - client.insert_regional_inventory(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = regionalinventory.InsertRegionalInventoryRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_regional_inventory_empty_call_grpc(): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_regional_inventory), - '__call__') as call: - call.return_value = None - client.delete_regional_inventory(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = regionalinventory.DeleteRegionalInventoryRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = RegionalInventoryServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = RegionalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_regional_inventories_empty_call_grpc_asyncio(): - client = RegionalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_regional_inventories), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regionalinventory.ListRegionalInventoriesResponse( - next_page_token='next_page_token_value', - )) - await client.list_regional_inventories(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = regionalinventory.ListRegionalInventoriesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_insert_regional_inventory_empty_call_grpc_asyncio(): - client = RegionalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.insert_regional_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regionalinventory.RegionalInventory( - name='name_value', - account=749, - region='region_value', - availability='availability_value', - )) - await client.insert_regional_inventory(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = regionalinventory.InsertRegionalInventoryRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_delete_regional_inventory_empty_call_grpc_asyncio(): - client = RegionalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_regional_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_regional_inventory(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = regionalinventory.DeleteRegionalInventoryRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = RegionalInventoryServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_list_regional_inventories_rest_bad_request(request_type=regionalinventory.ListRegionalInventoriesRequest): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1/products/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_regional_inventories(request) - - -@pytest.mark.parametrize("request_type", [ - regionalinventory.ListRegionalInventoriesRequest, - dict, -]) -def test_list_regional_inventories_rest_call_success(request_type): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1/products/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = regionalinventory.ListRegionalInventoriesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = regionalinventory.ListRegionalInventoriesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_regional_inventories(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListRegionalInventoriesPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_regional_inventories_rest_interceptors(null_interceptor): - transport = transports.RegionalInventoryServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegionalInventoryServiceRestInterceptor(), - ) - client = RegionalInventoryServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RegionalInventoryServiceRestInterceptor, "post_list_regional_inventories") as post, \ - mock.patch.object(transports.RegionalInventoryServiceRestInterceptor, "pre_list_regional_inventories") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = regionalinventory.ListRegionalInventoriesRequest.pb(regionalinventory.ListRegionalInventoriesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = regionalinventory.ListRegionalInventoriesResponse.to_json(regionalinventory.ListRegionalInventoriesResponse()) - req.return_value.content = return_value - - request = regionalinventory.ListRegionalInventoriesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = regionalinventory.ListRegionalInventoriesResponse() - - client.list_regional_inventories(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_insert_regional_inventory_rest_bad_request(request_type=regionalinventory.InsertRegionalInventoryRequest): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1/products/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.insert_regional_inventory(request) - - -@pytest.mark.parametrize("request_type", [ - regionalinventory.InsertRegionalInventoryRequest, - dict, -]) -def test_insert_regional_inventory_rest_call_success(request_type): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1/products/sample2'} - request_init["regional_inventory"] = {'name': 'name_value', 'account': 749, 'region': 'region_value', 'price': {'amount_micros': 1408, 'currency_code': 'currency_code_value'}, 'sale_price': {}, 'sale_price_effective_date': {'start_time': {'seconds': 751, 'nanos': 543}, 'end_time': {}}, 'availability': 'availability_value', 'custom_attributes': [{'name': 'name_value', 'value': 'value_value', 'group_values': {}}]} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = regionalinventory.InsertRegionalInventoryRequest.meta.fields["regional_inventory"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["regional_inventory"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["regional_inventory"][field])): - del request_init["regional_inventory"][field][i][subfield] - else: - del request_init["regional_inventory"][field][subfield] - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = regionalinventory.RegionalInventory( - name='name_value', - account=749, - region='region_value', - availability='availability_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = regionalinventory.RegionalInventory.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.insert_regional_inventory(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, regionalinventory.RegionalInventory) - assert response.name == 'name_value' - assert response.account == 749 - assert response.region == 'region_value' - assert response.availability == 'availability_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_insert_regional_inventory_rest_interceptors(null_interceptor): - transport = transports.RegionalInventoryServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegionalInventoryServiceRestInterceptor(), - ) - client = RegionalInventoryServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RegionalInventoryServiceRestInterceptor, "post_insert_regional_inventory") as post, \ - mock.patch.object(transports.RegionalInventoryServiceRestInterceptor, "pre_insert_regional_inventory") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = regionalinventory.InsertRegionalInventoryRequest.pb(regionalinventory.InsertRegionalInventoryRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = regionalinventory.RegionalInventory.to_json(regionalinventory.RegionalInventory()) - req.return_value.content = return_value - - request = regionalinventory.InsertRegionalInventoryRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = regionalinventory.RegionalInventory() - - client.insert_regional_inventory(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_regional_inventory_rest_bad_request(request_type=regionalinventory.DeleteRegionalInventoryRequest): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/products/sample2/regionalInventories/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_regional_inventory(request) - - -@pytest.mark.parametrize("request_type", [ - regionalinventory.DeleteRegionalInventoryRequest, - dict, -]) -def test_delete_regional_inventory_rest_call_success(request_type): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/products/sample2/regionalInventories/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = '' - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_regional_inventory(request) - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_regional_inventory_rest_interceptors(null_interceptor): - transport = transports.RegionalInventoryServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegionalInventoryServiceRestInterceptor(), - ) - client = RegionalInventoryServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RegionalInventoryServiceRestInterceptor, "pre_delete_regional_inventory") as pre: - pre.assert_not_called() - pb_message = regionalinventory.DeleteRegionalInventoryRequest.pb(regionalinventory.DeleteRegionalInventoryRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - request = regionalinventory.DeleteRegionalInventoryRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_regional_inventory(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - -def test_initialize_client_w_rest(): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_regional_inventories_empty_call_rest(): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_regional_inventories), - '__call__') as call: - client.list_regional_inventories(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = regionalinventory.ListRegionalInventoriesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_insert_regional_inventory_empty_call_rest(): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.insert_regional_inventory), - '__call__') as call: - client.insert_regional_inventory(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = regionalinventory.InsertRegionalInventoryRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_regional_inventory_empty_call_rest(): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_regional_inventory), - '__call__') as call: - client.delete_regional_inventory(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = regionalinventory.DeleteRegionalInventoryRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.RegionalInventoryServiceGrpcTransport, - ) - -def test_regional_inventory_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.RegionalInventoryServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_regional_inventory_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.transports.RegionalInventoryServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.RegionalInventoryServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_regional_inventories', - 'insert_regional_inventory', - 'delete_regional_inventory', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_regional_inventory_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.transports.RegionalInventoryServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.RegionalInventoryServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/content', -), - quota_project_id="octopus", - ) - - -def test_regional_inventory_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.transports.RegionalInventoryServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.RegionalInventoryServiceTransport() - adc.assert_called_once() - - -def test_regional_inventory_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - RegionalInventoryServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/content', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.RegionalInventoryServiceGrpcTransport, - transports.RegionalInventoryServiceGrpcAsyncIOTransport, - ], -) -def test_regional_inventory_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/content',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.RegionalInventoryServiceGrpcTransport, - transports.RegionalInventoryServiceGrpcAsyncIOTransport, - transports.RegionalInventoryServiceRestTransport, - ], -) -def test_regional_inventory_service_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.RegionalInventoryServiceGrpcTransport, grpc_helpers), - (transports.RegionalInventoryServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_regional_inventory_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "merchantapi.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/content', -), - scopes=["1", "2"], - default_host="merchantapi.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.RegionalInventoryServiceGrpcTransport, transports.RegionalInventoryServiceGrpcAsyncIOTransport]) -def test_regional_inventory_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_regional_inventory_service_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.RegionalInventoryServiceRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_regional_inventory_service_host_no_port(transport_name): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='merchantapi.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'merchantapi.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://merchantapi.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_regional_inventory_service_host_with_port(transport_name): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='merchantapi.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'merchantapi.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://merchantapi.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_regional_inventory_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = RegionalInventoryServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = RegionalInventoryServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_regional_inventories._session - session2 = client2.transport.list_regional_inventories._session - assert session1 != session2 - session1 = client1.transport.insert_regional_inventory._session - session2 = client2.transport.insert_regional_inventory._session - assert session1 != session2 - session1 = client1.transport.delete_regional_inventory._session - session2 = client2.transport.delete_regional_inventory._session - assert session1 != session2 -def test_regional_inventory_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.RegionalInventoryServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_regional_inventory_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.RegionalInventoryServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.RegionalInventoryServiceGrpcTransport, transports.RegionalInventoryServiceGrpcAsyncIOTransport]) -def test_regional_inventory_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.RegionalInventoryServiceGrpcTransport, transports.RegionalInventoryServiceGrpcAsyncIOTransport]) -def test_regional_inventory_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_regional_inventory_path(): - account = "squid" - product = "clam" - region = "whelk" - expected = "accounts/{account}/products/{product}/regionalInventories/{region}".format(account=account, product=product, region=region, ) - actual = RegionalInventoryServiceClient.regional_inventory_path(account, product, region) - assert expected == actual - - -def test_parse_regional_inventory_path(): - expected = { - "account": "octopus", - "product": "oyster", - "region": "nudibranch", - } - path = RegionalInventoryServiceClient.regional_inventory_path(**expected) - - # Check that the path construction is reversible. - actual = RegionalInventoryServiceClient.parse_regional_inventory_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = RegionalInventoryServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = RegionalInventoryServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = RegionalInventoryServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = RegionalInventoryServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = RegionalInventoryServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = RegionalInventoryServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = RegionalInventoryServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = RegionalInventoryServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = RegionalInventoryServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = RegionalInventoryServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = RegionalInventoryServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = RegionalInventoryServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = RegionalInventoryServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = RegionalInventoryServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = RegionalInventoryServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.RegionalInventoryServiceTransport, '_prep_wrapped_messages') as prep: - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.RegionalInventoryServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = RegionalInventoryServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -def test_transport_close_grpc(): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" - ) - with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - - -@pytest.mark.asyncio -async def test_transport_close_grpc_asyncio(): - client = RegionalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" - ) - with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close_rest(): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - with mock.patch.object(type(getattr(client.transport, "_session")), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (RegionalInventoryServiceClient, transports.RegionalInventoryServiceGrpcTransport), - (RegionalInventoryServiceAsyncClient, transports.RegionalInventoryServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/.coveragerc b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/.coveragerc deleted file mode 100644 index b0d5d8ec19fc..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/shopping/merchant_lfp/__init__.py - google/shopping/merchant_lfp/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-lfp/v1beta/.flake8 b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/MANIFEST.in b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/MANIFEST.in deleted file mode 100644 index f8f949b2a9d9..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/shopping/merchant_lfp *.py -recursive-include google/shopping/merchant_lfp_v1beta *.py diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/README.rst b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/README.rst deleted file mode 100644 index 10235930e853..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Shopping Merchant Lfp 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 Lfp 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 diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/_static/custom.css b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/_static/custom.css +++ /dev/null @@ -1,3 +0,0 @@ -dl.field-list > dt { - min-width: 100px -} diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/conf.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/conf.py deleted file mode 100644 index 666ccbca902c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-lfp 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("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# 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.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -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-lfp" -copyright = u"2023, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# 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 = 'en' - -# 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"] - -# 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 Python", - "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-lfp-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-lfp.tex", - u"google-shopping-merchant-lfp 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-lfp", - u"Google Shopping Merchant Lfp 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-lfp", - u"google-shopping-merchant-lfp Documentation", - author, - "google-shopping-merchant-lfp", - "GAPIC library for Google Shopping Merchant Lfp API", - "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": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", 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-lfp/v1beta/docs/index.rst b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/index.rst deleted file mode 100644 index da51952965f1..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - merchant_lfp_v1beta/services_ - merchant_lfp_v1beta/types_ diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/merchant_lfp_v1beta/lfp_inventory_service.rst b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/merchant_lfp_v1beta/lfp_inventory_service.rst deleted file mode 100644 index bec997d8d55e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/merchant_lfp_v1beta/lfp_inventory_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -LfpInventoryService -------------------------------------- - -.. automodule:: google.shopping.merchant_lfp_v1beta.services.lfp_inventory_service - :members: - :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/merchant_lfp_v1beta/lfp_sale_service.rst b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/merchant_lfp_v1beta/lfp_sale_service.rst deleted file mode 100644 index 0d6ff3402769..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/merchant_lfp_v1beta/lfp_sale_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -LfpSaleService --------------------------------- - -.. automodule:: google.shopping.merchant_lfp_v1beta.services.lfp_sale_service - :members: - :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/merchant_lfp_v1beta/lfp_store_service.rst b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/merchant_lfp_v1beta/lfp_store_service.rst deleted file mode 100644 index 5c836ac7e718..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/merchant_lfp_v1beta/lfp_store_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -LfpStoreService ---------------------------------- - -.. automodule:: google.shopping.merchant_lfp_v1beta.services.lfp_store_service - :members: - :inherited-members: - -.. automodule:: google.shopping.merchant_lfp_v1beta.services.lfp_store_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/merchant_lfp_v1beta/services_.rst b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/merchant_lfp_v1beta/services_.rst deleted file mode 100644 index 799a587ac9ec..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/merchant_lfp_v1beta/services_.rst +++ /dev/null @@ -1,8 +0,0 @@ -Services for Google Shopping Merchant Lfp v1beta API -==================================================== -.. toctree:: - :maxdepth: 2 - - lfp_inventory_service - lfp_sale_service - lfp_store_service diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/merchant_lfp_v1beta/types_.rst b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/merchant_lfp_v1beta/types_.rst deleted file mode 100644 index 71508ca1ae9e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/docs/merchant_lfp_v1beta/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Shopping Merchant Lfp v1beta API -================================================= - -.. automodule:: google.shopping.merchant_lfp_v1beta.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp/__init__.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp/__init__.py deleted file mode 100644 index 6a3c87cb8651..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp/__init__.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_lfp import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.shopping.merchant_lfp_v1beta.services.lfp_inventory_service.client import LfpInventoryServiceClient -from google.shopping.merchant_lfp_v1beta.services.lfp_inventory_service.async_client import LfpInventoryServiceAsyncClient -from google.shopping.merchant_lfp_v1beta.services.lfp_sale_service.client import LfpSaleServiceClient -from google.shopping.merchant_lfp_v1beta.services.lfp_sale_service.async_client import LfpSaleServiceAsyncClient -from google.shopping.merchant_lfp_v1beta.services.lfp_store_service.client import LfpStoreServiceClient -from google.shopping.merchant_lfp_v1beta.services.lfp_store_service.async_client import LfpStoreServiceAsyncClient - -from google.shopping.merchant_lfp_v1beta.types.lfpinventory import InsertLfpInventoryRequest -from google.shopping.merchant_lfp_v1beta.types.lfpinventory import LfpInventory -from google.shopping.merchant_lfp_v1beta.types.lfpsale import InsertLfpSaleRequest -from google.shopping.merchant_lfp_v1beta.types.lfpsale import LfpSale -from google.shopping.merchant_lfp_v1beta.types.lfpstore import DeleteLfpStoreRequest -from google.shopping.merchant_lfp_v1beta.types.lfpstore import GetLfpStoreRequest -from google.shopping.merchant_lfp_v1beta.types.lfpstore import InsertLfpStoreRequest -from google.shopping.merchant_lfp_v1beta.types.lfpstore import LfpStore -from google.shopping.merchant_lfp_v1beta.types.lfpstore import ListLfpStoresRequest -from google.shopping.merchant_lfp_v1beta.types.lfpstore import ListLfpStoresResponse - -__all__ = ('LfpInventoryServiceClient', - 'LfpInventoryServiceAsyncClient', - 'LfpSaleServiceClient', - 'LfpSaleServiceAsyncClient', - 'LfpStoreServiceClient', - 'LfpStoreServiceAsyncClient', - 'InsertLfpInventoryRequest', - 'LfpInventory', - 'InsertLfpSaleRequest', - 'LfpSale', - 'DeleteLfpStoreRequest', - 'GetLfpStoreRequest', - 'InsertLfpStoreRequest', - 'LfpStore', - 'ListLfpStoresRequest', - 'ListLfpStoresResponse', -) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp/gapic_version.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-lfp/v1beta/google/shopping/merchant_lfp/py.typed b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp/py.typed deleted file mode 100644 index da994d195527..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-shopping-merchant-lfp package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/__init__.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/__init__.py deleted file mode 100644 index f5221f93e79c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/__init__.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_lfp_v1beta import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.lfp_inventory_service import LfpInventoryServiceClient -from .services.lfp_inventory_service import LfpInventoryServiceAsyncClient -from .services.lfp_sale_service import LfpSaleServiceClient -from .services.lfp_sale_service import LfpSaleServiceAsyncClient -from .services.lfp_store_service import LfpStoreServiceClient -from .services.lfp_store_service import LfpStoreServiceAsyncClient - -from .types.lfpinventory import InsertLfpInventoryRequest -from .types.lfpinventory import LfpInventory -from .types.lfpsale import InsertLfpSaleRequest -from .types.lfpsale import LfpSale -from .types.lfpstore import DeleteLfpStoreRequest -from .types.lfpstore import GetLfpStoreRequest -from .types.lfpstore import InsertLfpStoreRequest -from .types.lfpstore import LfpStore -from .types.lfpstore import ListLfpStoresRequest -from .types.lfpstore import ListLfpStoresResponse - -__all__ = ( - 'LfpInventoryServiceAsyncClient', - 'LfpSaleServiceAsyncClient', - 'LfpStoreServiceAsyncClient', -'DeleteLfpStoreRequest', -'GetLfpStoreRequest', -'InsertLfpInventoryRequest', -'InsertLfpSaleRequest', -'InsertLfpStoreRequest', -'LfpInventory', -'LfpInventoryServiceClient', -'LfpSale', -'LfpSaleServiceClient', -'LfpStore', -'LfpStoreServiceClient', -'ListLfpStoresRequest', -'ListLfpStoresResponse', -) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/gapic_metadata.json b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/gapic_metadata.json deleted file mode 100644 index 8f3360964705..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/gapic_metadata.json +++ /dev/null @@ -1,156 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.shopping.merchant_lfp_v1beta", - "protoPackage": "google.shopping.merchant.lfp.v1beta", - "schema": "1.0", - "services": { - "LfpInventoryService": { - "clients": { - "grpc": { - "libraryClient": "LfpInventoryServiceClient", - "rpcs": { - "InsertLfpInventory": { - "methods": [ - "insert_lfp_inventory" - ] - } - } - }, - "grpc-async": { - "libraryClient": "LfpInventoryServiceAsyncClient", - "rpcs": { - "InsertLfpInventory": { - "methods": [ - "insert_lfp_inventory" - ] - } - } - }, - "rest": { - "libraryClient": "LfpInventoryServiceClient", - "rpcs": { - "InsertLfpInventory": { - "methods": [ - "insert_lfp_inventory" - ] - } - } - } - } - }, - "LfpSaleService": { - "clients": { - "grpc": { - "libraryClient": "LfpSaleServiceClient", - "rpcs": { - "InsertLfpSale": { - "methods": [ - "insert_lfp_sale" - ] - } - } - }, - "grpc-async": { - "libraryClient": "LfpSaleServiceAsyncClient", - "rpcs": { - "InsertLfpSale": { - "methods": [ - "insert_lfp_sale" - ] - } - } - }, - "rest": { - "libraryClient": "LfpSaleServiceClient", - "rpcs": { - "InsertLfpSale": { - "methods": [ - "insert_lfp_sale" - ] - } - } - } - } - }, - "LfpStoreService": { - "clients": { - "grpc": { - "libraryClient": "LfpStoreServiceClient", - "rpcs": { - "DeleteLfpStore": { - "methods": [ - "delete_lfp_store" - ] - }, - "GetLfpStore": { - "methods": [ - "get_lfp_store" - ] - }, - "InsertLfpStore": { - "methods": [ - "insert_lfp_store" - ] - }, - "ListLfpStores": { - "methods": [ - "list_lfp_stores" - ] - } - } - }, - "grpc-async": { - "libraryClient": "LfpStoreServiceAsyncClient", - "rpcs": { - "DeleteLfpStore": { - "methods": [ - "delete_lfp_store" - ] - }, - "GetLfpStore": { - "methods": [ - "get_lfp_store" - ] - }, - "InsertLfpStore": { - "methods": [ - "insert_lfp_store" - ] - }, - "ListLfpStores": { - "methods": [ - "list_lfp_stores" - ] - } - } - }, - "rest": { - "libraryClient": "LfpStoreServiceClient", - "rpcs": { - "DeleteLfpStore": { - "methods": [ - "delete_lfp_store" - ] - }, - "GetLfpStore": { - "methods": [ - "get_lfp_store" - ] - }, - "InsertLfpStore": { - "methods": [ - "insert_lfp_store" - ] - }, - "ListLfpStores": { - "methods": [ - "list_lfp_stores" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/gapic_version.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-lfp/v1beta/google/shopping/merchant_lfp_v1beta/py.typed b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/py.typed deleted file mode 100644 index da994d195527..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-shopping-merchant-lfp package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/__init__.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/__init__.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/__init__.py deleted file mode 100644 index ee83eecc3a55..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 LfpInventoryServiceClient -from .async_client import LfpInventoryServiceAsyncClient - -__all__ = ( - 'LfpInventoryServiceClient', - 'LfpInventoryServiceAsyncClient', -) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/async_client.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/async_client.py deleted file mode 100644 index 5d709f778740..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/async_client.py +++ /dev/null @@ -1,357 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_lfp_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 - - -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 timestamp_pb2 # type: ignore -from google.shopping.merchant_lfp_v1beta.types import lfpinventory -from google.shopping.type.types import types -from .transports.base import LfpInventoryServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import LfpInventoryServiceGrpcAsyncIOTransport -from .client import LfpInventoryServiceClient - -try: - from google.api_core import client_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 LfpInventoryServiceAsyncClient: - """Service for a `LFP - partner `__ to - submit local inventories for a merchant. - """ - - _client: LfpInventoryServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = LfpInventoryServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = LfpInventoryServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = LfpInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = LfpInventoryServiceClient._DEFAULT_UNIVERSE - - lfp_inventory_path = staticmethod(LfpInventoryServiceClient.lfp_inventory_path) - parse_lfp_inventory_path = staticmethod(LfpInventoryServiceClient.parse_lfp_inventory_path) - common_billing_account_path = staticmethod(LfpInventoryServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(LfpInventoryServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(LfpInventoryServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(LfpInventoryServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(LfpInventoryServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(LfpInventoryServiceClient.parse_common_organization_path) - common_project_path = staticmethod(LfpInventoryServiceClient.common_project_path) - parse_common_project_path = staticmethod(LfpInventoryServiceClient.parse_common_project_path) - common_location_path = staticmethod(LfpInventoryServiceClient.common_location_path) - parse_common_location_path = staticmethod(LfpInventoryServiceClient.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: - LfpInventoryServiceAsyncClient: The constructed client. - """ - return LfpInventoryServiceClient.from_service_account_info.__func__(LfpInventoryServiceAsyncClient, 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: - LfpInventoryServiceAsyncClient: The constructed client. - """ - return LfpInventoryServiceClient.from_service_account_file.__func__(LfpInventoryServiceAsyncClient, 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 LfpInventoryServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> LfpInventoryServiceTransport: - """Returns the transport used by the client instance. - - Returns: - LfpInventoryServiceTransport: 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 = LfpInventoryServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, LfpInventoryServiceTransport, Callable[..., LfpInventoryServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the lfp inventory service async client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,LfpInventoryServiceTransport,Callable[..., LfpInventoryServiceTransport]]]): - 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 LfpInventoryServiceTransport 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 = LfpInventoryServiceClient( - 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.lfp_v1beta.LfpInventoryServiceAsyncClient`.", - extra = { - "serviceName": "google.shopping.merchant.lfp.v1beta.LfpInventoryService", - "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.lfp.v1beta.LfpInventoryService", - "credentialsType": None, - } - ) - - async def insert_lfp_inventory(self, - request: Optional[Union[lfpinventory.InsertLfpInventoryRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> lfpinventory.LfpInventory: - r"""Inserts a ``LfpInventory`` resource for the given target - merchant account. If the resource already exists, it will be - replaced. The inventory automatically expires after 30 days. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_lfp_v1beta - - async def sample_insert_lfp_inventory(): - # Create a client - client = merchant_lfp_v1beta.LfpInventoryServiceAsyncClient() - - # Initialize request argument(s) - lfp_inventory = merchant_lfp_v1beta.LfpInventory() - lfp_inventory.target_account = 1491 - lfp_inventory.store_code = "store_code_value" - lfp_inventory.offer_id = "offer_id_value" - lfp_inventory.region_code = "region_code_value" - lfp_inventory.content_language = "content_language_value" - lfp_inventory.availability = "availability_value" - - request = merchant_lfp_v1beta.InsertLfpInventoryRequest( - parent="parent_value", - lfp_inventory=lfp_inventory, - ) - - # Make the request - response = await client.insert_lfp_inventory(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_lfp_v1beta.types.InsertLfpInventoryRequest, dict]]): - The request object. Request message for the ``InsertLfpInventory`` 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_lfp_v1beta.types.LfpInventory: - Local Inventory for the merchant. - """ - # 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, lfpinventory.InsertLfpInventoryRequest): - request = lfpinventory.InsertLfpInventoryRequest(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_lfp_inventory] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self) -> "LfpInventoryServiceAsyncClient": - 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__) - - -__all__ = ( - "LfpInventoryServiceAsyncClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/client.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/client.py deleted file mode 100644 index 64e3e171ba8f..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/client.py +++ /dev/null @@ -1,693 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -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_lfp_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 - -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 timestamp_pb2 # type: ignore -from google.shopping.merchant_lfp_v1beta.types import lfpinventory -from google.shopping.type.types import types -from .transports.base import LfpInventoryServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import LfpInventoryServiceGrpcTransport -from .transports.grpc_asyncio import LfpInventoryServiceGrpcAsyncIOTransport -from .transports.rest import LfpInventoryServiceRestTransport - - -class LfpInventoryServiceClientMeta(type): - """Metaclass for the LfpInventoryService 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[LfpInventoryServiceTransport]] - _transport_registry["grpc"] = LfpInventoryServiceGrpcTransport - _transport_registry["grpc_asyncio"] = LfpInventoryServiceGrpcAsyncIOTransport - _transport_registry["rest"] = LfpInventoryServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[LfpInventoryServiceTransport]: - """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 LfpInventoryServiceClient(metaclass=LfpInventoryServiceClientMeta): - """Service for a `LFP - partner `__ to - submit local inventories for a merchant. - """ - - @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: - LfpInventoryServiceClient: 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: - LfpInventoryServiceClient: 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) -> LfpInventoryServiceTransport: - """Returns the transport used by the client instance. - - Returns: - LfpInventoryServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def lfp_inventory_path(account: str,target_merchant: str,store_code: str,offer: str,) -> str: - """Returns a fully-qualified lfp_inventory string.""" - return "accounts/{account}/lfpInventories/{target_merchant}~{store_code}~{offer}".format(account=account, target_merchant=target_merchant, store_code=store_code, offer=offer, ) - - @staticmethod - def parse_lfp_inventory_path(path: str) -> Dict[str,str]: - """Parses a lfp_inventory path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/lfpInventories/(?P.+?)~(?P.+?)~(?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 = LfpInventoryServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = LfpInventoryServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = LfpInventoryServiceClient._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 = LfpInventoryServiceClient._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 - - @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, LfpInventoryServiceTransport, Callable[..., LfpInventoryServiceTransport]]] = 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 inventory service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,LfpInventoryServiceTransport,Callable[..., LfpInventoryServiceTransport]]]): - 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 LfpInventoryServiceTransport 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 = LfpInventoryServiceClient._read_environment_variables() - self._client_cert_source = LfpInventoryServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = LfpInventoryServiceClient._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, LfpInventoryServiceTransport) - if transport_provided: - # transport is a LfpInventoryServiceTransport 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(LfpInventoryServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - LfpInventoryServiceClient._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[LfpInventoryServiceTransport], Callable[..., LfpInventoryServiceTransport]] = ( - LfpInventoryServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., LfpInventoryServiceTransport], 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.lfp_v1beta.LfpInventoryServiceClient`.", - extra = { - "serviceName": "google.shopping.merchant.lfp.v1beta.LfpInventoryService", - "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.lfp.v1beta.LfpInventoryService", - "credentialsType": None, - } - ) - - def insert_lfp_inventory(self, - request: Optional[Union[lfpinventory.InsertLfpInventoryRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> lfpinventory.LfpInventory: - r"""Inserts a ``LfpInventory`` resource for the given target - merchant account. If the resource already exists, it will be - replaced. The inventory automatically expires after 30 days. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_lfp_v1beta - - def sample_insert_lfp_inventory(): - # Create a client - client = merchant_lfp_v1beta.LfpInventoryServiceClient() - - # Initialize request argument(s) - lfp_inventory = merchant_lfp_v1beta.LfpInventory() - lfp_inventory.target_account = 1491 - lfp_inventory.store_code = "store_code_value" - lfp_inventory.offer_id = "offer_id_value" - lfp_inventory.region_code = "region_code_value" - lfp_inventory.content_language = "content_language_value" - lfp_inventory.availability = "availability_value" - - request = merchant_lfp_v1beta.InsertLfpInventoryRequest( - parent="parent_value", - lfp_inventory=lfp_inventory, - ) - - # Make the request - response = client.insert_lfp_inventory(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_lfp_v1beta.types.InsertLfpInventoryRequest, dict]): - The request object. Request message for the ``InsertLfpInventory`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.shopping.merchant_lfp_v1beta.types.LfpInventory: - Local Inventory for the merchant. - """ - # 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, lfpinventory.InsertLfpInventoryRequest): - request = lfpinventory.InsertLfpInventoryRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.insert_lfp_inventory] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "LfpInventoryServiceClient": - 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__) - - -__all__ = ( - "LfpInventoryServiceClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/README.rst deleted file mode 100644 index c4b5f2586c1a..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`LfpInventoryServiceTransport` is the ABC for all transports. -- public child `LfpInventoryServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `LfpInventoryServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseLfpInventoryServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `LfpInventoryServiceRestTransport` 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-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/__init__.py deleted file mode 100644 index 0d9048eb741f..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 LfpInventoryServiceTransport -from .grpc import LfpInventoryServiceGrpcTransport -from .grpc_asyncio import LfpInventoryServiceGrpcAsyncIOTransport -from .rest import LfpInventoryServiceRestTransport -from .rest import LfpInventoryServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[LfpInventoryServiceTransport]] -_transport_registry['grpc'] = LfpInventoryServiceGrpcTransport -_transport_registry['grpc_asyncio'] = LfpInventoryServiceGrpcAsyncIOTransport -_transport_registry['rest'] = LfpInventoryServiceRestTransport - -__all__ = ( - 'LfpInventoryServiceTransport', - 'LfpInventoryServiceGrpcTransport', - 'LfpInventoryServiceGrpcAsyncIOTransport', - 'LfpInventoryServiceRestTransport', - 'LfpInventoryServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/base.py deleted file mode 100644 index 73a179941ae6..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/base.py +++ /dev/null @@ -1,154 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_lfp_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 - -from google.shopping.merchant_lfp_v1beta.types import lfpinventory - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class LfpInventoryServiceTransport(abc.ABC): - """Abstract transport class for LfpInventoryService.""" - - 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.insert_lfp_inventory: gapic_v1.method.wrap_method( - self.insert_lfp_inventory, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def insert_lfp_inventory(self) -> Callable[ - [lfpinventory.InsertLfpInventoryRequest], - Union[ - lfpinventory.LfpInventory, - Awaitable[lfpinventory.LfpInventory] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'LfpInventoryServiceTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/grpc.py deleted file mode 100644 index d5f88e0239d8..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/grpc.py +++ /dev/null @@ -1,351 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_lfp_v1beta.types import lfpinventory -from .base import LfpInventoryServiceTransport, 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.lfp.v1beta.LfpInventoryService", - "rpcName": 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.lfp.v1beta.LfpInventoryService", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class LfpInventoryServiceGrpcTransport(LfpInventoryServiceTransport): - """gRPC backend transport for LfpInventoryService. - - Service for a `LFP - partner `__ to - submit local inventories for a merchant. - - This 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 insert_lfp_inventory(self) -> Callable[ - [lfpinventory.InsertLfpInventoryRequest], - lfpinventory.LfpInventory]: - r"""Return a callable for the insert lfp inventory method over gRPC. - - Inserts a ``LfpInventory`` resource for the given target - merchant account. If the resource already exists, it will be - replaced. The inventory automatically expires after 30 days. - - Returns: - Callable[[~.InsertLfpInventoryRequest], - ~.LfpInventory]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_lfp_inventory' not in self._stubs: - self._stubs['insert_lfp_inventory'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.lfp.v1beta.LfpInventoryService/InsertLfpInventory', - request_serializer=lfpinventory.InsertLfpInventoryRequest.serialize, - response_deserializer=lfpinventory.LfpInventory.deserialize, - ) - return self._stubs['insert_lfp_inventory'] - - def close(self): - self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'LfpInventoryServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/grpc_asyncio.py deleted file mode 100644 index 0f89e2fcd73c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,371 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_lfp_v1beta.types import lfpinventory -from .base import LfpInventoryServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import LfpInventoryServiceGrpcTransport - -try: - from google.api_core import client_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.lfp.v1beta.LfpInventoryService", - "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.lfp.v1beta.LfpInventoryService", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class LfpInventoryServiceGrpcAsyncIOTransport(LfpInventoryServiceTransport): - """gRPC AsyncIO backend transport for LfpInventoryService. - - Service for a `LFP - partner `__ to - submit local inventories for a merchant. - - This 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 insert_lfp_inventory(self) -> Callable[ - [lfpinventory.InsertLfpInventoryRequest], - Awaitable[lfpinventory.LfpInventory]]: - r"""Return a callable for the insert lfp inventory method over gRPC. - - Inserts a ``LfpInventory`` resource for the given target - merchant account. If the resource already exists, it will be - replaced. The inventory automatically expires after 30 days. - - Returns: - Callable[[~.InsertLfpInventoryRequest], - Awaitable[~.LfpInventory]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_lfp_inventory' not in self._stubs: - self._stubs['insert_lfp_inventory'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.lfp.v1beta.LfpInventoryService/InsertLfpInventory', - request_serializer=lfpinventory.InsertLfpInventoryRequest.serialize, - response_deserializer=lfpinventory.LfpInventory.deserialize, - ) - return self._stubs['insert_lfp_inventory'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.insert_lfp_inventory: self._wrap_method( - self.insert_lfp_inventory, - default_timeout=None, - client_info=client_info, - ), - } - - def _wrap_method(self, func, *args, **kwargs): - if self._wrap_with_kind: # pragma: NO COVER - kwargs["kind"] = self.kind - return gapic_v1.method_async.wrap_method(func, *args, **kwargs) - - def close(self): - return self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc_asyncio" - - -__all__ = ( - 'LfpInventoryServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/rest.py deleted file mode 100644 index 88744ba1d88c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/rest.py +++ /dev/null @@ -1,331 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -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_lfp_v1beta.types import lfpinventory - - -from .rest_base import _BaseLfpInventoryServiceRestTransport -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}", -) - - -class LfpInventoryServiceRestInterceptor: - """Interceptor for LfpInventoryService. - - 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 LfpInventoryServiceRestTransport. - - .. code-block:: python - class MyCustomLfpInventoryServiceInterceptor(LfpInventoryServiceRestInterceptor): - def pre_insert_lfp_inventory(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_insert_lfp_inventory(self, response): - logging.log(f"Received response: {response}") - return response - - transport = LfpInventoryServiceRestTransport(interceptor=MyCustomLfpInventoryServiceInterceptor()) - client = LfpInventoryServiceClient(transport=transport) - - - """ - def pre_insert_lfp_inventory(self, request: lfpinventory.InsertLfpInventoryRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[lfpinventory.InsertLfpInventoryRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for insert_lfp_inventory - - Override in a subclass to manipulate the request or metadata - before they are sent to the LfpInventoryService server. - """ - return request, metadata - - def post_insert_lfp_inventory(self, response: lfpinventory.LfpInventory) -> lfpinventory.LfpInventory: - """Post-rpc interceptor for insert_lfp_inventory - - Override in a subclass to manipulate the response - after it is returned by the LfpInventoryService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class LfpInventoryServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: LfpInventoryServiceRestInterceptor - - -class LfpInventoryServiceRestTransport(_BaseLfpInventoryServiceRestTransport): - """REST backend synchronous transport for LfpInventoryService. - - Service for a `LFP - partner `__ to - submit local inventories for a merchant. - - This 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[LfpInventoryServiceRestInterceptor] = 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 LfpInventoryServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _InsertLfpInventory(_BaseLfpInventoryServiceRestTransport._BaseInsertLfpInventory, LfpInventoryServiceRestStub): - def __hash__(self): - return hash("LfpInventoryServiceRestTransport.InsertLfpInventory") - - @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: lfpinventory.InsertLfpInventoryRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> lfpinventory.LfpInventory: - r"""Call the insert lfp inventory method over HTTP. - - Args: - request (~.lfpinventory.InsertLfpInventoryRequest): - The request object. Request message for the ``InsertLfpInventory`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.lfpinventory.LfpInventory: - Local Inventory for the merchant. - """ - - http_options = _BaseLfpInventoryServiceRestTransport._BaseInsertLfpInventory._get_http_options() - - request, metadata = self._interceptor.pre_insert_lfp_inventory(request, metadata) - transcoded_request = _BaseLfpInventoryServiceRestTransport._BaseInsertLfpInventory._get_transcoded_request(http_options, request) - - body = _BaseLfpInventoryServiceRestTransport._BaseInsertLfpInventory._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseLfpInventoryServiceRestTransport._BaseInsertLfpInventory._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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.lfp_v1beta.LfpInventoryServiceClient.InsertLfpInventory", - extra = { - "serviceName": "google.shopping.merchant.lfp.v1beta.LfpInventoryService", - "rpcName": "InsertLfpInventory", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = LfpInventoryServiceRestTransport._InsertLfpInventory._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 = lfpinventory.LfpInventory() - pb_resp = lfpinventory.LfpInventory.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_insert_lfp_inventory(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = lfpinventory.LfpInventory.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.lfp_v1beta.LfpInventoryServiceClient.insert_lfp_inventory", - extra = { - "serviceName": "google.shopping.merchant.lfp.v1beta.LfpInventoryService", - "rpcName": "InsertLfpInventory", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def insert_lfp_inventory(self) -> Callable[ - [lfpinventory.InsertLfpInventoryRequest], - lfpinventory.LfpInventory]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._InsertLfpInventory(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'LfpInventoryServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/rest_base.py deleted file mode 100644 index 5d4ac2c2f2b4..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/rest_base.py +++ /dev/null @@ -1,138 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 LfpInventoryServiceTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.shopping.merchant_lfp_v1beta.types import lfpinventory - - -class _BaseLfpInventoryServiceRestTransport(LfpInventoryServiceTransport): - """Base REST backend transport for LfpInventoryService. - - 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 _BaseInsertLfpInventory: - 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': '/lfp/v1beta/{parent=accounts/*}/lfpInventories:insert', - 'body': 'lfp_inventory', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = lfpinventory.InsertLfpInventoryRequest.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(_BaseLfpInventoryServiceRestTransport._BaseInsertLfpInventory._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseLfpInventoryServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/__init__.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/__init__.py deleted file mode 100644 index 480f390ef2d5..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 LfpSaleServiceClient -from .async_client import LfpSaleServiceAsyncClient - -__all__ = ( - 'LfpSaleServiceClient', - 'LfpSaleServiceAsyncClient', -) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/async_client.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/async_client.py deleted file mode 100644 index f3636dc14aa0..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/async_client.py +++ /dev/null @@ -1,357 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_lfp_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 - - -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 timestamp_pb2 # type: ignore -from google.shopping.merchant_lfp_v1beta.types import lfpsale -from google.shopping.type.types import types -from .transports.base import LfpSaleServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import LfpSaleServiceGrpcAsyncIOTransport -from .client import LfpSaleServiceClient - -try: - from google.api_core import client_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 LfpSaleServiceAsyncClient: - """Service for a `LFP - partner `__ to - submit sales data for a merchant. - """ - - _client: LfpSaleServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = LfpSaleServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = LfpSaleServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = LfpSaleServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = LfpSaleServiceClient._DEFAULT_UNIVERSE - - lfp_sale_path = staticmethod(LfpSaleServiceClient.lfp_sale_path) - parse_lfp_sale_path = staticmethod(LfpSaleServiceClient.parse_lfp_sale_path) - common_billing_account_path = staticmethod(LfpSaleServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(LfpSaleServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(LfpSaleServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(LfpSaleServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(LfpSaleServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(LfpSaleServiceClient.parse_common_organization_path) - common_project_path = staticmethod(LfpSaleServiceClient.common_project_path) - parse_common_project_path = staticmethod(LfpSaleServiceClient.parse_common_project_path) - common_location_path = staticmethod(LfpSaleServiceClient.common_location_path) - parse_common_location_path = staticmethod(LfpSaleServiceClient.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: - LfpSaleServiceAsyncClient: The constructed client. - """ - return LfpSaleServiceClient.from_service_account_info.__func__(LfpSaleServiceAsyncClient, 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: - LfpSaleServiceAsyncClient: The constructed client. - """ - return LfpSaleServiceClient.from_service_account_file.__func__(LfpSaleServiceAsyncClient, 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 LfpSaleServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> LfpSaleServiceTransport: - """Returns the transport used by the client instance. - - Returns: - LfpSaleServiceTransport: 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 = LfpSaleServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, LfpSaleServiceTransport, Callable[..., LfpSaleServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the lfp sale 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,LfpSaleServiceTransport,Callable[..., LfpSaleServiceTransport]]]): - 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 LfpSaleServiceTransport 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 = LfpSaleServiceClient( - 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.lfp_v1beta.LfpSaleServiceAsyncClient`.", - extra = { - "serviceName": "google.shopping.merchant.lfp.v1beta.LfpSaleService", - "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.lfp.v1beta.LfpSaleService", - "credentialsType": None, - } - ) - - async def insert_lfp_sale(self, - request: Optional[Union[lfpsale.InsertLfpSaleRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> lfpsale.LfpSale: - r"""Inserts a ``LfpSale`` 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_lfp_v1beta - - async def sample_insert_lfp_sale(): - # Create a client - client = merchant_lfp_v1beta.LfpSaleServiceAsyncClient() - - # Initialize request argument(s) - lfp_sale = merchant_lfp_v1beta.LfpSale() - lfp_sale.target_account = 1491 - lfp_sale.store_code = "store_code_value" - lfp_sale.offer_id = "offer_id_value" - lfp_sale.region_code = "region_code_value" - lfp_sale.content_language = "content_language_value" - lfp_sale.gtin = "gtin_value" - lfp_sale.quantity = 895 - - request = merchant_lfp_v1beta.InsertLfpSaleRequest( - parent="parent_value", - lfp_sale=lfp_sale, - ) - - # Make the request - response = await client.insert_lfp_sale(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_lfp_v1beta.types.InsertLfpSaleRequest, dict]]): - The request object. Request message for the InsertLfpSale - 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_lfp_v1beta.types.LfpSale: - A sale for the merchant. - """ - # 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, lfpsale.InsertLfpSaleRequest): - request = lfpsale.InsertLfpSaleRequest(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_lfp_sale] - - # Certain 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) -> "LfpSaleServiceAsyncClient": - 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__) - - -__all__ = ( - "LfpSaleServiceAsyncClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/client.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/client.py deleted file mode 100644 index 1865b4bb14b0..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/client.py +++ /dev/null @@ -1,693 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -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_lfp_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 - -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 timestamp_pb2 # type: ignore -from google.shopping.merchant_lfp_v1beta.types import lfpsale -from google.shopping.type.types import types -from .transports.base import LfpSaleServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import LfpSaleServiceGrpcTransport -from .transports.grpc_asyncio import LfpSaleServiceGrpcAsyncIOTransport -from .transports.rest import LfpSaleServiceRestTransport - - -class LfpSaleServiceClientMeta(type): - """Metaclass for the LfpSaleService 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[LfpSaleServiceTransport]] - _transport_registry["grpc"] = LfpSaleServiceGrpcTransport - _transport_registry["grpc_asyncio"] = LfpSaleServiceGrpcAsyncIOTransport - _transport_registry["rest"] = LfpSaleServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[LfpSaleServiceTransport]: - """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 LfpSaleServiceClient(metaclass=LfpSaleServiceClientMeta): - """Service for a `LFP - partner `__ to - submit sales data for a merchant. - """ - - @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: - LfpSaleServiceClient: 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: - LfpSaleServiceClient: 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) -> LfpSaleServiceTransport: - """Returns the transport used by the client instance. - - Returns: - LfpSaleServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def lfp_sale_path(account: str,sale: str,) -> str: - """Returns a fully-qualified lfp_sale string.""" - return "accounts/{account}/lfpSales/{sale}".format(account=account, sale=sale, ) - - @staticmethod - def parse_lfp_sale_path(path: str) -> Dict[str,str]: - """Parses a lfp_sale path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/lfpSales/(?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 = LfpSaleServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = LfpSaleServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = LfpSaleServiceClient._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 = LfpSaleServiceClient._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 - - @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, LfpSaleServiceTransport, Callable[..., LfpSaleServiceTransport]]] = 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 sale 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,LfpSaleServiceTransport,Callable[..., LfpSaleServiceTransport]]]): - 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 LfpSaleServiceTransport 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 = LfpSaleServiceClient._read_environment_variables() - self._client_cert_source = LfpSaleServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = LfpSaleServiceClient._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, LfpSaleServiceTransport) - if transport_provided: - # transport is a LfpSaleServiceTransport 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(LfpSaleServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - LfpSaleServiceClient._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[LfpSaleServiceTransport], Callable[..., LfpSaleServiceTransport]] = ( - LfpSaleServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., LfpSaleServiceTransport], 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.lfp_v1beta.LfpSaleServiceClient`.", - extra = { - "serviceName": "google.shopping.merchant.lfp.v1beta.LfpSaleService", - "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.lfp.v1beta.LfpSaleService", - "credentialsType": None, - } - ) - - def insert_lfp_sale(self, - request: Optional[Union[lfpsale.InsertLfpSaleRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> lfpsale.LfpSale: - r"""Inserts a ``LfpSale`` 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_lfp_v1beta - - def sample_insert_lfp_sale(): - # Create a client - client = merchant_lfp_v1beta.LfpSaleServiceClient() - - # Initialize request argument(s) - lfp_sale = merchant_lfp_v1beta.LfpSale() - lfp_sale.target_account = 1491 - lfp_sale.store_code = "store_code_value" - lfp_sale.offer_id = "offer_id_value" - lfp_sale.region_code = "region_code_value" - lfp_sale.content_language = "content_language_value" - lfp_sale.gtin = "gtin_value" - lfp_sale.quantity = 895 - - request = merchant_lfp_v1beta.InsertLfpSaleRequest( - parent="parent_value", - lfp_sale=lfp_sale, - ) - - # Make the request - response = client.insert_lfp_sale(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_lfp_v1beta.types.InsertLfpSaleRequest, dict]): - The request object. Request message for the InsertLfpSale - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.shopping.merchant_lfp_v1beta.types.LfpSale: - A sale for the merchant. - """ - # 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, lfpsale.InsertLfpSaleRequest): - request = lfpsale.InsertLfpSaleRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.insert_lfp_sale] - - # Certain 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) -> "LfpSaleServiceClient": - 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__) - - -__all__ = ( - "LfpSaleServiceClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/README.rst deleted file mode 100644 index 5a2eb4c5a035..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`LfpSaleServiceTransport` is the ABC for all transports. -- public child `LfpSaleServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `LfpSaleServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseLfpSaleServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `LfpSaleServiceRestTransport` 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-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/__init__.py deleted file mode 100644 index 1d8c06407377..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 LfpSaleServiceTransport -from .grpc import LfpSaleServiceGrpcTransport -from .grpc_asyncio import LfpSaleServiceGrpcAsyncIOTransport -from .rest import LfpSaleServiceRestTransport -from .rest import LfpSaleServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[LfpSaleServiceTransport]] -_transport_registry['grpc'] = LfpSaleServiceGrpcTransport -_transport_registry['grpc_asyncio'] = LfpSaleServiceGrpcAsyncIOTransport -_transport_registry['rest'] = LfpSaleServiceRestTransport - -__all__ = ( - 'LfpSaleServiceTransport', - 'LfpSaleServiceGrpcTransport', - 'LfpSaleServiceGrpcAsyncIOTransport', - 'LfpSaleServiceRestTransport', - 'LfpSaleServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/base.py deleted file mode 100644 index 19ed7312d61e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/base.py +++ /dev/null @@ -1,154 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_lfp_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 - -from google.shopping.merchant_lfp_v1beta.types import lfpsale - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class LfpSaleServiceTransport(abc.ABC): - """Abstract transport class for LfpSaleService.""" - - 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.insert_lfp_sale: gapic_v1.method.wrap_method( - self.insert_lfp_sale, - 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 insert_lfp_sale(self) -> Callable[ - [lfpsale.InsertLfpSaleRequest], - Union[ - lfpsale.LfpSale, - Awaitable[lfpsale.LfpSale] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'LfpSaleServiceTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/grpc.py deleted file mode 100644 index db72f06dd688..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/grpc.py +++ /dev/null @@ -1,349 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_lfp_v1beta.types import lfpsale -from .base import LfpSaleServiceTransport, 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.lfp.v1beta.LfpSaleService", - "rpcName": 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.lfp.v1beta.LfpSaleService", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class LfpSaleServiceGrpcTransport(LfpSaleServiceTransport): - """gRPC backend transport for LfpSaleService. - - Service for a `LFP - partner `__ to - submit sales data for a merchant. - - This 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 insert_lfp_sale(self) -> Callable[ - [lfpsale.InsertLfpSaleRequest], - lfpsale.LfpSale]: - r"""Return a callable for the insert lfp sale method over gRPC. - - Inserts a ``LfpSale`` for the given merchant. - - Returns: - Callable[[~.InsertLfpSaleRequest], - ~.LfpSale]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_lfp_sale' not in self._stubs: - self._stubs['insert_lfp_sale'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.lfp.v1beta.LfpSaleService/InsertLfpSale', - request_serializer=lfpsale.InsertLfpSaleRequest.serialize, - response_deserializer=lfpsale.LfpSale.deserialize, - ) - return self._stubs['insert_lfp_sale'] - - def close(self): - self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'LfpSaleServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/grpc_asyncio.py deleted file mode 100644 index 90493a146911..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,369 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_lfp_v1beta.types import lfpsale -from .base import LfpSaleServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import LfpSaleServiceGrpcTransport - -try: - from google.api_core import client_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.lfp.v1beta.LfpSaleService", - "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.lfp.v1beta.LfpSaleService", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class LfpSaleServiceGrpcAsyncIOTransport(LfpSaleServiceTransport): - """gRPC AsyncIO backend transport for LfpSaleService. - - Service for a `LFP - partner `__ to - submit sales data for a merchant. - - This 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 insert_lfp_sale(self) -> Callable[ - [lfpsale.InsertLfpSaleRequest], - Awaitable[lfpsale.LfpSale]]: - r"""Return a callable for the insert lfp sale method over gRPC. - - Inserts a ``LfpSale`` for the given merchant. - - Returns: - Callable[[~.InsertLfpSaleRequest], - Awaitable[~.LfpSale]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_lfp_sale' not in self._stubs: - self._stubs['insert_lfp_sale'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.lfp.v1beta.LfpSaleService/InsertLfpSale', - request_serializer=lfpsale.InsertLfpSaleRequest.serialize, - response_deserializer=lfpsale.LfpSale.deserialize, - ) - return self._stubs['insert_lfp_sale'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.insert_lfp_sale: self._wrap_method( - self.insert_lfp_sale, - 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__ = ( - 'LfpSaleServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/rest.py deleted file mode 100644 index 68c8a9d5dc68..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/rest.py +++ /dev/null @@ -1,332 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -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_lfp_v1beta.types import lfpsale - - -from .rest_base import _BaseLfpSaleServiceRestTransport -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}", -) - - -class LfpSaleServiceRestInterceptor: - """Interceptor for LfpSaleService. - - 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 LfpSaleServiceRestTransport. - - .. code-block:: python - class MyCustomLfpSaleServiceInterceptor(LfpSaleServiceRestInterceptor): - def pre_insert_lfp_sale(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_insert_lfp_sale(self, response): - logging.log(f"Received response: {response}") - return response - - transport = LfpSaleServiceRestTransport(interceptor=MyCustomLfpSaleServiceInterceptor()) - client = LfpSaleServiceClient(transport=transport) - - - """ - def pre_insert_lfp_sale(self, request: lfpsale.InsertLfpSaleRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[lfpsale.InsertLfpSaleRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for insert_lfp_sale - - Override in a subclass to manipulate the request or metadata - before they are sent to the LfpSaleService server. - """ - return request, metadata - - def post_insert_lfp_sale(self, response: lfpsale.LfpSale) -> lfpsale.LfpSale: - """Post-rpc interceptor for insert_lfp_sale - - Override in a subclass to manipulate the response - after it is returned by the LfpSaleService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class LfpSaleServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: LfpSaleServiceRestInterceptor - - -class LfpSaleServiceRestTransport(_BaseLfpSaleServiceRestTransport): - """REST backend synchronous transport for LfpSaleService. - - Service for a `LFP - partner `__ to - submit sales data for a merchant. - - This 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[LfpSaleServiceRestInterceptor] = 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 LfpSaleServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _InsertLfpSale(_BaseLfpSaleServiceRestTransport._BaseInsertLfpSale, LfpSaleServiceRestStub): - def __hash__(self): - return hash("LfpSaleServiceRestTransport.InsertLfpSale") - - @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: lfpsale.InsertLfpSaleRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> lfpsale.LfpSale: - r"""Call the insert lfp sale method over HTTP. - - Args: - request (~.lfpsale.InsertLfpSaleRequest): - The request object. Request message for the InsertLfpSale - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.lfpsale.LfpSale: - A sale for the merchant. - """ - - http_options = _BaseLfpSaleServiceRestTransport._BaseInsertLfpSale._get_http_options() - - request, metadata = self._interceptor.pre_insert_lfp_sale(request, metadata) - transcoded_request = _BaseLfpSaleServiceRestTransport._BaseInsertLfpSale._get_transcoded_request(http_options, request) - - body = _BaseLfpSaleServiceRestTransport._BaseInsertLfpSale._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseLfpSaleServiceRestTransport._BaseInsertLfpSale._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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.lfp_v1beta.LfpSaleServiceClient.InsertLfpSale", - extra = { - "serviceName": "google.shopping.merchant.lfp.v1beta.LfpSaleService", - "rpcName": "InsertLfpSale", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = LfpSaleServiceRestTransport._InsertLfpSale._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 = lfpsale.LfpSale() - pb_resp = lfpsale.LfpSale.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_insert_lfp_sale(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = lfpsale.LfpSale.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.lfp_v1beta.LfpSaleServiceClient.insert_lfp_sale", - extra = { - "serviceName": "google.shopping.merchant.lfp.v1beta.LfpSaleService", - "rpcName": "InsertLfpSale", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def insert_lfp_sale(self) -> Callable[ - [lfpsale.InsertLfpSaleRequest], - lfpsale.LfpSale]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._InsertLfpSale(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'LfpSaleServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/rest_base.py deleted file mode 100644 index f5f597e2210e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/rest_base.py +++ /dev/null @@ -1,138 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 LfpSaleServiceTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.shopping.merchant_lfp_v1beta.types import lfpsale - - -class _BaseLfpSaleServiceRestTransport(LfpSaleServiceTransport): - """Base REST backend transport for LfpSaleService. - - 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 _BaseInsertLfpSale: - 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': '/lfp/v1beta/{parent=accounts/*}/lfpSales:insert', - 'body': 'lfp_sale', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = lfpsale.InsertLfpSaleRequest.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(_BaseLfpSaleServiceRestTransport._BaseInsertLfpSale._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseLfpSaleServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/__init__.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/__init__.py deleted file mode 100644 index 097d5476e3d9..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 LfpStoreServiceClient -from .async_client import LfpStoreServiceAsyncClient - -__all__ = ( - 'LfpStoreServiceClient', - 'LfpStoreServiceAsyncClient', -) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/async_client.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/async_client.py deleted file mode 100644 index 9b5b71901cf3..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/async_client.py +++ /dev/null @@ -1,714 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_lfp_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 - - -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_lfp_v1beta.services.lfp_store_service import pagers -from google.shopping.merchant_lfp_v1beta.types import lfpstore -from .transports.base import LfpStoreServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import LfpStoreServiceGrpcAsyncIOTransport -from .client import LfpStoreServiceClient - -try: - from google.api_core import client_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 LfpStoreServiceAsyncClient: - """Service for a `LFP - partner `__ to - submit local stores for a merchant. - """ - - _client: LfpStoreServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = LfpStoreServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = LfpStoreServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = LfpStoreServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = LfpStoreServiceClient._DEFAULT_UNIVERSE - - lfp_store_path = staticmethod(LfpStoreServiceClient.lfp_store_path) - parse_lfp_store_path = staticmethod(LfpStoreServiceClient.parse_lfp_store_path) - common_billing_account_path = staticmethod(LfpStoreServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(LfpStoreServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(LfpStoreServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(LfpStoreServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(LfpStoreServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(LfpStoreServiceClient.parse_common_organization_path) - common_project_path = staticmethod(LfpStoreServiceClient.common_project_path) - parse_common_project_path = staticmethod(LfpStoreServiceClient.parse_common_project_path) - common_location_path = staticmethod(LfpStoreServiceClient.common_location_path) - parse_common_location_path = staticmethod(LfpStoreServiceClient.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: - LfpStoreServiceAsyncClient: The constructed client. - """ - return LfpStoreServiceClient.from_service_account_info.__func__(LfpStoreServiceAsyncClient, 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: - LfpStoreServiceAsyncClient: The constructed client. - """ - return LfpStoreServiceClient.from_service_account_file.__func__(LfpStoreServiceAsyncClient, 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 LfpStoreServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> LfpStoreServiceTransport: - """Returns the transport used by the client instance. - - Returns: - LfpStoreServiceTransport: 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 = LfpStoreServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, LfpStoreServiceTransport, Callable[..., LfpStoreServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the lfp store 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,LfpStoreServiceTransport,Callable[..., LfpStoreServiceTransport]]]): - 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 LfpStoreServiceTransport 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 = LfpStoreServiceClient( - 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.lfp_v1beta.LfpStoreServiceAsyncClient`.", - extra = { - "serviceName": "google.shopping.merchant.lfp.v1beta.LfpStoreService", - "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.lfp.v1beta.LfpStoreService", - "credentialsType": None, - } - ) - - async def get_lfp_store(self, - request: Optional[Union[lfpstore.GetLfpStoreRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> lfpstore.LfpStore: - r"""Retrieves information about a store. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_lfp_v1beta - - async def sample_get_lfp_store(): - # Create a client - client = merchant_lfp_v1beta.LfpStoreServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_lfp_v1beta.GetLfpStoreRequest( - name="name_value", - ) - - # Make the request - response = await client.get_lfp_store(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_lfp_v1beta.types.GetLfpStoreRequest, dict]]): - The request object. Request message for the ``GetLfpStore`` method. - name (:class:`str`): - Required. The name of the store to retrieve. Format: - ``accounts/{account}/lfpStores/{target_merchant}~{store_code}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.shopping.merchant_lfp_v1beta.types.LfpStore: - A store for the merchant. This will - be used to match to a store under the - Google Business Profile of the target - merchant. If a matching store can't be - found, the inventories or sales - submitted with the store code will not - be used. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, lfpstore.GetLfpStoreRequest): - request = lfpstore.GetLfpStoreRequest(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_lfp_store] - - # Certain 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_lfp_store(self, - request: Optional[Union[lfpstore.InsertLfpStoreRequest, dict]] = None, - *, - parent: Optional[str] = None, - lfp_store: Optional[lfpstore.LfpStore] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> lfpstore.LfpStore: - r"""Inserts a store for the target merchant. If the store - with the same store code already exists, it will be - replaced. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_lfp_v1beta - - async def sample_insert_lfp_store(): - # Create a client - client = merchant_lfp_v1beta.LfpStoreServiceAsyncClient() - - # Initialize request argument(s) - lfp_store = merchant_lfp_v1beta.LfpStore() - lfp_store.target_account = 1491 - lfp_store.store_code = "store_code_value" - lfp_store.store_address = "store_address_value" - - request = merchant_lfp_v1beta.InsertLfpStoreRequest( - parent="parent_value", - lfp_store=lfp_store, - ) - - # Make the request - response = await client.insert_lfp_store(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_lfp_v1beta.types.InsertLfpStoreRequest, dict]]): - The request object. Request message for the - InsertLfpStore method. - parent (:class:`str`): - Required. The LFP provider account Format: - ``accounts/{account}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - lfp_store (:class:`google.shopping.merchant_lfp_v1beta.types.LfpStore`): - Required. The store to insert. - This corresponds to the ``lfp_store`` 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_lfp_v1beta.types.LfpStore: - A store for the merchant. This will - be used to match to a store under the - Google Business Profile of the target - merchant. If a matching store can't be - found, the inventories or sales - submitted with the store code will not - be used. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, lfp_store]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, lfpstore.InsertLfpStoreRequest): - request = lfpstore.InsertLfpStoreRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if lfp_store is not None: - request.lfp_store = lfp_store - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.insert_lfp_store] - - # Certain 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_lfp_store(self, - request: Optional[Union[lfpstore.DeleteLfpStoreRequest, dict]] = None, - *, - name: Optional[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 store for a target 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_lfp_v1beta - - async def sample_delete_lfp_store(): - # Create a client - client = merchant_lfp_v1beta.LfpStoreServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_lfp_v1beta.DeleteLfpStoreRequest( - name="name_value", - ) - - # Make the request - await client.delete_lfp_store(request=request) - - Args: - request (Optional[Union[google.shopping.merchant_lfp_v1beta.types.DeleteLfpStoreRequest, dict]]): - The request object. Request message for the - DeleteLfpStore method. - name (:class:`str`): - Required. The name of the store to delete for the target - merchant account. Format: - ``accounts/{account}/lfpStores/{target_merchant}~{store_code}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, lfpstore.DeleteLfpStoreRequest): - request = lfpstore.DeleteLfpStoreRequest(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_lfp_store] - - # Certain 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_lfp_stores(self, - request: Optional[Union[lfpstore.ListLfpStoresRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListLfpStoresAsyncPager: - r"""Lists the stores of the target merchant, specified by the filter - in ``ListLfpStoresRequest``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_lfp_v1beta - - async def sample_list_lfp_stores(): - # Create a client - client = merchant_lfp_v1beta.LfpStoreServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_lfp_v1beta.ListLfpStoresRequest( - parent="parent_value", - target_account=1491, - ) - - # Make the request - page_result = client.list_lfp_stores(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_lfp_v1beta.types.ListLfpStoresRequest, dict]]): - The request object. Request message for the ListLfpStores - method. - parent (:class:`str`): - Required. The LFP partner. 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_lfp_v1beta.services.lfp_store_service.pagers.ListLfpStoresAsyncPager: - Response message for the - ListLfpStores 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, lfpstore.ListLfpStoresRequest): - request = lfpstore.ListLfpStoresRequest(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_lfp_stores] - - # Certain 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.ListLfpStoresAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self) -> "LfpStoreServiceAsyncClient": - 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__) - - -__all__ = ( - "LfpStoreServiceAsyncClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/client.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/client.py deleted file mode 100644 index c436d694f956..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/client.py +++ /dev/null @@ -1,1046 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -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_lfp_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 - -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_lfp_v1beta.services.lfp_store_service import pagers -from google.shopping.merchant_lfp_v1beta.types import lfpstore -from .transports.base import LfpStoreServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import LfpStoreServiceGrpcTransport -from .transports.grpc_asyncio import LfpStoreServiceGrpcAsyncIOTransport -from .transports.rest import LfpStoreServiceRestTransport - - -class LfpStoreServiceClientMeta(type): - """Metaclass for the LfpStoreService 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[LfpStoreServiceTransport]] - _transport_registry["grpc"] = LfpStoreServiceGrpcTransport - _transport_registry["grpc_asyncio"] = LfpStoreServiceGrpcAsyncIOTransport - _transport_registry["rest"] = LfpStoreServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[LfpStoreServiceTransport]: - """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 LfpStoreServiceClient(metaclass=LfpStoreServiceClientMeta): - """Service for a `LFP - partner `__ to - submit local stores for a merchant. - """ - - @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: - LfpStoreServiceClient: 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: - LfpStoreServiceClient: 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) -> LfpStoreServiceTransport: - """Returns the transport used by the client instance. - - Returns: - LfpStoreServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def lfp_store_path(account: str,target_merchant: str,store_code: str,) -> str: - """Returns a fully-qualified lfp_store string.""" - return "accounts/{account}/lfpStores/{target_merchant}~{store_code}".format(account=account, target_merchant=target_merchant, store_code=store_code, ) - - @staticmethod - def parse_lfp_store_path(path: str) -> Dict[str,str]: - """Parses a lfp_store path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/lfpStores/(?P.+?)~(?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 = LfpStoreServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = LfpStoreServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = LfpStoreServiceClient._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 = LfpStoreServiceClient._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 - - @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, LfpStoreServiceTransport, Callable[..., LfpStoreServiceTransport]]] = 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 store 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,LfpStoreServiceTransport,Callable[..., LfpStoreServiceTransport]]]): - 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 LfpStoreServiceTransport 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 = LfpStoreServiceClient._read_environment_variables() - self._client_cert_source = LfpStoreServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = LfpStoreServiceClient._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, LfpStoreServiceTransport) - if transport_provided: - # transport is a LfpStoreServiceTransport 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(LfpStoreServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - LfpStoreServiceClient._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[LfpStoreServiceTransport], Callable[..., LfpStoreServiceTransport]] = ( - LfpStoreServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., LfpStoreServiceTransport], 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.lfp_v1beta.LfpStoreServiceClient`.", - extra = { - "serviceName": "google.shopping.merchant.lfp.v1beta.LfpStoreService", - "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.lfp.v1beta.LfpStoreService", - "credentialsType": None, - } - ) - - def get_lfp_store(self, - request: Optional[Union[lfpstore.GetLfpStoreRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> lfpstore.LfpStore: - r"""Retrieves information about a store. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_lfp_v1beta - - def sample_get_lfp_store(): - # Create a client - client = merchant_lfp_v1beta.LfpStoreServiceClient() - - # Initialize request argument(s) - request = merchant_lfp_v1beta.GetLfpStoreRequest( - name="name_value", - ) - - # Make the request - response = client.get_lfp_store(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_lfp_v1beta.types.GetLfpStoreRequest, dict]): - The request object. Request message for the ``GetLfpStore`` method. - name (str): - Required. The name of the store to retrieve. Format: - ``accounts/{account}/lfpStores/{target_merchant}~{store_code}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.shopping.merchant_lfp_v1beta.types.LfpStore: - A store for the merchant. This will - be used to match to a store under the - Google Business Profile of the target - merchant. If a matching store can't be - found, the inventories or sales - submitted with the store code will not - be used. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, lfpstore.GetLfpStoreRequest): - request = lfpstore.GetLfpStoreRequest(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_lfp_store] - - # Certain 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_lfp_store(self, - request: Optional[Union[lfpstore.InsertLfpStoreRequest, dict]] = None, - *, - parent: Optional[str] = None, - lfp_store: Optional[lfpstore.LfpStore] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> lfpstore.LfpStore: - r"""Inserts a store for the target merchant. If the store - with the same store code already exists, it will be - replaced. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_lfp_v1beta - - def sample_insert_lfp_store(): - # Create a client - client = merchant_lfp_v1beta.LfpStoreServiceClient() - - # Initialize request argument(s) - lfp_store = merchant_lfp_v1beta.LfpStore() - lfp_store.target_account = 1491 - lfp_store.store_code = "store_code_value" - lfp_store.store_address = "store_address_value" - - request = merchant_lfp_v1beta.InsertLfpStoreRequest( - parent="parent_value", - lfp_store=lfp_store, - ) - - # Make the request - response = client.insert_lfp_store(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_lfp_v1beta.types.InsertLfpStoreRequest, dict]): - The request object. Request message for the - InsertLfpStore method. - parent (str): - Required. The LFP provider account Format: - ``accounts/{account}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - lfp_store (google.shopping.merchant_lfp_v1beta.types.LfpStore): - Required. The store to insert. - This corresponds to the ``lfp_store`` 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_lfp_v1beta.types.LfpStore: - A store for the merchant. This will - be used to match to a store under the - Google Business Profile of the target - merchant. If a matching store can't be - found, the inventories or sales - submitted with the store code will not - be used. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, lfp_store]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, lfpstore.InsertLfpStoreRequest): - request = lfpstore.InsertLfpStoreRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if lfp_store is not None: - request.lfp_store = lfp_store - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.insert_lfp_store] - - # Certain 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_lfp_store(self, - request: Optional[Union[lfpstore.DeleteLfpStoreRequest, dict]] = None, - *, - name: Optional[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 store for a target 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_lfp_v1beta - - def sample_delete_lfp_store(): - # Create a client - client = merchant_lfp_v1beta.LfpStoreServiceClient() - - # Initialize request argument(s) - request = merchant_lfp_v1beta.DeleteLfpStoreRequest( - name="name_value", - ) - - # Make the request - client.delete_lfp_store(request=request) - - Args: - request (Union[google.shopping.merchant_lfp_v1beta.types.DeleteLfpStoreRequest, dict]): - The request object. Request message for the - DeleteLfpStore method. - name (str): - Required. The name of the store to delete for the target - merchant account. Format: - ``accounts/{account}/lfpStores/{target_merchant}~{store_code}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, lfpstore.DeleteLfpStoreRequest): - request = lfpstore.DeleteLfpStoreRequest(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_lfp_store] - - # Certain 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_lfp_stores(self, - request: Optional[Union[lfpstore.ListLfpStoresRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListLfpStoresPager: - r"""Lists the stores of the target merchant, specified by the filter - in ``ListLfpStoresRequest``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_lfp_v1beta - - def sample_list_lfp_stores(): - # Create a client - client = merchant_lfp_v1beta.LfpStoreServiceClient() - - # Initialize request argument(s) - request = merchant_lfp_v1beta.ListLfpStoresRequest( - parent="parent_value", - target_account=1491, - ) - - # Make the request - page_result = client.list_lfp_stores(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.shopping.merchant_lfp_v1beta.types.ListLfpStoresRequest, dict]): - The request object. Request message for the ListLfpStores - method. - parent (str): - Required. The LFP partner. 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_lfp_v1beta.services.lfp_store_service.pagers.ListLfpStoresPager: - Response message for the - ListLfpStores 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, lfpstore.ListLfpStoresRequest): - request = lfpstore.ListLfpStoresRequest(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_lfp_stores] - - # Certain 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.ListLfpStoresPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "LfpStoreServiceClient": - 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__) - - -__all__ = ( - "LfpStoreServiceClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/pagers.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/pagers.py deleted file mode 100644 index a7745d10afde..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/pagers.py +++ /dev/null @@ -1,166 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_lfp_v1beta.types import lfpstore - - -class ListLfpStoresPager: - """A pager for iterating through ``list_lfp_stores`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_lfp_v1beta.types.ListLfpStoresResponse` object, and - provides an ``__iter__`` method to iterate through its - ``lfp_stores`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListLfpStores`` requests and continue to iterate - through the ``lfp_stores`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_lfp_v1beta.types.ListLfpStoresResponse` - 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[..., lfpstore.ListLfpStoresResponse], - request: lfpstore.ListLfpStoresRequest, - response: lfpstore.ListLfpStoresResponse, - *, - 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_lfp_v1beta.types.ListLfpStoresRequest): - The initial request object. - response (google.shopping.merchant_lfp_v1beta.types.ListLfpStoresResponse): - 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 = lfpstore.ListLfpStoresRequest(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[lfpstore.ListLfpStoresResponse]: - 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[lfpstore.LfpStore]: - for page in self.pages: - yield from page.lfp_stores - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListLfpStoresAsyncPager: - """A pager for iterating through ``list_lfp_stores`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_lfp_v1beta.types.ListLfpStoresResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``lfp_stores`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListLfpStores`` requests and continue to iterate - through the ``lfp_stores`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_lfp_v1beta.types.ListLfpStoresResponse` - 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[lfpstore.ListLfpStoresResponse]], - request: lfpstore.ListLfpStoresRequest, - response: lfpstore.ListLfpStoresResponse, - *, - 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_lfp_v1beta.types.ListLfpStoresRequest): - The initial request object. - response (google.shopping.merchant_lfp_v1beta.types.ListLfpStoresResponse): - 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 = lfpstore.ListLfpStoresRequest(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[lfpstore.ListLfpStoresResponse]: - 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[lfpstore.LfpStore]: - async def async_generator(): - async for page in self.pages: - for response in page.lfp_stores: - 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-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/README.rst deleted file mode 100644 index ed35abffa51e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`LfpStoreServiceTransport` is the ABC for all transports. -- public child `LfpStoreServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `LfpStoreServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseLfpStoreServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `LfpStoreServiceRestTransport` 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-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/__init__.py deleted file mode 100644 index 7f93047869ee..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 LfpStoreServiceTransport -from .grpc import LfpStoreServiceGrpcTransport -from .grpc_asyncio import LfpStoreServiceGrpcAsyncIOTransport -from .rest import LfpStoreServiceRestTransport -from .rest import LfpStoreServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[LfpStoreServiceTransport]] -_transport_registry['grpc'] = LfpStoreServiceGrpcTransport -_transport_registry['grpc_asyncio'] = LfpStoreServiceGrpcAsyncIOTransport -_transport_registry['rest'] = LfpStoreServiceRestTransport - -__all__ = ( - 'LfpStoreServiceTransport', - 'LfpStoreServiceGrpcTransport', - 'LfpStoreServiceGrpcAsyncIOTransport', - 'LfpStoreServiceRestTransport', - 'LfpStoreServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/base.py deleted file mode 100644 index 8aaec461f03f..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/base.py +++ /dev/null @@ -1,197 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_lfp_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 - -from google.protobuf import empty_pb2 # type: ignore -from google.shopping.merchant_lfp_v1beta.types import lfpstore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class LfpStoreServiceTransport(abc.ABC): - """Abstract transport class for LfpStoreService.""" - - 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_lfp_store: gapic_v1.method.wrap_method( - self.get_lfp_store, - default_timeout=None, - client_info=client_info, - ), - self.insert_lfp_store: gapic_v1.method.wrap_method( - self.insert_lfp_store, - default_timeout=None, - client_info=client_info, - ), - self.delete_lfp_store: gapic_v1.method.wrap_method( - self.delete_lfp_store, - default_timeout=None, - client_info=client_info, - ), - self.list_lfp_stores: gapic_v1.method.wrap_method( - self.list_lfp_stores, - 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_lfp_store(self) -> Callable[ - [lfpstore.GetLfpStoreRequest], - Union[ - lfpstore.LfpStore, - Awaitable[lfpstore.LfpStore] - ]]: - raise NotImplementedError() - - @property - def insert_lfp_store(self) -> Callable[ - [lfpstore.InsertLfpStoreRequest], - Union[ - lfpstore.LfpStore, - Awaitable[lfpstore.LfpStore] - ]]: - raise NotImplementedError() - - @property - def delete_lfp_store(self) -> Callable[ - [lfpstore.DeleteLfpStoreRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def list_lfp_stores(self) -> Callable[ - [lfpstore.ListLfpStoresRequest], - Union[ - lfpstore.ListLfpStoresResponse, - Awaitable[lfpstore.ListLfpStoresResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'LfpStoreServiceTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/grpc.py deleted file mode 100644 index e312dd60f248..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/grpc.py +++ /dev/null @@ -1,431 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_lfp_v1beta.types import lfpstore -from .base import LfpStoreServiceTransport, 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.lfp.v1beta.LfpStoreService", - "rpcName": 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.lfp.v1beta.LfpStoreService", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class LfpStoreServiceGrpcTransport(LfpStoreServiceTransport): - """gRPC backend transport for LfpStoreService. - - Service for a `LFP - partner `__ to - submit local stores for a merchant. - - This 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_lfp_store(self) -> Callable[ - [lfpstore.GetLfpStoreRequest], - lfpstore.LfpStore]: - r"""Return a callable for the get lfp store method over gRPC. - - Retrieves information about a store. - - Returns: - Callable[[~.GetLfpStoreRequest], - ~.LfpStore]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_lfp_store' not in self._stubs: - self._stubs['get_lfp_store'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.lfp.v1beta.LfpStoreService/GetLfpStore', - request_serializer=lfpstore.GetLfpStoreRequest.serialize, - response_deserializer=lfpstore.LfpStore.deserialize, - ) - return self._stubs['get_lfp_store'] - - @property - def insert_lfp_store(self) -> Callable[ - [lfpstore.InsertLfpStoreRequest], - lfpstore.LfpStore]: - r"""Return a callable for the insert lfp store method over gRPC. - - Inserts a store for the target merchant. If the store - with the same store code already exists, it will be - replaced. - - Returns: - Callable[[~.InsertLfpStoreRequest], - ~.LfpStore]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_lfp_store' not in self._stubs: - self._stubs['insert_lfp_store'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.lfp.v1beta.LfpStoreService/InsertLfpStore', - request_serializer=lfpstore.InsertLfpStoreRequest.serialize, - response_deserializer=lfpstore.LfpStore.deserialize, - ) - return self._stubs['insert_lfp_store'] - - @property - def delete_lfp_store(self) -> Callable[ - [lfpstore.DeleteLfpStoreRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete lfp store method over gRPC. - - Deletes a store for a target merchant. - - Returns: - Callable[[~.DeleteLfpStoreRequest], - ~.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_lfp_store' not in self._stubs: - self._stubs['delete_lfp_store'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.lfp.v1beta.LfpStoreService/DeleteLfpStore', - request_serializer=lfpstore.DeleteLfpStoreRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_lfp_store'] - - @property - def list_lfp_stores(self) -> Callable[ - [lfpstore.ListLfpStoresRequest], - lfpstore.ListLfpStoresResponse]: - r"""Return a callable for the list lfp stores method over gRPC. - - Lists the stores of the target merchant, specified by the filter - in ``ListLfpStoresRequest``. - - Returns: - Callable[[~.ListLfpStoresRequest], - ~.ListLfpStoresResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_lfp_stores' not in self._stubs: - self._stubs['list_lfp_stores'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.lfp.v1beta.LfpStoreService/ListLfpStores', - request_serializer=lfpstore.ListLfpStoresRequest.serialize, - response_deserializer=lfpstore.ListLfpStoresResponse.deserialize, - ) - return self._stubs['list_lfp_stores'] - - def close(self): - self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'LfpStoreServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/grpc_asyncio.py deleted file mode 100644 index 51b43f32f4a4..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,466 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_lfp_v1beta.types import lfpstore -from .base import LfpStoreServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import LfpStoreServiceGrpcTransport - -try: - from google.api_core import client_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.lfp.v1beta.LfpStoreService", - "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.lfp.v1beta.LfpStoreService", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class LfpStoreServiceGrpcAsyncIOTransport(LfpStoreServiceTransport): - """gRPC AsyncIO backend transport for LfpStoreService. - - Service for a `LFP - partner `__ to - submit local stores for a merchant. - - This 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_lfp_store(self) -> Callable[ - [lfpstore.GetLfpStoreRequest], - Awaitable[lfpstore.LfpStore]]: - r"""Return a callable for the get lfp store method over gRPC. - - Retrieves information about a store. - - Returns: - Callable[[~.GetLfpStoreRequest], - Awaitable[~.LfpStore]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_lfp_store' not in self._stubs: - self._stubs['get_lfp_store'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.lfp.v1beta.LfpStoreService/GetLfpStore', - request_serializer=lfpstore.GetLfpStoreRequest.serialize, - response_deserializer=lfpstore.LfpStore.deserialize, - ) - return self._stubs['get_lfp_store'] - - @property - def insert_lfp_store(self) -> Callable[ - [lfpstore.InsertLfpStoreRequest], - Awaitable[lfpstore.LfpStore]]: - r"""Return a callable for the insert lfp store method over gRPC. - - Inserts a store for the target merchant. If the store - with the same store code already exists, it will be - replaced. - - Returns: - Callable[[~.InsertLfpStoreRequest], - Awaitable[~.LfpStore]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_lfp_store' not in self._stubs: - self._stubs['insert_lfp_store'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.lfp.v1beta.LfpStoreService/InsertLfpStore', - request_serializer=lfpstore.InsertLfpStoreRequest.serialize, - response_deserializer=lfpstore.LfpStore.deserialize, - ) - return self._stubs['insert_lfp_store'] - - @property - def delete_lfp_store(self) -> Callable[ - [lfpstore.DeleteLfpStoreRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete lfp store method over gRPC. - - Deletes a store for a target merchant. - - Returns: - Callable[[~.DeleteLfpStoreRequest], - 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_lfp_store' not in self._stubs: - self._stubs['delete_lfp_store'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.lfp.v1beta.LfpStoreService/DeleteLfpStore', - request_serializer=lfpstore.DeleteLfpStoreRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_lfp_store'] - - @property - def list_lfp_stores(self) -> Callable[ - [lfpstore.ListLfpStoresRequest], - Awaitable[lfpstore.ListLfpStoresResponse]]: - r"""Return a callable for the list lfp stores method over gRPC. - - Lists the stores of the target merchant, specified by the filter - in ``ListLfpStoresRequest``. - - Returns: - Callable[[~.ListLfpStoresRequest], - Awaitable[~.ListLfpStoresResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_lfp_stores' not in self._stubs: - self._stubs['list_lfp_stores'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.lfp.v1beta.LfpStoreService/ListLfpStores', - request_serializer=lfpstore.ListLfpStoresRequest.serialize, - response_deserializer=lfpstore.ListLfpStoresResponse.deserialize, - ) - return self._stubs['list_lfp_stores'] - - 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_lfp_store: self._wrap_method( - self.get_lfp_store, - default_timeout=None, - client_info=client_info, - ), - self.insert_lfp_store: self._wrap_method( - self.insert_lfp_store, - default_timeout=None, - client_info=client_info, - ), - self.delete_lfp_store: self._wrap_method( - self.delete_lfp_store, - default_timeout=None, - client_info=client_info, - ), - self.list_lfp_stores: self._wrap_method( - self.list_lfp_stores, - 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__ = ( - 'LfpStoreServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/rest.py deleted file mode 100644 index 44939c1d91a7..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/rest.py +++ /dev/null @@ -1,756 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -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_lfp_v1beta.types import lfpstore - - -from .rest_base import _BaseLfpStoreServiceRestTransport -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}", -) - - -class LfpStoreServiceRestInterceptor: - """Interceptor for LfpStoreService. - - 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 LfpStoreServiceRestTransport. - - .. code-block:: python - class MyCustomLfpStoreServiceInterceptor(LfpStoreServiceRestInterceptor): - def pre_delete_lfp_store(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_lfp_store(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_lfp_store(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_insert_lfp_store(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_insert_lfp_store(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_lfp_stores(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_lfp_stores(self, response): - logging.log(f"Received response: {response}") - return response - - transport = LfpStoreServiceRestTransport(interceptor=MyCustomLfpStoreServiceInterceptor()) - client = LfpStoreServiceClient(transport=transport) - - - """ - def pre_delete_lfp_store(self, request: lfpstore.DeleteLfpStoreRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[lfpstore.DeleteLfpStoreRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_lfp_store - - Override in a subclass to manipulate the request or metadata - before they are sent to the LfpStoreService server. - """ - return request, metadata - - def pre_get_lfp_store(self, request: lfpstore.GetLfpStoreRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[lfpstore.GetLfpStoreRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_lfp_store - - Override in a subclass to manipulate the request or metadata - before they are sent to the LfpStoreService server. - """ - return request, metadata - - def post_get_lfp_store(self, response: lfpstore.LfpStore) -> lfpstore.LfpStore: - """Post-rpc interceptor for get_lfp_store - - Override in a subclass to manipulate the response - after it is returned by the LfpStoreService server but before - it is returned to user code. - """ - return response - - def pre_insert_lfp_store(self, request: lfpstore.InsertLfpStoreRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[lfpstore.InsertLfpStoreRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for insert_lfp_store - - Override in a subclass to manipulate the request or metadata - before they are sent to the LfpStoreService server. - """ - return request, metadata - - def post_insert_lfp_store(self, response: lfpstore.LfpStore) -> lfpstore.LfpStore: - """Post-rpc interceptor for insert_lfp_store - - Override in a subclass to manipulate the response - after it is returned by the LfpStoreService server but before - it is returned to user code. - """ - return response - - def pre_list_lfp_stores(self, request: lfpstore.ListLfpStoresRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[lfpstore.ListLfpStoresRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_lfp_stores - - Override in a subclass to manipulate the request or metadata - before they are sent to the LfpStoreService server. - """ - return request, metadata - - def post_list_lfp_stores(self, response: lfpstore.ListLfpStoresResponse) -> lfpstore.ListLfpStoresResponse: - """Post-rpc interceptor for list_lfp_stores - - Override in a subclass to manipulate the response - after it is returned by the LfpStoreService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class LfpStoreServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: LfpStoreServiceRestInterceptor - - -class LfpStoreServiceRestTransport(_BaseLfpStoreServiceRestTransport): - """REST backend synchronous transport for LfpStoreService. - - Service for a `LFP - partner `__ to - submit local stores for a merchant. - - This 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[LfpStoreServiceRestInterceptor] = 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 LfpStoreServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _DeleteLfpStore(_BaseLfpStoreServiceRestTransport._BaseDeleteLfpStore, LfpStoreServiceRestStub): - def __hash__(self): - return hash("LfpStoreServiceRestTransport.DeleteLfpStore") - - @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: lfpstore.DeleteLfpStoreRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ): - r"""Call the delete lfp store method over HTTP. - - Args: - request (~.lfpstore.DeleteLfpStoreRequest): - The request object. Request message for the - DeleteLfpStore method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, 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 = _BaseLfpStoreServiceRestTransport._BaseDeleteLfpStore._get_http_options() - - request, metadata = self._interceptor.pre_delete_lfp_store(request, metadata) - transcoded_request = _BaseLfpStoreServiceRestTransport._BaseDeleteLfpStore._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseLfpStoreServiceRestTransport._BaseDeleteLfpStore._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(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.lfp_v1beta.LfpStoreServiceClient.DeleteLfpStore", - extra = { - "serviceName": "google.shopping.merchant.lfp.v1beta.LfpStoreService", - "rpcName": "DeleteLfpStore", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = LfpStoreServiceRestTransport._DeleteLfpStore._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 _GetLfpStore(_BaseLfpStoreServiceRestTransport._BaseGetLfpStore, LfpStoreServiceRestStub): - def __hash__(self): - return hash("LfpStoreServiceRestTransport.GetLfpStore") - - @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: lfpstore.GetLfpStoreRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> lfpstore.LfpStore: - r"""Call the get lfp store method over HTTP. - - Args: - request (~.lfpstore.GetLfpStoreRequest): - The request object. Request message for the ``GetLfpStore`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.lfpstore.LfpStore: - A store for the merchant. This will - be used to match to a store under the - Google Business Profile of the target - merchant. If a matching store can't be - found, the inventories or sales - submitted with the store code will not - be used. - - """ - - http_options = _BaseLfpStoreServiceRestTransport._BaseGetLfpStore._get_http_options() - - request, metadata = self._interceptor.pre_get_lfp_store(request, metadata) - transcoded_request = _BaseLfpStoreServiceRestTransport._BaseGetLfpStore._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseLfpStoreServiceRestTransport._BaseGetLfpStore._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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.lfp_v1beta.LfpStoreServiceClient.GetLfpStore", - extra = { - "serviceName": "google.shopping.merchant.lfp.v1beta.LfpStoreService", - "rpcName": "GetLfpStore", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = LfpStoreServiceRestTransport._GetLfpStore._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 = lfpstore.LfpStore() - pb_resp = lfpstore.LfpStore.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_lfp_store(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = lfpstore.LfpStore.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.lfp_v1beta.LfpStoreServiceClient.get_lfp_store", - extra = { - "serviceName": "google.shopping.merchant.lfp.v1beta.LfpStoreService", - "rpcName": "GetLfpStore", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _InsertLfpStore(_BaseLfpStoreServiceRestTransport._BaseInsertLfpStore, LfpStoreServiceRestStub): - def __hash__(self): - return hash("LfpStoreServiceRestTransport.InsertLfpStore") - - @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: lfpstore.InsertLfpStoreRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> lfpstore.LfpStore: - r"""Call the insert lfp store method over HTTP. - - Args: - request (~.lfpstore.InsertLfpStoreRequest): - The request object. Request message for the - InsertLfpStore method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.lfpstore.LfpStore: - A store for the merchant. This will - be used to match to a store under the - Google Business Profile of the target - merchant. If a matching store can't be - found, the inventories or sales - submitted with the store code will not - be used. - - """ - - http_options = _BaseLfpStoreServiceRestTransport._BaseInsertLfpStore._get_http_options() - - request, metadata = self._interceptor.pre_insert_lfp_store(request, metadata) - transcoded_request = _BaseLfpStoreServiceRestTransport._BaseInsertLfpStore._get_transcoded_request(http_options, request) - - body = _BaseLfpStoreServiceRestTransport._BaseInsertLfpStore._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseLfpStoreServiceRestTransport._BaseInsertLfpStore._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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.lfp_v1beta.LfpStoreServiceClient.InsertLfpStore", - extra = { - "serviceName": "google.shopping.merchant.lfp.v1beta.LfpStoreService", - "rpcName": "InsertLfpStore", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = LfpStoreServiceRestTransport._InsertLfpStore._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 = lfpstore.LfpStore() - pb_resp = lfpstore.LfpStore.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_insert_lfp_store(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = lfpstore.LfpStore.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.lfp_v1beta.LfpStoreServiceClient.insert_lfp_store", - extra = { - "serviceName": "google.shopping.merchant.lfp.v1beta.LfpStoreService", - "rpcName": "InsertLfpStore", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListLfpStores(_BaseLfpStoreServiceRestTransport._BaseListLfpStores, LfpStoreServiceRestStub): - def __hash__(self): - return hash("LfpStoreServiceRestTransport.ListLfpStores") - - @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: lfpstore.ListLfpStoresRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> lfpstore.ListLfpStoresResponse: - r"""Call the list lfp stores method over HTTP. - - Args: - request (~.lfpstore.ListLfpStoresRequest): - The request object. Request message for the ListLfpStores - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.lfpstore.ListLfpStoresResponse: - Response message for the - ListLfpStores method. - - """ - - http_options = _BaseLfpStoreServiceRestTransport._BaseListLfpStores._get_http_options() - - request, metadata = self._interceptor.pre_list_lfp_stores(request, metadata) - transcoded_request = _BaseLfpStoreServiceRestTransport._BaseListLfpStores._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseLfpStoreServiceRestTransport._BaseListLfpStores._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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.lfp_v1beta.LfpStoreServiceClient.ListLfpStores", - extra = { - "serviceName": "google.shopping.merchant.lfp.v1beta.LfpStoreService", - "rpcName": "ListLfpStores", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = LfpStoreServiceRestTransport._ListLfpStores._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 = lfpstore.ListLfpStoresResponse() - pb_resp = lfpstore.ListLfpStoresResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_lfp_stores(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = lfpstore.ListLfpStoresResponse.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.lfp_v1beta.LfpStoreServiceClient.list_lfp_stores", - extra = { - "serviceName": "google.shopping.merchant.lfp.v1beta.LfpStoreService", - "rpcName": "ListLfpStores", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def delete_lfp_store(self) -> Callable[ - [lfpstore.DeleteLfpStoreRequest], - 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._DeleteLfpStore(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_lfp_store(self) -> Callable[ - [lfpstore.GetLfpStoreRequest], - lfpstore.LfpStore]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetLfpStore(self._session, self._host, self._interceptor) # type: ignore - - @property - def insert_lfp_store(self) -> Callable[ - [lfpstore.InsertLfpStoreRequest], - lfpstore.LfpStore]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._InsertLfpStore(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_lfp_stores(self) -> Callable[ - [lfpstore.ListLfpStoresRequest], - lfpstore.ListLfpStoresResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListLfpStores(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'LfpStoreServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/rest_base.py deleted file mode 100644 index b685711f10d7..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/rest_base.py +++ /dev/null @@ -1,250 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 LfpStoreServiceTransport, 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_lfp_v1beta.types import lfpstore - - -class _BaseLfpStoreServiceRestTransport(LfpStoreServiceTransport): - """Base REST backend transport for LfpStoreService. - - 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 _BaseDeleteLfpStore: - 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': '/lfp/v1beta/{name=accounts/*/lfpStores/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = lfpstore.DeleteLfpStoreRequest.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(_BaseLfpStoreServiceRestTransport._BaseDeleteLfpStore._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetLfpStore: - 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': '/lfp/v1beta/{name=accounts/*/lfpStores/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = lfpstore.GetLfpStoreRequest.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(_BaseLfpStoreServiceRestTransport._BaseGetLfpStore._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseInsertLfpStore: - 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': '/lfp/v1beta/{parent=accounts/*}/lfpStores:insert', - 'body': 'lfp_store', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = lfpstore.InsertLfpStoreRequest.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(_BaseLfpStoreServiceRestTransport._BaseInsertLfpStore._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListLfpStores: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "targetAccount" : 0, } - - @classmethod - def _get_unset_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': '/lfp/v1beta/{parent=accounts/*}/lfpStores', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = lfpstore.ListLfpStoresRequest.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(_BaseLfpStoreServiceRestTransport._BaseListLfpStores._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseLfpStoreServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/types/__init__.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/types/__init__.py deleted file mode 100644 index cf8ecc8b896a..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/types/__init__.py +++ /dev/null @@ -1,44 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .lfpinventory import ( - InsertLfpInventoryRequest, - LfpInventory, -) -from .lfpsale import ( - InsertLfpSaleRequest, - LfpSale, -) -from .lfpstore import ( - DeleteLfpStoreRequest, - GetLfpStoreRequest, - InsertLfpStoreRequest, - LfpStore, - ListLfpStoresRequest, - ListLfpStoresResponse, -) - -__all__ = ( - 'InsertLfpInventoryRequest', - 'LfpInventory', - 'InsertLfpSaleRequest', - 'LfpSale', - 'DeleteLfpStoreRequest', - 'GetLfpStoreRequest', - 'InsertLfpStoreRequest', - 'LfpStore', - 'ListLfpStoresRequest', - 'ListLfpStoresResponse', -) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/types/lfpinventory.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/types/lfpinventory.py deleted file mode 100644 index c87612bc3840..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/types/lfpinventory.py +++ /dev/null @@ -1,200 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 timestamp_pb2 # type: ignore -from google.shopping.type.types import types - - -__protobuf__ = proto.module( - package='google.shopping.merchant.lfp.v1beta', - manifest={ - 'LfpInventory', - 'InsertLfpInventoryRequest', - }, -) - - -class LfpInventory(proto.Message): - r"""Local Inventory for the merchant. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - Output only. Identifier. The name for the ``LfpInventory`` - resource. Format: - ``accounts/{account}/lfpInventories/{target_merchant}~{store_code}~{offer}`` - target_account (int): - Required. The Merchant Center ID of the - merchant to submit the inventory for. - store_code (str): - Required. The identifier of the merchant's store. Either the - store code inserted through ``InsertLfpStore`` or the store - code in the Business Profile. - offer_id (str): - Required. Immutable. A unique identifier for the product. If - both inventories and sales are submitted for a merchant, - this id should match for the same product. - - **Note**: if the merchant sells the same product new and - used, they should have different IDs. - region_code (str): - Required. The `CLDR territory - code `__ - for the country where the product is sold. - content_language (str): - Required. The two-letter ISO 639-1 language - code for the item. - gtin (str): - Optional. The Global Trade Item Number of the - product. - - This field is a member of `oneof`_ ``_gtin``. - price (google.shopping.type.types.Price): - Optional. The current price of the product. - availability (str): - Required. Availability of the product at this store. For - accepted attribute values, see the `local product inventory - data - specification `__ - quantity (int): - Optional. Quantity of the product available - at this store. Must be greater than or equal to - zero. - - This field is a member of `oneof`_ ``_quantity``. - collection_time (google.protobuf.timestamp_pb2.Timestamp): - Optional. The time when the inventory is - collected. If not set, it will be set to the - time when the inventory is submitted. - pickup_method (str): - Optional. Supported pickup method for this offer. Unless the - value is "not supported", this field must be submitted - together with ``pickupSla``. For accepted attribute values, - see the `local product inventory data - specification `__. - - This field is a member of `oneof`_ ``_pickup_method``. - pickup_sla (str): - Optional. Expected date that an order will be ready for - pickup relative to the order date. Must be submitted - together with ``pickupMethod``. For accepted attribute - values, see the `local product inventory data - specification `__. - - This field is a member of `oneof`_ ``_pickup_sla``. - feed_label (str): - Optional. The `feed - label `__ - for the product. If this is not set, it will default to - ``regionCode``. - - This field is a member of `oneof`_ ``_feed_label``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - target_account: int = proto.Field( - proto.INT64, - number=2, - ) - store_code: str = proto.Field( - proto.STRING, - number=3, - ) - offer_id: str = proto.Field( - proto.STRING, - number=4, - ) - region_code: str = proto.Field( - proto.STRING, - number=5, - ) - content_language: str = proto.Field( - proto.STRING, - number=6, - ) - gtin: str = proto.Field( - proto.STRING, - number=7, - optional=True, - ) - price: types.Price = proto.Field( - proto.MESSAGE, - number=8, - message=types.Price, - ) - availability: str = proto.Field( - proto.STRING, - number=9, - ) - quantity: int = proto.Field( - proto.INT64, - number=10, - optional=True, - ) - collection_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=11, - message=timestamp_pb2.Timestamp, - ) - pickup_method: str = proto.Field( - proto.STRING, - number=12, - optional=True, - ) - pickup_sla: str = proto.Field( - proto.STRING, - number=13, - optional=True, - ) - feed_label: str = proto.Field( - proto.STRING, - number=14, - optional=True, - ) - - -class InsertLfpInventoryRequest(proto.Message): - r"""Request message for the ``InsertLfpInventory`` method. - - Attributes: - parent (str): - Required. The LFP provider account. Format: - ``accounts/{account}`` - lfp_inventory (google.shopping.merchant_lfp_v1beta.types.LfpInventory): - Required. The inventory to insert. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - lfp_inventory: 'LfpInventory' = proto.Field( - proto.MESSAGE, - number=2, - message='LfpInventory', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/types/lfpsale.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/types/lfpsale.py deleted file mode 100644 index 765ac207bfa8..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/types/lfpsale.py +++ /dev/null @@ -1,165 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 timestamp_pb2 # type: ignore -from google.shopping.type.types import types - - -__protobuf__ = proto.module( - package='google.shopping.merchant.lfp.v1beta', - manifest={ - 'LfpSale', - 'InsertLfpSaleRequest', - }, -) - - -class LfpSale(proto.Message): - r"""A sale for the merchant. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - Output only. Identifier. The name of the ``LfpSale`` - resource. Format: ``accounts/{account}/lfpSales/{sale}`` - target_account (int): - Required. The Merchant Center ID of the - merchant to submit the sale for. - store_code (str): - Required. The identifier of the merchant's store. Either a - ``storeCode`` inserted through the API or the code of the - store in the Business Profile. - offer_id (str): - Required. A unique identifier for the product. If both - inventories and sales are submitted for a merchant, this id - should match for the same product. - - **Note**: if the merchant sells the same product new and - used, they should have different IDs. - region_code (str): - Required. The `CLDR territory - code `__ - for the country where the product is sold. - content_language (str): - Required. The two-letter ISO 639-1 language - code for the item. - gtin (str): - Required. The Global Trade Item Number of the - sold product. - price (google.shopping.type.types.Price): - Required. The unit price of the product. - quantity (int): - Required. The relative change of the - available quantity. Negative for items returned. - sale_time (google.protobuf.timestamp_pb2.Timestamp): - Required. The timestamp for the sale. - uid (str): - Output only. System generated globally unique ID for the - ``LfpSale``. - - This field is a member of `oneof`_ ``_uid``. - feed_label (str): - Optional. The `feed - label `__ - for the product. If this is not set, it will default to - ``regionCode``. - - This field is a member of `oneof`_ ``_feed_label``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - target_account: int = proto.Field( - proto.INT64, - number=2, - ) - store_code: str = proto.Field( - proto.STRING, - number=3, - ) - offer_id: str = proto.Field( - proto.STRING, - number=4, - ) - region_code: str = proto.Field( - proto.STRING, - number=5, - ) - content_language: str = proto.Field( - proto.STRING, - number=6, - ) - gtin: str = proto.Field( - proto.STRING, - number=7, - ) - price: types.Price = proto.Field( - proto.MESSAGE, - number=8, - message=types.Price, - ) - quantity: int = proto.Field( - proto.INT64, - number=9, - ) - sale_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - uid: str = proto.Field( - proto.STRING, - number=11, - optional=True, - ) - feed_label: str = proto.Field( - proto.STRING, - number=12, - optional=True, - ) - - -class InsertLfpSaleRequest(proto.Message): - r"""Request message for the InsertLfpSale method. - - Attributes: - parent (str): - Required. The LFP provider account. Format: - ``accounts/{lfp_partner}`` - lfp_sale (google.shopping.merchant_lfp_v1beta.types.LfpSale): - Required. The sale to insert. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - lfp_sale: 'LfpSale' = proto.Field( - proto.MESSAGE, - number=2, - message='LfpSale', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/types/lfpstore.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/types/lfpstore.py deleted file mode 100644 index 51c5d7c21439..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/types/lfpstore.py +++ /dev/null @@ -1,308 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.lfp.v1beta', - manifest={ - 'LfpStore', - 'GetLfpStoreRequest', - 'InsertLfpStoreRequest', - 'DeleteLfpStoreRequest', - 'ListLfpStoresRequest', - 'ListLfpStoresResponse', - }, -) - - -class LfpStore(proto.Message): - r"""A store for the merchant. This will be used to match to a - store under the Google Business Profile of the target merchant. - If a matching store can't be found, the inventories or sales - submitted with the store code will not be used. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - Output only. Identifier. The name of the ``LfpStore`` - resource. Format: - ``accounts/{account}/lfpStores/{target_merchant}~{store_code}`` - target_account (int): - Required. The Merchant Center id of the - merchant to submit the store for. - store_code (str): - Required. Immutable. A store identifier that - is unique for the target merchant. - store_address (str): - Required. The street address of the store. - Example: 1600 Amphitheatre Pkwy, Mountain View, - CA 94043, USA. - store_name (str): - Optional. The merchant or store name. - - This field is a member of `oneof`_ ``_store_name``. - phone_number (str): - Optional. The store phone number in - `E.164 `__ format. - Example: ``+15556767888`` - - This field is a member of `oneof`_ ``_phone_number``. - website_uri (str): - Optional. The website URL for the store or - merchant. - - This field is a member of `oneof`_ ``_website_uri``. - gcid_category (MutableSequence[str]): - Optional. `Google My Business category - id `__. - place_id (str): - Optional. The `Google Place - Id `__ - of the store location. - - This field is a member of `oneof`_ ``_place_id``. - matching_state (google.shopping.merchant_lfp_v1beta.types.LfpStore.StoreMatchingState): - Optional. Output only. The state of matching to a Google - Business Profile. See - [matchingStateHint][google.shopping.merchant.lfp.v1beta.LfpStore.matching_state_hint] - for further details if no match is found. - matching_state_hint (str): - Optional. Output only. The hint of why the matching has - failed. This is only set when - [matchingState][google.shopping.merchant.lfp.v1beta.LfpStore.matching_state]=``STORE_MATCHING_STATE_FAILED``. - - Possible values are: - - - "``linked-store-not-found``": There aren't any Google - Business Profile stores available for matching. - - "``store-match-not-found``": The provided ``LfpStore`` - couldn't be matched to any of the connected Google - Business Profile stores. Merchant Center account is - connected correctly and stores are available on Google - Business Profile, but the ``LfpStore`` location address - does not match with Google Business Profile stores' - addresses. Update the ``LfpStore`` address or Google - Business Profile store address to match correctly. - - "``store-match-unverified``": The provided ``LfpStore`` - couldn't be matched to any of the connected Google - Business Profile stores, as the matched Google Business - Profile store is unverified. Go through the Google - Business Profile verification process to match correctly. - - This field is a member of `oneof`_ ``_matching_state_hint``. - """ - class StoreMatchingState(proto.Enum): - r"""The state of matching ``LfpStore`` to a Google Business Profile. - - Values: - STORE_MATCHING_STATE_UNSPECIFIED (0): - Store matching state unspecified. - STORE_MATCHING_STATE_MATCHED (1): - The ``LfpStore`` is successfully matched with a Google - Business Profile store. - STORE_MATCHING_STATE_FAILED (2): - The ``LfpStore`` is not matched with a Google Business - Profile store. - """ - STORE_MATCHING_STATE_UNSPECIFIED = 0 - STORE_MATCHING_STATE_MATCHED = 1 - STORE_MATCHING_STATE_FAILED = 2 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - target_account: int = proto.Field( - proto.INT64, - number=2, - ) - store_code: str = proto.Field( - proto.STRING, - number=3, - ) - store_address: str = proto.Field( - proto.STRING, - number=4, - ) - store_name: str = proto.Field( - proto.STRING, - number=5, - optional=True, - ) - phone_number: str = proto.Field( - proto.STRING, - number=6, - optional=True, - ) - website_uri: str = proto.Field( - proto.STRING, - number=7, - optional=True, - ) - gcid_category: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=8, - ) - place_id: str = proto.Field( - proto.STRING, - number=9, - optional=True, - ) - matching_state: StoreMatchingState = proto.Field( - proto.ENUM, - number=10, - enum=StoreMatchingState, - ) - matching_state_hint: str = proto.Field( - proto.STRING, - number=11, - optional=True, - ) - - -class GetLfpStoreRequest(proto.Message): - r"""Request message for the ``GetLfpStore`` method. - - Attributes: - name (str): - Required. The name of the store to retrieve. Format: - ``accounts/{account}/lfpStores/{target_merchant}~{store_code}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class InsertLfpStoreRequest(proto.Message): - r"""Request message for the InsertLfpStore method. - - Attributes: - parent (str): - Required. The LFP provider account Format: - ``accounts/{account}`` - lfp_store (google.shopping.merchant_lfp_v1beta.types.LfpStore): - Required. The store to insert. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - lfp_store: 'LfpStore' = proto.Field( - proto.MESSAGE, - number=2, - message='LfpStore', - ) - - -class DeleteLfpStoreRequest(proto.Message): - r"""Request message for the DeleteLfpStore method. - - Attributes: - name (str): - Required. The name of the store to delete for the target - merchant account. Format: - ``accounts/{account}/lfpStores/{target_merchant}~{store_code}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListLfpStoresRequest(proto.Message): - r"""Request message for the ListLfpStores method. - - Attributes: - parent (str): - Required. The LFP partner. Format: ``accounts/{account}`` - target_account (int): - Required. The Merchant Center id of the - merchant to list stores for. - page_size (int): - Optional. The maximum number of ``LfpStore`` resources for - the given account to return. The service returns fewer than - this value if the number of stores for the given account is - less than the ``pageSize``. The default value is 250. 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 - ``ListLfpStoresRequest`` call. Provide the page token to - retrieve the subsequent page. When paginating, all other - parameters provided to ``ListLfpStoresRequest`` must match - the call that provided the page token. The token returned as - [nextPageToken][google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse.next_page_token] - in the response to the previous request. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - target_account: int = proto.Field( - proto.INT64, - number=2, - ) - page_size: int = proto.Field( - proto.INT32, - number=3, - ) - page_token: str = proto.Field( - proto.STRING, - number=4, - ) - - -class ListLfpStoresResponse(proto.Message): - r"""Response message for the ListLfpStores method. - - Attributes: - lfp_stores (MutableSequence[google.shopping.merchant_lfp_v1beta.types.LfpStore]): - The stores from the specified merchant. - 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 - - lfp_stores: MutableSequence['LfpStore'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='LfpStore', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/mypy.ini b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/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-lfp/v1beta/noxfile.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/noxfile.py deleted file mode 100644 index 00ac360425a6..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/noxfile.py +++ /dev/null @@ -1,280 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", - "3.12", - "3.13", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = 'google-shopping-merchant-lfp' - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.13" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "prerelease_deps", -] - -@nox.session(python=ALL_PYTHON) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def unit(session, protobuf_implementation): - """Run the unit test suite.""" - - 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+") - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") - - # 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") - - session.run( - 'py.test', - '--quiet', - '--cov=google/shopping/merchant_lfp_v1beta/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - -@nox.session(python=ALL_PYTHON[-1]) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def prerelease_deps(session, protobuf_implementation): - """Run the unit test suite against pre-release versions of dependencies.""" - - 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 test environment dependencies - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - - # Install the package without dependencies - session.install('-e', '.', '--no-deps') - - # We test the minimum dependency versions using the minimum Python - # version so the lowest python runtime that we test has a corresponding constraints - # file, located at `testing/constraints--.txt`, which contains all of the - # 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 - ) - ] - - session.install(*constraints_deps) - - prerel_deps = [ - "googleapis-common-protos", - "google-api-core", - "google-auth", - # Exclude grpcio!=1.67.0rc1 which does not support python 3.13 - "grpcio!=1.67.0rc1", - "grpcio-status", - "protobuf", - "proto-plus", - ] - - for dep in prerel_deps: - session.install("--pre", "--no-deps", "--upgrade", dep) - - # Remaining dependencies - other_deps = [ - "requests", - ] - session.install(*other_deps) - - # Print out prerelease package versions - - session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") - session.run("python", "-c", "import google.auth; print(google.auth.__version__)") - session.run("python", "-c", "import grpc; print(grpc.__version__)") - session.run( - "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" - ) - session.run( - "python", "-c", "import proto; print(proto.__version__)" - ) - - session.run( - 'py.test', - '--quiet', - '--cov=google/shopping/merchant_lfp_v1beta/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - - -@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=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 docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==7.0.1", "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=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", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_inventory_service_insert_lfp_inventory_async.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_inventory_service_insert_lfp_inventory_async.py deleted file mode 100644 index 3deb231592ee..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_inventory_service_insert_lfp_inventory_async.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for InsertLfpInventory -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-lfp - - -# [START merchantapi_v1beta_generated_LfpInventoryService_InsertLfpInventory_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_lfp_v1beta - - -async def sample_insert_lfp_inventory(): - # Create a client - client = merchant_lfp_v1beta.LfpInventoryServiceAsyncClient() - - # Initialize request argument(s) - lfp_inventory = merchant_lfp_v1beta.LfpInventory() - lfp_inventory.target_account = 1491 - lfp_inventory.store_code = "store_code_value" - lfp_inventory.offer_id = "offer_id_value" - lfp_inventory.region_code = "region_code_value" - lfp_inventory.content_language = "content_language_value" - lfp_inventory.availability = "availability_value" - - request = merchant_lfp_v1beta.InsertLfpInventoryRequest( - parent="parent_value", - lfp_inventory=lfp_inventory, - ) - - # Make the request - response = await client.insert_lfp_inventory(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_LfpInventoryService_InsertLfpInventory_async] diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_inventory_service_insert_lfp_inventory_sync.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_inventory_service_insert_lfp_inventory_sync.py deleted file mode 100644 index 45c4a36fe2d4..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_inventory_service_insert_lfp_inventory_sync.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for InsertLfpInventory -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-lfp - - -# [START merchantapi_v1beta_generated_LfpInventoryService_InsertLfpInventory_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_lfp_v1beta - - -def sample_insert_lfp_inventory(): - # Create a client - client = merchant_lfp_v1beta.LfpInventoryServiceClient() - - # Initialize request argument(s) - lfp_inventory = merchant_lfp_v1beta.LfpInventory() - lfp_inventory.target_account = 1491 - lfp_inventory.store_code = "store_code_value" - lfp_inventory.offer_id = "offer_id_value" - lfp_inventory.region_code = "region_code_value" - lfp_inventory.content_language = "content_language_value" - lfp_inventory.availability = "availability_value" - - request = merchant_lfp_v1beta.InsertLfpInventoryRequest( - parent="parent_value", - lfp_inventory=lfp_inventory, - ) - - # Make the request - response = client.insert_lfp_inventory(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_LfpInventoryService_InsertLfpInventory_sync] diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_sale_service_insert_lfp_sale_async.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_sale_service_insert_lfp_sale_async.py deleted file mode 100644 index 1837b8532da8..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_sale_service_insert_lfp_sale_async.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for InsertLfpSale -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-lfp - - -# [START merchantapi_v1beta_generated_LfpSaleService_InsertLfpSale_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_lfp_v1beta - - -async def sample_insert_lfp_sale(): - # Create a client - client = merchant_lfp_v1beta.LfpSaleServiceAsyncClient() - - # Initialize request argument(s) - lfp_sale = merchant_lfp_v1beta.LfpSale() - lfp_sale.target_account = 1491 - lfp_sale.store_code = "store_code_value" - lfp_sale.offer_id = "offer_id_value" - lfp_sale.region_code = "region_code_value" - lfp_sale.content_language = "content_language_value" - lfp_sale.gtin = "gtin_value" - lfp_sale.quantity = 895 - - request = merchant_lfp_v1beta.InsertLfpSaleRequest( - parent="parent_value", - lfp_sale=lfp_sale, - ) - - # Make the request - response = await client.insert_lfp_sale(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_LfpSaleService_InsertLfpSale_async] diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_sale_service_insert_lfp_sale_sync.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_sale_service_insert_lfp_sale_sync.py deleted file mode 100644 index 663261c61a6d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_sale_service_insert_lfp_sale_sync.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for InsertLfpSale -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-lfp - - -# [START merchantapi_v1beta_generated_LfpSaleService_InsertLfpSale_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_lfp_v1beta - - -def sample_insert_lfp_sale(): - # Create a client - client = merchant_lfp_v1beta.LfpSaleServiceClient() - - # Initialize request argument(s) - lfp_sale = merchant_lfp_v1beta.LfpSale() - lfp_sale.target_account = 1491 - lfp_sale.store_code = "store_code_value" - lfp_sale.offer_id = "offer_id_value" - lfp_sale.region_code = "region_code_value" - lfp_sale.content_language = "content_language_value" - lfp_sale.gtin = "gtin_value" - lfp_sale.quantity = 895 - - request = merchant_lfp_v1beta.InsertLfpSaleRequest( - parent="parent_value", - lfp_sale=lfp_sale, - ) - - # Make the request - response = client.insert_lfp_sale(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_LfpSaleService_InsertLfpSale_sync] diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_delete_lfp_store_async.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_delete_lfp_store_async.py deleted file mode 100644 index 049ac1c46d70..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_delete_lfp_store_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteLfpStore -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-lfp - - -# [START merchantapi_v1beta_generated_LfpStoreService_DeleteLfpStore_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_lfp_v1beta - - -async def sample_delete_lfp_store(): - # Create a client - client = merchant_lfp_v1beta.LfpStoreServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_lfp_v1beta.DeleteLfpStoreRequest( - name="name_value", - ) - - # Make the request - await client.delete_lfp_store(request=request) - - -# [END merchantapi_v1beta_generated_LfpStoreService_DeleteLfpStore_async] diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_delete_lfp_store_sync.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_delete_lfp_store_sync.py deleted file mode 100644 index 5340c182dc2f..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_delete_lfp_store_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteLfpStore -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-lfp - - -# [START merchantapi_v1beta_generated_LfpStoreService_DeleteLfpStore_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_lfp_v1beta - - -def sample_delete_lfp_store(): - # Create a client - client = merchant_lfp_v1beta.LfpStoreServiceClient() - - # Initialize request argument(s) - request = merchant_lfp_v1beta.DeleteLfpStoreRequest( - name="name_value", - ) - - # Make the request - client.delete_lfp_store(request=request) - - -# [END merchantapi_v1beta_generated_LfpStoreService_DeleteLfpStore_sync] diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_get_lfp_store_async.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_get_lfp_store_async.py deleted file mode 100644 index 2ca93b570e26..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_get_lfp_store_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetLfpStore -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-lfp - - -# [START merchantapi_v1beta_generated_LfpStoreService_GetLfpStore_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_lfp_v1beta - - -async def sample_get_lfp_store(): - # Create a client - client = merchant_lfp_v1beta.LfpStoreServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_lfp_v1beta.GetLfpStoreRequest( - name="name_value", - ) - - # Make the request - response = await client.get_lfp_store(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_LfpStoreService_GetLfpStore_async] diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_get_lfp_store_sync.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_get_lfp_store_sync.py deleted file mode 100644 index 6a40361b8fd6..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_get_lfp_store_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetLfpStore -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-lfp - - -# [START merchantapi_v1beta_generated_LfpStoreService_GetLfpStore_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_lfp_v1beta - - -def sample_get_lfp_store(): - # Create a client - client = merchant_lfp_v1beta.LfpStoreServiceClient() - - # Initialize request argument(s) - request = merchant_lfp_v1beta.GetLfpStoreRequest( - name="name_value", - ) - - # Make the request - response = client.get_lfp_store(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_LfpStoreService_GetLfpStore_sync] diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_insert_lfp_store_async.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_insert_lfp_store_async.py deleted file mode 100644 index 2a248dcdd969..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_insert_lfp_store_async.py +++ /dev/null @@ -1,58 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for InsertLfpStore -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-lfp - - -# [START merchantapi_v1beta_generated_LfpStoreService_InsertLfpStore_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_lfp_v1beta - - -async def sample_insert_lfp_store(): - # Create a client - client = merchant_lfp_v1beta.LfpStoreServiceAsyncClient() - - # Initialize request argument(s) - lfp_store = merchant_lfp_v1beta.LfpStore() - lfp_store.target_account = 1491 - lfp_store.store_code = "store_code_value" - lfp_store.store_address = "store_address_value" - - request = merchant_lfp_v1beta.InsertLfpStoreRequest( - parent="parent_value", - lfp_store=lfp_store, - ) - - # Make the request - response = await client.insert_lfp_store(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_LfpStoreService_InsertLfpStore_async] diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_insert_lfp_store_sync.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_insert_lfp_store_sync.py deleted file mode 100644 index 27fed1065b46..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_insert_lfp_store_sync.py +++ /dev/null @@ -1,58 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for InsertLfpStore -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-lfp - - -# [START merchantapi_v1beta_generated_LfpStoreService_InsertLfpStore_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_lfp_v1beta - - -def sample_insert_lfp_store(): - # Create a client - client = merchant_lfp_v1beta.LfpStoreServiceClient() - - # Initialize request argument(s) - lfp_store = merchant_lfp_v1beta.LfpStore() - lfp_store.target_account = 1491 - lfp_store.store_code = "store_code_value" - lfp_store.store_address = "store_address_value" - - request = merchant_lfp_v1beta.InsertLfpStoreRequest( - parent="parent_value", - lfp_store=lfp_store, - ) - - # Make the request - response = client.insert_lfp_store(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_LfpStoreService_InsertLfpStore_sync] diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_list_lfp_stores_async.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_list_lfp_stores_async.py deleted file mode 100644 index 8cee2dee7524..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_list_lfp_stores_async.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListLfpStores -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-lfp - - -# [START merchantapi_v1beta_generated_LfpStoreService_ListLfpStores_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_lfp_v1beta - - -async def sample_list_lfp_stores(): - # Create a client - client = merchant_lfp_v1beta.LfpStoreServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_lfp_v1beta.ListLfpStoresRequest( - parent="parent_value", - target_account=1491, - ) - - # Make the request - page_result = client.list_lfp_stores(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_LfpStoreService_ListLfpStores_async] diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_list_lfp_stores_sync.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_list_lfp_stores_sync.py deleted file mode 100644 index 61c063017649..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_store_service_list_lfp_stores_sync.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListLfpStores -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-lfp - - -# [START merchantapi_v1beta_generated_LfpStoreService_ListLfpStores_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_lfp_v1beta - - -def sample_list_lfp_stores(): - # Create a client - client = merchant_lfp_v1beta.LfpStoreServiceClient() - - # Initialize request argument(s) - request = merchant_lfp_v1beta.ListLfpStoresRequest( - parent="parent_value", - target_account=1491, - ) - - # Make the request - page_result = client.list_lfp_stores(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_LfpStoreService_ListLfpStores_sync] diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.lfp.v1beta.json b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.lfp.v1beta.json deleted file mode 100644 index c88051dded42..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.lfp.v1beta.json +++ /dev/null @@ -1,967 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.shopping.merchant.lfp.v1beta", - "version": "v1beta" - } - ], - "language": "PYTHON", - "name": "google-shopping-merchant-lfp", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_lfp_v1beta.LfpInventoryServiceAsyncClient", - "shortName": "LfpInventoryServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_lfp_v1beta.LfpInventoryServiceAsyncClient.insert_lfp_inventory", - "method": { - "fullName": "google.shopping.merchant.lfp.v1beta.LfpInventoryService.InsertLfpInventory", - "service": { - "fullName": "google.shopping.merchant.lfp.v1beta.LfpInventoryService", - "shortName": "LfpInventoryService" - }, - "shortName": "InsertLfpInventory" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_lfp_v1beta.types.InsertLfpInventoryRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.shopping.merchant_lfp_v1beta.types.LfpInventory", - "shortName": "insert_lfp_inventory" - }, - "description": "Sample for InsertLfpInventory", - "file": "merchantapi_v1beta_generated_lfp_inventory_service_insert_lfp_inventory_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_LfpInventoryService_InsertLfpInventory_async", - "segments": [ - { - "end": 60, - "start": 27, - "type": "FULL" - }, - { - "end": 60, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 54, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 57, - "start": 55, - "type": "REQUEST_EXECUTION" - }, - { - "end": 61, - "start": 58, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_lfp_inventory_service_insert_lfp_inventory_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_lfp_v1beta.LfpInventoryServiceClient", - "shortName": "LfpInventoryServiceClient" - }, - "fullName": "google.shopping.merchant_lfp_v1beta.LfpInventoryServiceClient.insert_lfp_inventory", - "method": { - "fullName": "google.shopping.merchant.lfp.v1beta.LfpInventoryService.InsertLfpInventory", - "service": { - "fullName": "google.shopping.merchant.lfp.v1beta.LfpInventoryService", - "shortName": "LfpInventoryService" - }, - "shortName": "InsertLfpInventory" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_lfp_v1beta.types.InsertLfpInventoryRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.shopping.merchant_lfp_v1beta.types.LfpInventory", - "shortName": "insert_lfp_inventory" - }, - "description": "Sample for InsertLfpInventory", - "file": "merchantapi_v1beta_generated_lfp_inventory_service_insert_lfp_inventory_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_LfpInventoryService_InsertLfpInventory_sync", - "segments": [ - { - "end": 60, - "start": 27, - "type": "FULL" - }, - { - "end": 60, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 54, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 57, - "start": 55, - "type": "REQUEST_EXECUTION" - }, - { - "end": 61, - "start": 58, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_lfp_inventory_service_insert_lfp_inventory_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_lfp_v1beta.LfpSaleServiceAsyncClient", - "shortName": "LfpSaleServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_lfp_v1beta.LfpSaleServiceAsyncClient.insert_lfp_sale", - "method": { - "fullName": "google.shopping.merchant.lfp.v1beta.LfpSaleService.InsertLfpSale", - "service": { - "fullName": "google.shopping.merchant.lfp.v1beta.LfpSaleService", - "shortName": "LfpSaleService" - }, - "shortName": "InsertLfpSale" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_lfp_v1beta.types.InsertLfpSaleRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.shopping.merchant_lfp_v1beta.types.LfpSale", - "shortName": "insert_lfp_sale" - }, - "description": "Sample for InsertLfpSale", - "file": "merchantapi_v1beta_generated_lfp_sale_service_insert_lfp_sale_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_LfpSaleService_InsertLfpSale_async", - "segments": [ - { - "end": 61, - "start": 27, - "type": "FULL" - }, - { - "end": 61, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 55, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 58, - "start": 56, - "type": "REQUEST_EXECUTION" - }, - { - "end": 62, - "start": 59, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_lfp_sale_service_insert_lfp_sale_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_lfp_v1beta.LfpSaleServiceClient", - "shortName": "LfpSaleServiceClient" - }, - "fullName": "google.shopping.merchant_lfp_v1beta.LfpSaleServiceClient.insert_lfp_sale", - "method": { - "fullName": "google.shopping.merchant.lfp.v1beta.LfpSaleService.InsertLfpSale", - "service": { - "fullName": "google.shopping.merchant.lfp.v1beta.LfpSaleService", - "shortName": "LfpSaleService" - }, - "shortName": "InsertLfpSale" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_lfp_v1beta.types.InsertLfpSaleRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.shopping.merchant_lfp_v1beta.types.LfpSale", - "shortName": "insert_lfp_sale" - }, - "description": "Sample for InsertLfpSale", - "file": "merchantapi_v1beta_generated_lfp_sale_service_insert_lfp_sale_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_LfpSaleService_InsertLfpSale_sync", - "segments": [ - { - "end": 61, - "start": 27, - "type": "FULL" - }, - { - "end": 61, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 55, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 58, - "start": 56, - "type": "REQUEST_EXECUTION" - }, - { - "end": 62, - "start": 59, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_lfp_sale_service_insert_lfp_sale_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_lfp_v1beta.LfpStoreServiceAsyncClient", - "shortName": "LfpStoreServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_lfp_v1beta.LfpStoreServiceAsyncClient.delete_lfp_store", - "method": { - "fullName": "google.shopping.merchant.lfp.v1beta.LfpStoreService.DeleteLfpStore", - "service": { - "fullName": "google.shopping.merchant.lfp.v1beta.LfpStoreService", - "shortName": "LfpStoreService" - }, - "shortName": "DeleteLfpStore" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_lfp_v1beta.types.DeleteLfpStoreRequest" - }, - { - "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_lfp_store" - }, - "description": "Sample for DeleteLfpStore", - "file": "merchantapi_v1beta_generated_lfp_store_service_delete_lfp_store_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_LfpStoreService_DeleteLfpStore_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_lfp_store_service_delete_lfp_store_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_lfp_v1beta.LfpStoreServiceClient", - "shortName": "LfpStoreServiceClient" - }, - "fullName": "google.shopping.merchant_lfp_v1beta.LfpStoreServiceClient.delete_lfp_store", - "method": { - "fullName": "google.shopping.merchant.lfp.v1beta.LfpStoreService.DeleteLfpStore", - "service": { - "fullName": "google.shopping.merchant.lfp.v1beta.LfpStoreService", - "shortName": "LfpStoreService" - }, - "shortName": "DeleteLfpStore" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_lfp_v1beta.types.DeleteLfpStoreRequest" - }, - { - "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_lfp_store" - }, - "description": "Sample for DeleteLfpStore", - "file": "merchantapi_v1beta_generated_lfp_store_service_delete_lfp_store_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_LfpStoreService_DeleteLfpStore_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_lfp_store_service_delete_lfp_store_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_lfp_v1beta.LfpStoreServiceAsyncClient", - "shortName": "LfpStoreServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_lfp_v1beta.LfpStoreServiceAsyncClient.get_lfp_store", - "method": { - "fullName": "google.shopping.merchant.lfp.v1beta.LfpStoreService.GetLfpStore", - "service": { - "fullName": "google.shopping.merchant.lfp.v1beta.LfpStoreService", - "shortName": "LfpStoreService" - }, - "shortName": "GetLfpStore" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_lfp_v1beta.types.GetLfpStoreRequest" - }, - { - "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_lfp_v1beta.types.LfpStore", - "shortName": "get_lfp_store" - }, - "description": "Sample for GetLfpStore", - "file": "merchantapi_v1beta_generated_lfp_store_service_get_lfp_store_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_LfpStoreService_GetLfpStore_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_lfp_store_service_get_lfp_store_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_lfp_v1beta.LfpStoreServiceClient", - "shortName": "LfpStoreServiceClient" - }, - "fullName": "google.shopping.merchant_lfp_v1beta.LfpStoreServiceClient.get_lfp_store", - "method": { - "fullName": "google.shopping.merchant.lfp.v1beta.LfpStoreService.GetLfpStore", - "service": { - "fullName": "google.shopping.merchant.lfp.v1beta.LfpStoreService", - "shortName": "LfpStoreService" - }, - "shortName": "GetLfpStore" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_lfp_v1beta.types.GetLfpStoreRequest" - }, - { - "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_lfp_v1beta.types.LfpStore", - "shortName": "get_lfp_store" - }, - "description": "Sample for GetLfpStore", - "file": "merchantapi_v1beta_generated_lfp_store_service_get_lfp_store_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_LfpStoreService_GetLfpStore_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_lfp_store_service_get_lfp_store_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_lfp_v1beta.LfpStoreServiceAsyncClient", - "shortName": "LfpStoreServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_lfp_v1beta.LfpStoreServiceAsyncClient.insert_lfp_store", - "method": { - "fullName": "google.shopping.merchant.lfp.v1beta.LfpStoreService.InsertLfpStore", - "service": { - "fullName": "google.shopping.merchant.lfp.v1beta.LfpStoreService", - "shortName": "LfpStoreService" - }, - "shortName": "InsertLfpStore" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_lfp_v1beta.types.InsertLfpStoreRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "lfp_store", - "type": "google.shopping.merchant_lfp_v1beta.types.LfpStore" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.shopping.merchant_lfp_v1beta.types.LfpStore", - "shortName": "insert_lfp_store" - }, - "description": "Sample for InsertLfpStore", - "file": "merchantapi_v1beta_generated_lfp_store_service_insert_lfp_store_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_LfpStoreService_InsertLfpStore_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_lfp_store_service_insert_lfp_store_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_lfp_v1beta.LfpStoreServiceClient", - "shortName": "LfpStoreServiceClient" - }, - "fullName": "google.shopping.merchant_lfp_v1beta.LfpStoreServiceClient.insert_lfp_store", - "method": { - "fullName": "google.shopping.merchant.lfp.v1beta.LfpStoreService.InsertLfpStore", - "service": { - "fullName": "google.shopping.merchant.lfp.v1beta.LfpStoreService", - "shortName": "LfpStoreService" - }, - "shortName": "InsertLfpStore" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_lfp_v1beta.types.InsertLfpStoreRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "lfp_store", - "type": "google.shopping.merchant_lfp_v1beta.types.LfpStore" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.shopping.merchant_lfp_v1beta.types.LfpStore", - "shortName": "insert_lfp_store" - }, - "description": "Sample for InsertLfpStore", - "file": "merchantapi_v1beta_generated_lfp_store_service_insert_lfp_store_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_LfpStoreService_InsertLfpStore_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_lfp_store_service_insert_lfp_store_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_lfp_v1beta.LfpStoreServiceAsyncClient", - "shortName": "LfpStoreServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_lfp_v1beta.LfpStoreServiceAsyncClient.list_lfp_stores", - "method": { - "fullName": "google.shopping.merchant.lfp.v1beta.LfpStoreService.ListLfpStores", - "service": { - "fullName": "google.shopping.merchant.lfp.v1beta.LfpStoreService", - "shortName": "LfpStoreService" - }, - "shortName": "ListLfpStores" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_lfp_v1beta.types.ListLfpStoresRequest" - }, - { - "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_lfp_v1beta.services.lfp_store_service.pagers.ListLfpStoresAsyncPager", - "shortName": "list_lfp_stores" - }, - "description": "Sample for ListLfpStores", - "file": "merchantapi_v1beta_generated_lfp_store_service_list_lfp_stores_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_LfpStoreService_ListLfpStores_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "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": 54, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_lfp_store_service_list_lfp_stores_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_lfp_v1beta.LfpStoreServiceClient", - "shortName": "LfpStoreServiceClient" - }, - "fullName": "google.shopping.merchant_lfp_v1beta.LfpStoreServiceClient.list_lfp_stores", - "method": { - "fullName": "google.shopping.merchant.lfp.v1beta.LfpStoreService.ListLfpStores", - "service": { - "fullName": "google.shopping.merchant.lfp.v1beta.LfpStoreService", - "shortName": "LfpStoreService" - }, - "shortName": "ListLfpStores" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_lfp_v1beta.types.ListLfpStoresRequest" - }, - { - "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_lfp_v1beta.services.lfp_store_service.pagers.ListLfpStoresPager", - "shortName": "list_lfp_stores" - }, - "description": "Sample for ListLfpStores", - "file": "merchantapi_v1beta_generated_lfp_store_service_list_lfp_stores_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_LfpStoreService_ListLfpStores_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "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": 54, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_lfp_store_service_list_lfp_stores_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/scripts/fixup_merchant_lfp_v1beta_keywords.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/scripts/fixup_merchant_lfp_v1beta_keywords.py deleted file mode 100644 index f94ed4a889c2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/scripts/fixup_merchant_lfp_v1beta_keywords.py +++ /dev/null @@ -1,181 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_lfpCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'delete_lfp_store': ('name', ), - 'get_lfp_store': ('name', ), - 'insert_lfp_inventory': ('parent', 'lfp_inventory', ), - 'insert_lfp_sale': ('parent', 'lfp_sale', ), - 'insert_lfp_store': ('parent', 'lfp_store', ), - 'list_lfp_stores': ('parent', 'target_account', 'page_size', 'page_token', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=merchant_lfpCallTransformer(), -): - """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_lfp 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-lfp/v1beta/setup.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/setup.py deleted file mode 100644 index c80b6726642d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/setup.py +++ /dev/null @@ -1,99 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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-lfp' - - -description = "Google Shopping Merchant Lfp API client library" - -version = None - -with open(os.path.join(package_root, 'google/shopping/merchant_lfp/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.0dev,!=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.0dev,!=2.24.0,!=2.25.0", - "proto-plus >= 1.22.3, <2.0.0dev", - "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'", - "protobuf>=3.20.2,<6.0.0dev,!=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.0dev", -] -extras = { -} -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-lfp" - -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-lfp/v1beta/testing/constraints-3.10.txt b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/testing/constraints-3.10.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/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-lfp/v1beta/testing/constraints-3.11.txt b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/testing/constraints-3.11.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/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-lfp/v1beta/testing/constraints-3.12.txt b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/testing/constraints-3.12.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/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-lfp/v1beta/testing/constraints-3.13.txt b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/testing/constraints-3.13.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/testing/constraints-3.13.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-lfp/v1beta/testing/constraints-3.7.txt b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/testing/constraints-3.7.txt deleted file mode 100644 index 130a0c0f80ab..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/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.0dev", -# 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-lfp/v1beta/testing/constraints-3.8.txt b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/testing/constraints-3.8.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/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-lfp/v1beta/testing/constraints-3.9.txt b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/testing/constraints-3.9.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/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-lfp/v1beta/tests/__init__.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-lfp/v1beta/tests/unit/__init__.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-lfp/v1beta/tests/unit/gapic/__init__.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-lfp/v1beta/tests/unit/gapic/merchant_lfp_v1beta/__init__.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/tests/unit/gapic/merchant_lfp_v1beta/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/tests/unit/gapic/merchant_lfp_v1beta/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-lfp/v1beta/tests/unit/gapic/merchant_lfp_v1beta/test_lfp_inventory_service.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/tests/unit/gapic/merchant_lfp_v1beta/test_lfp_inventory_service.py deleted file mode 100644 index 277752435069..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/tests/unit/gapic/merchant_lfp_v1beta/test_lfp_inventory_service.py +++ /dev/null @@ -1,2095 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable, AsyncIterable -from google.protobuf import json_format -import json -import math -import pytest -from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -try: - from google.auth.aio import credentials as ga_credentials_async - HAS_GOOGLE_AUTH_AIO = True -except ImportError: # pragma: NO COVER - HAS_GOOGLE_AUTH_AIO = False - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.oauth2 import service_account -from google.protobuf import timestamp_pb2 # type: ignore -from google.shopping.merchant_lfp_v1beta.services.lfp_inventory_service import LfpInventoryServiceAsyncClient -from google.shopping.merchant_lfp_v1beta.services.lfp_inventory_service import LfpInventoryServiceClient -from google.shopping.merchant_lfp_v1beta.services.lfp_inventory_service import transports -from google.shopping.merchant_lfp_v1beta.types import lfpinventory -from google.shopping.type.types import types -import google.auth - - -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 LfpInventoryServiceClient._get_default_mtls_endpoint(None) is None - assert LfpInventoryServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert LfpInventoryServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert LfpInventoryServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert LfpInventoryServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert LfpInventoryServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert LfpInventoryServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert LfpInventoryServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert LfpInventoryServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - LfpInventoryServiceClient._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 LfpInventoryServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert LfpInventoryServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert LfpInventoryServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - LfpInventoryServiceClient._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 LfpInventoryServiceClient._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 LfpInventoryServiceClient._get_client_cert_source(None, False) is None - assert LfpInventoryServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert LfpInventoryServiceClient._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 LfpInventoryServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert LfpInventoryServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(LfpInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpInventoryServiceClient)) -@mock.patch.object(LfpInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpInventoryServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = LfpInventoryServiceClient._DEFAULT_UNIVERSE - default_endpoint = LfpInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = LfpInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert LfpInventoryServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert LfpInventoryServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == LfpInventoryServiceClient.DEFAULT_MTLS_ENDPOINT - assert LfpInventoryServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert LfpInventoryServiceClient._get_api_endpoint(None, None, default_universe, "always") == LfpInventoryServiceClient.DEFAULT_MTLS_ENDPOINT - assert LfpInventoryServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == LfpInventoryServiceClient.DEFAULT_MTLS_ENDPOINT - assert LfpInventoryServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert LfpInventoryServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - LfpInventoryServiceClient._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 LfpInventoryServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert LfpInventoryServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert LfpInventoryServiceClient._get_universe_domain(None, None) == LfpInventoryServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - LfpInventoryServiceClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - - -@pytest.mark.parametrize("client_class,transport_name", [ - (LfpInventoryServiceClient, "grpc"), - (LfpInventoryServiceAsyncClient, "grpc_asyncio"), - (LfpInventoryServiceClient, "rest"), -]) -def test_lfp_inventory_service_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'merchantapi.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://merchantapi.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.LfpInventoryServiceGrpcTransport, "grpc"), - (transports.LfpInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.LfpInventoryServiceRestTransport, "rest"), -]) -def test_lfp_inventory_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (LfpInventoryServiceClient, "grpc"), - (LfpInventoryServiceAsyncClient, "grpc_asyncio"), - (LfpInventoryServiceClient, "rest"), -]) -def test_lfp_inventory_service_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'merchantapi.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://merchantapi.googleapis.com' - ) - - -def test_lfp_inventory_service_client_get_transport_class(): - transport = LfpInventoryServiceClient.get_transport_class() - available_transports = [ - transports.LfpInventoryServiceGrpcTransport, - transports.LfpInventoryServiceRestTransport, - ] - assert transport in available_transports - - transport = LfpInventoryServiceClient.get_transport_class("grpc") - assert transport == transports.LfpInventoryServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (LfpInventoryServiceClient, transports.LfpInventoryServiceGrpcTransport, "grpc"), - (LfpInventoryServiceAsyncClient, transports.LfpInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (LfpInventoryServiceClient, transports.LfpInventoryServiceRestTransport, "rest"), -]) -@mock.patch.object(LfpInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpInventoryServiceClient)) -@mock.patch.object(LfpInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpInventoryServiceAsyncClient)) -def test_lfp_inventory_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(LfpInventoryServiceClient, '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(LfpInventoryServiceClient, '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", [ - (LfpInventoryServiceClient, transports.LfpInventoryServiceGrpcTransport, "grpc", "true"), - (LfpInventoryServiceAsyncClient, transports.LfpInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (LfpInventoryServiceClient, transports.LfpInventoryServiceGrpcTransport, "grpc", "false"), - (LfpInventoryServiceAsyncClient, transports.LfpInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (LfpInventoryServiceClient, transports.LfpInventoryServiceRestTransport, "rest", "true"), - (LfpInventoryServiceClient, transports.LfpInventoryServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(LfpInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpInventoryServiceClient)) -@mock.patch.object(LfpInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpInventoryServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_lfp_inventory_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - LfpInventoryServiceClient, LfpInventoryServiceAsyncClient -]) -@mock.patch.object(LfpInventoryServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LfpInventoryServiceClient)) -@mock.patch.object(LfpInventoryServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LfpInventoryServiceAsyncClient)) -def test_lfp_inventory_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - -@pytest.mark.parametrize("client_class", [ - LfpInventoryServiceClient, LfpInventoryServiceAsyncClient -]) -@mock.patch.object(LfpInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpInventoryServiceClient)) -@mock.patch.object(LfpInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpInventoryServiceAsyncClient)) -def test_lfp_inventory_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = LfpInventoryServiceClient._DEFAULT_UNIVERSE - default_endpoint = LfpInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = LfpInventoryServiceClient._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", [ - (LfpInventoryServiceClient, transports.LfpInventoryServiceGrpcTransport, "grpc"), - (LfpInventoryServiceAsyncClient, transports.LfpInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (LfpInventoryServiceClient, transports.LfpInventoryServiceRestTransport, "rest"), -]) -def test_lfp_inventory_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (LfpInventoryServiceClient, transports.LfpInventoryServiceGrpcTransport, "grpc", grpc_helpers), - (LfpInventoryServiceAsyncClient, transports.LfpInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (LfpInventoryServiceClient, transports.LfpInventoryServiceRestTransport, "rest", None), -]) -def test_lfp_inventory_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_lfp_inventory_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_lfp_v1beta.services.lfp_inventory_service.transports.LfpInventoryServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = LfpInventoryServiceClient( - 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", [ - (LfpInventoryServiceClient, transports.LfpInventoryServiceGrpcTransport, "grpc", grpc_helpers), - (LfpInventoryServiceAsyncClient, transports.LfpInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_lfp_inventory_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "merchantapi.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/content', -), - scopes=None, - default_host="merchantapi.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - lfpinventory.InsertLfpInventoryRequest, - dict, -]) -def test_insert_lfp_inventory(request_type, transport: str = 'grpc'): - client = LfpInventoryServiceClient( - 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_lfp_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = lfpinventory.LfpInventory( - name='name_value', - target_account=1491, - store_code='store_code_value', - offer_id='offer_id_value', - region_code='region_code_value', - content_language='content_language_value', - gtin='gtin_value', - availability='availability_value', - quantity=895, - pickup_method='pickup_method_value', - pickup_sla='pickup_sla_value', - feed_label='feed_label_value', - ) - response = client.insert_lfp_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = lfpinventory.InsertLfpInventoryRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, lfpinventory.LfpInventory) - assert response.name == 'name_value' - assert response.target_account == 1491 - assert response.store_code == 'store_code_value' - assert response.offer_id == 'offer_id_value' - assert response.region_code == 'region_code_value' - assert response.content_language == 'content_language_value' - assert response.gtin == 'gtin_value' - assert response.availability == 'availability_value' - assert response.quantity == 895 - assert response.pickup_method == 'pickup_method_value' - assert response.pickup_sla == 'pickup_sla_value' - assert response.feed_label == 'feed_label_value' - - -def test_insert_lfp_inventory_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = LfpInventoryServiceClient( - 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 = lfpinventory.InsertLfpInventoryRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.insert_lfp_inventory), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.insert_lfp_inventory(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == lfpinventory.InsertLfpInventoryRequest( - parent='parent_value', - ) - -def test_insert_lfp_inventory_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = LfpInventoryServiceClient( - 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_lfp_inventory in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.insert_lfp_inventory] = mock_rpc - request = {} - client.insert_lfp_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.insert_lfp_inventory(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_insert_lfp_inventory_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = LfpInventoryServiceAsyncClient( - 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_lfp_inventory in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.insert_lfp_inventory] = mock_rpc - - request = {} - await client.insert_lfp_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.insert_lfp_inventory(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_insert_lfp_inventory_async(transport: str = 'grpc_asyncio', request_type=lfpinventory.InsertLfpInventoryRequest): - client = LfpInventoryServiceAsyncClient( - 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_lfp_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(lfpinventory.LfpInventory( - name='name_value', - target_account=1491, - store_code='store_code_value', - offer_id='offer_id_value', - region_code='region_code_value', - content_language='content_language_value', - gtin='gtin_value', - availability='availability_value', - quantity=895, - pickup_method='pickup_method_value', - pickup_sla='pickup_sla_value', - feed_label='feed_label_value', - )) - response = await client.insert_lfp_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = lfpinventory.InsertLfpInventoryRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, lfpinventory.LfpInventory) - assert response.name == 'name_value' - assert response.target_account == 1491 - assert response.store_code == 'store_code_value' - assert response.offer_id == 'offer_id_value' - assert response.region_code == 'region_code_value' - assert response.content_language == 'content_language_value' - assert response.gtin == 'gtin_value' - assert response.availability == 'availability_value' - assert response.quantity == 895 - assert response.pickup_method == 'pickup_method_value' - assert response.pickup_sla == 'pickup_sla_value' - assert response.feed_label == 'feed_label_value' - - -@pytest.mark.asyncio -async def test_insert_lfp_inventory_async_from_dict(): - await test_insert_lfp_inventory_async(request_type=dict) - -def test_insert_lfp_inventory_field_headers(): - client = LfpInventoryServiceClient( - 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 = lfpinventory.InsertLfpInventoryRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.insert_lfp_inventory), - '__call__') as call: - call.return_value = lfpinventory.LfpInventory() - client.insert_lfp_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_insert_lfp_inventory_field_headers_async(): - client = LfpInventoryServiceAsyncClient( - 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 = lfpinventory.InsertLfpInventoryRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.insert_lfp_inventory), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpinventory.LfpInventory()) - await client.insert_lfp_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_insert_lfp_inventory_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = LfpInventoryServiceClient( - 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_lfp_inventory in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.insert_lfp_inventory] = mock_rpc - - request = {} - client.insert_lfp_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.insert_lfp_inventory(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_insert_lfp_inventory_rest_required_fields(request_type=lfpinventory.InsertLfpInventoryRequest): - transport_class = transports.LfpInventoryServiceRestTransport - - 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_lfp_inventory._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).insert_lfp_inventory._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = LfpInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = lfpinventory.LfpInventory() - # 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 = lfpinventory.LfpInventory.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_lfp_inventory(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_insert_lfp_inventory_rest_unset_required_fields(): - transport = transports.LfpInventoryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.insert_lfp_inventory._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "lfpInventory", ))) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.LfpInventoryServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = LfpInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.LfpInventoryServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = LfpInventoryServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.LfpInventoryServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = LfpInventoryServiceClient( - 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 = LfpInventoryServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.LfpInventoryServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = LfpInventoryServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.LfpInventoryServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = LfpInventoryServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.LfpInventoryServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.LfpInventoryServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.LfpInventoryServiceGrpcTransport, - transports.LfpInventoryServiceGrpcAsyncIOTransport, - transports.LfpInventoryServiceRestTransport, -]) -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 = LfpInventoryServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = LfpInventoryServiceClient( - 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_insert_lfp_inventory_empty_call_grpc(): - client = LfpInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.insert_lfp_inventory), - '__call__') as call: - call.return_value = lfpinventory.LfpInventory() - client.insert_lfp_inventory(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = lfpinventory.InsertLfpInventoryRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = LfpInventoryServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = LfpInventoryServiceAsyncClient( - 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_insert_lfp_inventory_empty_call_grpc_asyncio(): - client = LfpInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.insert_lfp_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpinventory.LfpInventory( - name='name_value', - target_account=1491, - store_code='store_code_value', - offer_id='offer_id_value', - region_code='region_code_value', - content_language='content_language_value', - gtin='gtin_value', - availability='availability_value', - quantity=895, - pickup_method='pickup_method_value', - pickup_sla='pickup_sla_value', - feed_label='feed_label_value', - )) - await client.insert_lfp_inventory(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = lfpinventory.InsertLfpInventoryRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = LfpInventoryServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_insert_lfp_inventory_rest_bad_request(request_type=lfpinventory.InsertLfpInventoryRequest): - client = LfpInventoryServiceClient( - 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_lfp_inventory(request) - - -@pytest.mark.parametrize("request_type", [ - lfpinventory.InsertLfpInventoryRequest, - dict, -]) -def test_insert_lfp_inventory_rest_call_success(request_type): - client = LfpInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} - request_init["lfp_inventory"] = {'name': 'name_value', 'target_account': 1491, 'store_code': 'store_code_value', 'offer_id': 'offer_id_value', 'region_code': 'region_code_value', 'content_language': 'content_language_value', 'gtin': 'gtin_value', 'price': {'amount_micros': 1408, 'currency_code': 'currency_code_value'}, 'availability': 'availability_value', 'quantity': 895, 'collection_time': {'seconds': 751, 'nanos': 543}, 'pickup_method': 'pickup_method_value', 'pickup_sla': 'pickup_sla_value', 'feed_label': 'feed_label_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 = lfpinventory.InsertLfpInventoryRequest.meta.fields["lfp_inventory"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["lfp_inventory"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["lfp_inventory"][field])): - del request_init["lfp_inventory"][field][i][subfield] - else: - del request_init["lfp_inventory"][field][subfield] - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = lfpinventory.LfpInventory( - name='name_value', - target_account=1491, - store_code='store_code_value', - offer_id='offer_id_value', - region_code='region_code_value', - content_language='content_language_value', - gtin='gtin_value', - availability='availability_value', - quantity=895, - pickup_method='pickup_method_value', - pickup_sla='pickup_sla_value', - feed_label='feed_label_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 = lfpinventory.LfpInventory.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_lfp_inventory(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, lfpinventory.LfpInventory) - assert response.name == 'name_value' - assert response.target_account == 1491 - assert response.store_code == 'store_code_value' - assert response.offer_id == 'offer_id_value' - assert response.region_code == 'region_code_value' - assert response.content_language == 'content_language_value' - assert response.gtin == 'gtin_value' - assert response.availability == 'availability_value' - assert response.quantity == 895 - assert response.pickup_method == 'pickup_method_value' - assert response.pickup_sla == 'pickup_sla_value' - assert response.feed_label == 'feed_label_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_insert_lfp_inventory_rest_interceptors(null_interceptor): - transport = transports.LfpInventoryServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.LfpInventoryServiceRestInterceptor(), - ) - client = LfpInventoryServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.LfpInventoryServiceRestInterceptor, "post_insert_lfp_inventory") as post, \ - mock.patch.object(transports.LfpInventoryServiceRestInterceptor, "pre_insert_lfp_inventory") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = lfpinventory.InsertLfpInventoryRequest.pb(lfpinventory.InsertLfpInventoryRequest()) - 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 = lfpinventory.LfpInventory.to_json(lfpinventory.LfpInventory()) - req.return_value.content = return_value - - request = lfpinventory.InsertLfpInventoryRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = lfpinventory.LfpInventory() - - client.insert_lfp_inventory(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - -def test_initialize_client_w_rest(): - client = LfpInventoryServiceClient( - 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_insert_lfp_inventory_empty_call_rest(): - client = LfpInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.insert_lfp_inventory), - '__call__') as call: - client.insert_lfp_inventory(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = lfpinventory.InsertLfpInventoryRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = LfpInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.LfpInventoryServiceGrpcTransport, - ) - -def test_lfp_inventory_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.LfpInventoryServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_lfp_inventory_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.shopping.merchant_lfp_v1beta.services.lfp_inventory_service.transports.LfpInventoryServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.LfpInventoryServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'insert_lfp_inventory', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_lfp_inventory_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.shopping.merchant_lfp_v1beta.services.lfp_inventory_service.transports.LfpInventoryServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.LfpInventoryServiceTransport( - 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_inventory_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.shopping.merchant_lfp_v1beta.services.lfp_inventory_service.transports.LfpInventoryServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.LfpInventoryServiceTransport() - adc.assert_called_once() - - -def test_lfp_inventory_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - LfpInventoryServiceClient() - 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.LfpInventoryServiceGrpcTransport, - transports.LfpInventoryServiceGrpcAsyncIOTransport, - ], -) -def test_lfp_inventory_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/content',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.LfpInventoryServiceGrpcTransport, - transports.LfpInventoryServiceGrpcAsyncIOTransport, - transports.LfpInventoryServiceRestTransport, - ], -) -def test_lfp_inventory_service_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.LfpInventoryServiceGrpcTransport, grpc_helpers), - (transports.LfpInventoryServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_lfp_inventory_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "merchantapi.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/content', -), - scopes=["1", "2"], - default_host="merchantapi.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.LfpInventoryServiceGrpcTransport, transports.LfpInventoryServiceGrpcAsyncIOTransport]) -def test_lfp_inventory_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_lfp_inventory_service_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.LfpInventoryServiceRestTransport ( - 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_inventory_service_host_no_port(transport_name): - client = LfpInventoryServiceClient( - 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_inventory_service_host_with_port(transport_name): - client = LfpInventoryServiceClient( - 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_inventory_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = LfpInventoryServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = LfpInventoryServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.insert_lfp_inventory._session - session2 = client2.transport.insert_lfp_inventory._session - assert session1 != session2 -def test_lfp_inventory_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.LfpInventoryServiceGrpcTransport( - 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_inventory_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.LfpInventoryServiceGrpcAsyncIOTransport( - 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.LfpInventoryServiceGrpcTransport, transports.LfpInventoryServiceGrpcAsyncIOTransport]) -def test_lfp_inventory_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.LfpInventoryServiceGrpcTransport, transports.LfpInventoryServiceGrpcAsyncIOTransport]) -def test_lfp_inventory_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_lfp_inventory_path(): - account = "squid" - target_merchant = "clam" - store_code = "whelk" - offer = "octopus" - expected = "accounts/{account}/lfpInventories/{target_merchant}~{store_code}~{offer}".format(account=account, target_merchant=target_merchant, store_code=store_code, offer=offer, ) - actual = LfpInventoryServiceClient.lfp_inventory_path(account, target_merchant, store_code, offer) - assert expected == actual - - -def test_parse_lfp_inventory_path(): - expected = { - "account": "oyster", - "target_merchant": "nudibranch", - "store_code": "cuttlefish", - "offer": "mussel", - } - path = LfpInventoryServiceClient.lfp_inventory_path(**expected) - - # Check that the path construction is reversible. - actual = LfpInventoryServiceClient.parse_lfp_inventory_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = LfpInventoryServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nautilus", - } - path = LfpInventoryServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = LfpInventoryServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "scallop" - expected = "folders/{folder}".format(folder=folder, ) - actual = LfpInventoryServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "abalone", - } - path = LfpInventoryServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = LfpInventoryServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "squid" - expected = "organizations/{organization}".format(organization=organization, ) - actual = LfpInventoryServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "clam", - } - path = LfpInventoryServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = LfpInventoryServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "whelk" - expected = "projects/{project}".format(project=project, ) - actual = LfpInventoryServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "octopus", - } - path = LfpInventoryServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = LfpInventoryServiceClient.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 = LfpInventoryServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "cuttlefish", - "location": "mussel", - } - path = LfpInventoryServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = LfpInventoryServiceClient.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.LfpInventoryServiceTransport, '_prep_wrapped_messages') as prep: - client = LfpInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.LfpInventoryServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = LfpInventoryServiceClient.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 = LfpInventoryServiceClient( - 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 = LfpInventoryServiceAsyncClient( - 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 = LfpInventoryServiceClient( - 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 = LfpInventoryServiceClient( - 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", [ - (LfpInventoryServiceClient, transports.LfpInventoryServiceGrpcTransport), - (LfpInventoryServiceAsyncClient, transports.LfpInventoryServiceGrpcAsyncIOTransport), -]) -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-lfp/v1beta/tests/unit/gapic/merchant_lfp_v1beta/test_lfp_sale_service.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/tests/unit/gapic/merchant_lfp_v1beta/test_lfp_sale_service.py deleted file mode 100644 index 974dfbcc725f..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/tests/unit/gapic/merchant_lfp_v1beta/test_lfp_sale_service.py +++ /dev/null @@ -1,2077 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable, AsyncIterable -from google.protobuf import json_format -import json -import math -import pytest -from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -try: - from google.auth.aio import credentials as ga_credentials_async - HAS_GOOGLE_AUTH_AIO = True -except ImportError: # pragma: NO COVER - HAS_GOOGLE_AUTH_AIO = False - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.oauth2 import service_account -from google.protobuf import timestamp_pb2 # type: ignore -from google.shopping.merchant_lfp_v1beta.services.lfp_sale_service import LfpSaleServiceAsyncClient -from google.shopping.merchant_lfp_v1beta.services.lfp_sale_service import LfpSaleServiceClient -from google.shopping.merchant_lfp_v1beta.services.lfp_sale_service import transports -from google.shopping.merchant_lfp_v1beta.types import lfpsale -from google.shopping.type.types import types -import google.auth - - -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 LfpSaleServiceClient._get_default_mtls_endpoint(None) is None - assert LfpSaleServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert LfpSaleServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert LfpSaleServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert LfpSaleServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert LfpSaleServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert LfpSaleServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert LfpSaleServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert LfpSaleServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - LfpSaleServiceClient._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 LfpSaleServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert LfpSaleServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert LfpSaleServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - LfpSaleServiceClient._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 LfpSaleServiceClient._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 LfpSaleServiceClient._get_client_cert_source(None, False) is None - assert LfpSaleServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert LfpSaleServiceClient._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 LfpSaleServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert LfpSaleServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(LfpSaleServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpSaleServiceClient)) -@mock.patch.object(LfpSaleServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpSaleServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = LfpSaleServiceClient._DEFAULT_UNIVERSE - default_endpoint = LfpSaleServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = LfpSaleServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert LfpSaleServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert LfpSaleServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == LfpSaleServiceClient.DEFAULT_MTLS_ENDPOINT - assert LfpSaleServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert LfpSaleServiceClient._get_api_endpoint(None, None, default_universe, "always") == LfpSaleServiceClient.DEFAULT_MTLS_ENDPOINT - assert LfpSaleServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == LfpSaleServiceClient.DEFAULT_MTLS_ENDPOINT - assert LfpSaleServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert LfpSaleServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - LfpSaleServiceClient._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 LfpSaleServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert LfpSaleServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert LfpSaleServiceClient._get_universe_domain(None, None) == LfpSaleServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - LfpSaleServiceClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - - -@pytest.mark.parametrize("client_class,transport_name", [ - (LfpSaleServiceClient, "grpc"), - (LfpSaleServiceAsyncClient, "grpc_asyncio"), - (LfpSaleServiceClient, "rest"), -]) -def test_lfp_sale_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.LfpSaleServiceGrpcTransport, "grpc"), - (transports.LfpSaleServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.LfpSaleServiceRestTransport, "rest"), -]) -def test_lfp_sale_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", [ - (LfpSaleServiceClient, "grpc"), - (LfpSaleServiceAsyncClient, "grpc_asyncio"), - (LfpSaleServiceClient, "rest"), -]) -def test_lfp_sale_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_sale_service_client_get_transport_class(): - transport = LfpSaleServiceClient.get_transport_class() - available_transports = [ - transports.LfpSaleServiceGrpcTransport, - transports.LfpSaleServiceRestTransport, - ] - assert transport in available_transports - - transport = LfpSaleServiceClient.get_transport_class("grpc") - assert transport == transports.LfpSaleServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (LfpSaleServiceClient, transports.LfpSaleServiceGrpcTransport, "grpc"), - (LfpSaleServiceAsyncClient, transports.LfpSaleServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (LfpSaleServiceClient, transports.LfpSaleServiceRestTransport, "rest"), -]) -@mock.patch.object(LfpSaleServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpSaleServiceClient)) -@mock.patch.object(LfpSaleServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpSaleServiceAsyncClient)) -def test_lfp_sale_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(LfpSaleServiceClient, '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(LfpSaleServiceClient, '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", [ - (LfpSaleServiceClient, transports.LfpSaleServiceGrpcTransport, "grpc", "true"), - (LfpSaleServiceAsyncClient, transports.LfpSaleServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (LfpSaleServiceClient, transports.LfpSaleServiceGrpcTransport, "grpc", "false"), - (LfpSaleServiceAsyncClient, transports.LfpSaleServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (LfpSaleServiceClient, transports.LfpSaleServiceRestTransport, "rest", "true"), - (LfpSaleServiceClient, transports.LfpSaleServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(LfpSaleServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpSaleServiceClient)) -@mock.patch.object(LfpSaleServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpSaleServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_lfp_sale_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", [ - LfpSaleServiceClient, LfpSaleServiceAsyncClient -]) -@mock.patch.object(LfpSaleServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LfpSaleServiceClient)) -@mock.patch.object(LfpSaleServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LfpSaleServiceAsyncClient)) -def test_lfp_sale_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", [ - LfpSaleServiceClient, LfpSaleServiceAsyncClient -]) -@mock.patch.object(LfpSaleServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpSaleServiceClient)) -@mock.patch.object(LfpSaleServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpSaleServiceAsyncClient)) -def test_lfp_sale_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = LfpSaleServiceClient._DEFAULT_UNIVERSE - default_endpoint = LfpSaleServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = LfpSaleServiceClient._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", [ - (LfpSaleServiceClient, transports.LfpSaleServiceGrpcTransport, "grpc"), - (LfpSaleServiceAsyncClient, transports.LfpSaleServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (LfpSaleServiceClient, transports.LfpSaleServiceRestTransport, "rest"), -]) -def test_lfp_sale_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", [ - (LfpSaleServiceClient, transports.LfpSaleServiceGrpcTransport, "grpc", grpc_helpers), - (LfpSaleServiceAsyncClient, transports.LfpSaleServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (LfpSaleServiceClient, transports.LfpSaleServiceRestTransport, "rest", None), -]) -def test_lfp_sale_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_sale_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_lfp_v1beta.services.lfp_sale_service.transports.LfpSaleServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = LfpSaleServiceClient( - 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", [ - (LfpSaleServiceClient, transports.LfpSaleServiceGrpcTransport, "grpc", grpc_helpers), - (LfpSaleServiceAsyncClient, transports.LfpSaleServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_lfp_sale_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", [ - lfpsale.InsertLfpSaleRequest, - dict, -]) -def test_insert_lfp_sale(request_type, transport: str = 'grpc'): - client = LfpSaleServiceClient( - 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_lfp_sale), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = lfpsale.LfpSale( - name='name_value', - target_account=1491, - store_code='store_code_value', - offer_id='offer_id_value', - region_code='region_code_value', - content_language='content_language_value', - gtin='gtin_value', - quantity=895, - uid='uid_value', - feed_label='feed_label_value', - ) - response = client.insert_lfp_sale(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = lfpsale.InsertLfpSaleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, lfpsale.LfpSale) - assert response.name == 'name_value' - assert response.target_account == 1491 - assert response.store_code == 'store_code_value' - assert response.offer_id == 'offer_id_value' - assert response.region_code == 'region_code_value' - assert response.content_language == 'content_language_value' - assert response.gtin == 'gtin_value' - assert response.quantity == 895 - assert response.uid == 'uid_value' - assert response.feed_label == 'feed_label_value' - - -def test_insert_lfp_sale_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 = LfpSaleServiceClient( - 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 = lfpsale.InsertLfpSaleRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.insert_lfp_sale), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.insert_lfp_sale(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == lfpsale.InsertLfpSaleRequest( - parent='parent_value', - ) - -def test_insert_lfp_sale_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = LfpSaleServiceClient( - 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_lfp_sale in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_lfp_sale] = mock_rpc - request = {} - client.insert_lfp_sale(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.insert_lfp_sale(request) - - # Establish that a new wrapper 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_lfp_sale_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = LfpSaleServiceAsyncClient( - 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_lfp_sale in client._client._transport._wrapped_methods - - # 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_lfp_sale] = mock_rpc - - request = {} - await client.insert_lfp_sale(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.insert_lfp_sale(request) - - # Establish that a new wrapper 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_lfp_sale_async(transport: str = 'grpc_asyncio', request_type=lfpsale.InsertLfpSaleRequest): - client = LfpSaleServiceAsyncClient( - 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_lfp_sale), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(lfpsale.LfpSale( - name='name_value', - target_account=1491, - store_code='store_code_value', - offer_id='offer_id_value', - region_code='region_code_value', - content_language='content_language_value', - gtin='gtin_value', - quantity=895, - uid='uid_value', - feed_label='feed_label_value', - )) - response = await client.insert_lfp_sale(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = lfpsale.InsertLfpSaleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, lfpsale.LfpSale) - assert response.name == 'name_value' - assert response.target_account == 1491 - assert response.store_code == 'store_code_value' - assert response.offer_id == 'offer_id_value' - assert response.region_code == 'region_code_value' - assert response.content_language == 'content_language_value' - assert response.gtin == 'gtin_value' - assert response.quantity == 895 - assert response.uid == 'uid_value' - assert response.feed_label == 'feed_label_value' - - -@pytest.mark.asyncio -async def test_insert_lfp_sale_async_from_dict(): - await test_insert_lfp_sale_async(request_type=dict) - -def test_insert_lfp_sale_field_headers(): - client = LfpSaleServiceClient( - 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 = lfpsale.InsertLfpSaleRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.insert_lfp_sale), - '__call__') as call: - call.return_value = lfpsale.LfpSale() - client.insert_lfp_sale(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_lfp_sale_field_headers_async(): - client = LfpSaleServiceAsyncClient( - 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 = lfpsale.InsertLfpSaleRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.insert_lfp_sale), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpsale.LfpSale()) - await client.insert_lfp_sale(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_insert_lfp_sale_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 = LfpSaleServiceClient( - 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_lfp_sale in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_lfp_sale] = mock_rpc - - request = {} - client.insert_lfp_sale(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.insert_lfp_sale(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_lfp_sale_rest_required_fields(request_type=lfpsale.InsertLfpSaleRequest): - transport_class = transports.LfpSaleServiceRestTransport - - 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_lfp_sale._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_lfp_sale._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 = LfpSaleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = lfpsale.LfpSale() - # 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 = lfpsale.LfpSale.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_lfp_sale(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_insert_lfp_sale_rest_unset_required_fields(): - transport = transports.LfpSaleServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.insert_lfp_sale._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "lfpSale", ))) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.LfpSaleServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = LfpSaleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.LfpSaleServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = LfpSaleServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.LfpSaleServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = LfpSaleServiceClient( - 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 = LfpSaleServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.LfpSaleServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = LfpSaleServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.LfpSaleServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = LfpSaleServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.LfpSaleServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.LfpSaleServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.LfpSaleServiceGrpcTransport, - transports.LfpSaleServiceGrpcAsyncIOTransport, - transports.LfpSaleServiceRestTransport, -]) -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 = LfpSaleServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = LfpSaleServiceClient( - 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_insert_lfp_sale_empty_call_grpc(): - client = LfpSaleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.insert_lfp_sale), - '__call__') as call: - call.return_value = lfpsale.LfpSale() - client.insert_lfp_sale(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = lfpsale.InsertLfpSaleRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = LfpSaleServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = LfpSaleServiceAsyncClient( - 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_insert_lfp_sale_empty_call_grpc_asyncio(): - client = LfpSaleServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.insert_lfp_sale), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpsale.LfpSale( - name='name_value', - target_account=1491, - store_code='store_code_value', - offer_id='offer_id_value', - region_code='region_code_value', - content_language='content_language_value', - gtin='gtin_value', - quantity=895, - uid='uid_value', - feed_label='feed_label_value', - )) - await client.insert_lfp_sale(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = lfpsale.InsertLfpSaleRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = LfpSaleServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_insert_lfp_sale_rest_bad_request(request_type=lfpsale.InsertLfpSaleRequest): - client = LfpSaleServiceClient( - 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_lfp_sale(request) - - -@pytest.mark.parametrize("request_type", [ - lfpsale.InsertLfpSaleRequest, - dict, -]) -def test_insert_lfp_sale_rest_call_success(request_type): - client = LfpSaleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} - request_init["lfp_sale"] = {'name': 'name_value', 'target_account': 1491, 'store_code': 'store_code_value', 'offer_id': 'offer_id_value', 'region_code': 'region_code_value', 'content_language': 'content_language_value', 'gtin': 'gtin_value', 'price': {'amount_micros': 1408, 'currency_code': 'currency_code_value'}, 'quantity': 895, 'sale_time': {'seconds': 751, 'nanos': 543}, 'uid': 'uid_value', 'feed_label': 'feed_label_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 = lfpsale.InsertLfpSaleRequest.meta.fields["lfp_sale"] - - 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["lfp_sale"].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["lfp_sale"][field])): - del request_init["lfp_sale"][field][i][subfield] - else: - del request_init["lfp_sale"][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 = lfpsale.LfpSale( - name='name_value', - target_account=1491, - store_code='store_code_value', - offer_id='offer_id_value', - region_code='region_code_value', - content_language='content_language_value', - gtin='gtin_value', - quantity=895, - uid='uid_value', - feed_label='feed_label_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 = lfpsale.LfpSale.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_lfp_sale(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, lfpsale.LfpSale) - assert response.name == 'name_value' - assert response.target_account == 1491 - assert response.store_code == 'store_code_value' - assert response.offer_id == 'offer_id_value' - assert response.region_code == 'region_code_value' - assert response.content_language == 'content_language_value' - assert response.gtin == 'gtin_value' - assert response.quantity == 895 - assert response.uid == 'uid_value' - assert response.feed_label == 'feed_label_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_insert_lfp_sale_rest_interceptors(null_interceptor): - transport = transports.LfpSaleServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.LfpSaleServiceRestInterceptor(), - ) - client = LfpSaleServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.LfpSaleServiceRestInterceptor, "post_insert_lfp_sale") as post, \ - mock.patch.object(transports.LfpSaleServiceRestInterceptor, "pre_insert_lfp_sale") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = lfpsale.InsertLfpSaleRequest.pb(lfpsale.InsertLfpSaleRequest()) - 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 = lfpsale.LfpSale.to_json(lfpsale.LfpSale()) - req.return_value.content = return_value - - request = lfpsale.InsertLfpSaleRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = lfpsale.LfpSale() - - client.insert_lfp_sale(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - -def test_initialize_client_w_rest(): - client = LfpSaleServiceClient( - 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_insert_lfp_sale_empty_call_rest(): - client = LfpSaleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.insert_lfp_sale), - '__call__') as call: - client.insert_lfp_sale(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = lfpsale.InsertLfpSaleRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = LfpSaleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.LfpSaleServiceGrpcTransport, - ) - -def test_lfp_sale_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.LfpSaleServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_lfp_sale_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.shopping.merchant_lfp_v1beta.services.lfp_sale_service.transports.LfpSaleServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.LfpSaleServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'insert_lfp_sale', - ) - 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_sale_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_lfp_v1beta.services.lfp_sale_service.transports.LfpSaleServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.LfpSaleServiceTransport( - 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_sale_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_lfp_v1beta.services.lfp_sale_service.transports.LfpSaleServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.LfpSaleServiceTransport() - adc.assert_called_once() - - -def test_lfp_sale_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) - LfpSaleServiceClient() - 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.LfpSaleServiceGrpcTransport, - transports.LfpSaleServiceGrpcAsyncIOTransport, - ], -) -def test_lfp_sale_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.LfpSaleServiceGrpcTransport, - transports.LfpSaleServiceGrpcAsyncIOTransport, - transports.LfpSaleServiceRestTransport, - ], -) -def test_lfp_sale_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.LfpSaleServiceGrpcTransport, grpc_helpers), - (transports.LfpSaleServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_lfp_sale_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.LfpSaleServiceGrpcTransport, transports.LfpSaleServiceGrpcAsyncIOTransport]) -def test_lfp_sale_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_sale_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.LfpSaleServiceRestTransport ( - 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_sale_service_host_no_port(transport_name): - client = LfpSaleServiceClient( - 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_sale_service_host_with_port(transport_name): - client = LfpSaleServiceClient( - 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_sale_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = LfpSaleServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = LfpSaleServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.insert_lfp_sale._session - session2 = client2.transport.insert_lfp_sale._session - assert session1 != session2 -def test_lfp_sale_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.LfpSaleServiceGrpcTransport( - 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_sale_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.LfpSaleServiceGrpcAsyncIOTransport( - 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.LfpSaleServiceGrpcTransport, transports.LfpSaleServiceGrpcAsyncIOTransport]) -def test_lfp_sale_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.LfpSaleServiceGrpcTransport, transports.LfpSaleServiceGrpcAsyncIOTransport]) -def test_lfp_sale_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_sale_path(): - account = "squid" - sale = "clam" - expected = "accounts/{account}/lfpSales/{sale}".format(account=account, sale=sale, ) - actual = LfpSaleServiceClient.lfp_sale_path(account, sale) - assert expected == actual - - -def test_parse_lfp_sale_path(): - expected = { - "account": "whelk", - "sale": "octopus", - } - path = LfpSaleServiceClient.lfp_sale_path(**expected) - - # Check that the path construction is reversible. - actual = LfpSaleServiceClient.parse_lfp_sale_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = LfpSaleServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = LfpSaleServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = LfpSaleServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = LfpSaleServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = LfpSaleServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = LfpSaleServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = LfpSaleServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = LfpSaleServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = LfpSaleServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = LfpSaleServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = LfpSaleServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = LfpSaleServiceClient.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 = LfpSaleServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = LfpSaleServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = LfpSaleServiceClient.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.LfpSaleServiceTransport, '_prep_wrapped_messages') as prep: - client = LfpSaleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.LfpSaleServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = LfpSaleServiceClient.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 = LfpSaleServiceClient( - 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 = LfpSaleServiceAsyncClient( - 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 = LfpSaleServiceClient( - 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 = LfpSaleServiceClient( - 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", [ - (LfpSaleServiceClient, transports.LfpSaleServiceGrpcTransport), - (LfpSaleServiceAsyncClient, transports.LfpSaleServiceGrpcAsyncIOTransport), -]) -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-lfp/v1beta/tests/unit/gapic/merchant_lfp_v1beta/test_lfp_store_service.py b/owl-bot-staging/google-shopping-merchant-lfp/v1beta/tests/unit/gapic/merchant_lfp_v1beta/test_lfp_store_service.py deleted file mode 100644 index d5f55ed2da1e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/tests/unit/gapic/merchant_lfp_v1beta/test_lfp_store_service.py +++ /dev/null @@ -1,4514 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_lfp_v1beta.services.lfp_store_service import LfpStoreServiceAsyncClient -from google.shopping.merchant_lfp_v1beta.services.lfp_store_service import LfpStoreServiceClient -from google.shopping.merchant_lfp_v1beta.services.lfp_store_service import pagers -from google.shopping.merchant_lfp_v1beta.services.lfp_store_service import transports -from google.shopping.merchant_lfp_v1beta.types import lfpstore -import google.auth - - -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 LfpStoreServiceClient._get_default_mtls_endpoint(None) is None - assert LfpStoreServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert LfpStoreServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert LfpStoreServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert LfpStoreServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert LfpStoreServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert LfpStoreServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert LfpStoreServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert LfpStoreServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - LfpStoreServiceClient._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 LfpStoreServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert LfpStoreServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert LfpStoreServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - LfpStoreServiceClient._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 LfpStoreServiceClient._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 LfpStoreServiceClient._get_client_cert_source(None, False) is None - assert LfpStoreServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert LfpStoreServiceClient._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 LfpStoreServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert LfpStoreServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(LfpStoreServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpStoreServiceClient)) -@mock.patch.object(LfpStoreServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpStoreServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = LfpStoreServiceClient._DEFAULT_UNIVERSE - default_endpoint = LfpStoreServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = LfpStoreServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert LfpStoreServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert LfpStoreServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == LfpStoreServiceClient.DEFAULT_MTLS_ENDPOINT - assert LfpStoreServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert LfpStoreServiceClient._get_api_endpoint(None, None, default_universe, "always") == LfpStoreServiceClient.DEFAULT_MTLS_ENDPOINT - assert LfpStoreServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == LfpStoreServiceClient.DEFAULT_MTLS_ENDPOINT - assert LfpStoreServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert LfpStoreServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - LfpStoreServiceClient._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 LfpStoreServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert LfpStoreServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert LfpStoreServiceClient._get_universe_domain(None, None) == LfpStoreServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - LfpStoreServiceClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - - -@pytest.mark.parametrize("client_class,transport_name", [ - (LfpStoreServiceClient, "grpc"), - (LfpStoreServiceAsyncClient, "grpc_asyncio"), - (LfpStoreServiceClient, "rest"), -]) -def test_lfp_store_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.LfpStoreServiceGrpcTransport, "grpc"), - (transports.LfpStoreServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.LfpStoreServiceRestTransport, "rest"), -]) -def test_lfp_store_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", [ - (LfpStoreServiceClient, "grpc"), - (LfpStoreServiceAsyncClient, "grpc_asyncio"), - (LfpStoreServiceClient, "rest"), -]) -def test_lfp_store_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_store_service_client_get_transport_class(): - transport = LfpStoreServiceClient.get_transport_class() - available_transports = [ - transports.LfpStoreServiceGrpcTransport, - transports.LfpStoreServiceRestTransport, - ] - assert transport in available_transports - - transport = LfpStoreServiceClient.get_transport_class("grpc") - assert transport == transports.LfpStoreServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (LfpStoreServiceClient, transports.LfpStoreServiceGrpcTransport, "grpc"), - (LfpStoreServiceAsyncClient, transports.LfpStoreServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (LfpStoreServiceClient, transports.LfpStoreServiceRestTransport, "rest"), -]) -@mock.patch.object(LfpStoreServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpStoreServiceClient)) -@mock.patch.object(LfpStoreServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpStoreServiceAsyncClient)) -def test_lfp_store_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(LfpStoreServiceClient, '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(LfpStoreServiceClient, '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", [ - (LfpStoreServiceClient, transports.LfpStoreServiceGrpcTransport, "grpc", "true"), - (LfpStoreServiceAsyncClient, transports.LfpStoreServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (LfpStoreServiceClient, transports.LfpStoreServiceGrpcTransport, "grpc", "false"), - (LfpStoreServiceAsyncClient, transports.LfpStoreServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (LfpStoreServiceClient, transports.LfpStoreServiceRestTransport, "rest", "true"), - (LfpStoreServiceClient, transports.LfpStoreServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(LfpStoreServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpStoreServiceClient)) -@mock.patch.object(LfpStoreServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpStoreServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_lfp_store_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", [ - LfpStoreServiceClient, LfpStoreServiceAsyncClient -]) -@mock.patch.object(LfpStoreServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LfpStoreServiceClient)) -@mock.patch.object(LfpStoreServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LfpStoreServiceAsyncClient)) -def test_lfp_store_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", [ - LfpStoreServiceClient, LfpStoreServiceAsyncClient -]) -@mock.patch.object(LfpStoreServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpStoreServiceClient)) -@mock.patch.object(LfpStoreServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpStoreServiceAsyncClient)) -def test_lfp_store_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = LfpStoreServiceClient._DEFAULT_UNIVERSE - default_endpoint = LfpStoreServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = LfpStoreServiceClient._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", [ - (LfpStoreServiceClient, transports.LfpStoreServiceGrpcTransport, "grpc"), - (LfpStoreServiceAsyncClient, transports.LfpStoreServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (LfpStoreServiceClient, transports.LfpStoreServiceRestTransport, "rest"), -]) -def test_lfp_store_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", [ - (LfpStoreServiceClient, transports.LfpStoreServiceGrpcTransport, "grpc", grpc_helpers), - (LfpStoreServiceAsyncClient, transports.LfpStoreServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (LfpStoreServiceClient, transports.LfpStoreServiceRestTransport, "rest", None), -]) -def test_lfp_store_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_store_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_lfp_v1beta.services.lfp_store_service.transports.LfpStoreServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = LfpStoreServiceClient( - 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", [ - (LfpStoreServiceClient, transports.LfpStoreServiceGrpcTransport, "grpc", grpc_helpers), - (LfpStoreServiceAsyncClient, transports.LfpStoreServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_lfp_store_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", [ - lfpstore.GetLfpStoreRequest, - dict, -]) -def test_get_lfp_store(request_type, transport: str = 'grpc'): - client = LfpStoreServiceClient( - 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_lfp_store), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = lfpstore.LfpStore( - name='name_value', - target_account=1491, - store_code='store_code_value', - store_address='store_address_value', - store_name='store_name_value', - phone_number='phone_number_value', - website_uri='website_uri_value', - gcid_category=['gcid_category_value'], - place_id='place_id_value', - matching_state=lfpstore.LfpStore.StoreMatchingState.STORE_MATCHING_STATE_MATCHED, - matching_state_hint='matching_state_hint_value', - ) - response = client.get_lfp_store(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = lfpstore.GetLfpStoreRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, lfpstore.LfpStore) - assert response.name == 'name_value' - assert response.target_account == 1491 - assert response.store_code == 'store_code_value' - assert response.store_address == 'store_address_value' - assert response.store_name == 'store_name_value' - assert response.phone_number == 'phone_number_value' - assert response.website_uri == 'website_uri_value' - assert response.gcid_category == ['gcid_category_value'] - assert response.place_id == 'place_id_value' - assert response.matching_state == lfpstore.LfpStore.StoreMatchingState.STORE_MATCHING_STATE_MATCHED - assert response.matching_state_hint == 'matching_state_hint_value' - - -def test_get_lfp_store_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 = LfpStoreServiceClient( - 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 = lfpstore.GetLfpStoreRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_lfp_store), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_lfp_store(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == lfpstore.GetLfpStoreRequest( - name='name_value', - ) - -def test_get_lfp_store_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = LfpStoreServiceClient( - 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_lfp_store in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_lfp_store] = mock_rpc - request = {} - client.get_lfp_store(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_lfp_store(request) - - # Establish that a new wrapper 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_lfp_store_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = LfpStoreServiceAsyncClient( - 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_lfp_store in client._client._transport._wrapped_methods - - # 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_lfp_store] = mock_rpc - - request = {} - await client.get_lfp_store(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_lfp_store(request) - - # Establish that a new wrapper 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_lfp_store_async(transport: str = 'grpc_asyncio', request_type=lfpstore.GetLfpStoreRequest): - client = LfpStoreServiceAsyncClient( - 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_lfp_store), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(lfpstore.LfpStore( - name='name_value', - target_account=1491, - store_code='store_code_value', - store_address='store_address_value', - store_name='store_name_value', - phone_number='phone_number_value', - website_uri='website_uri_value', - gcid_category=['gcid_category_value'], - place_id='place_id_value', - matching_state=lfpstore.LfpStore.StoreMatchingState.STORE_MATCHING_STATE_MATCHED, - matching_state_hint='matching_state_hint_value', - )) - response = await client.get_lfp_store(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = lfpstore.GetLfpStoreRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, lfpstore.LfpStore) - assert response.name == 'name_value' - assert response.target_account == 1491 - assert response.store_code == 'store_code_value' - assert response.store_address == 'store_address_value' - assert response.store_name == 'store_name_value' - assert response.phone_number == 'phone_number_value' - assert response.website_uri == 'website_uri_value' - assert response.gcid_category == ['gcid_category_value'] - assert response.place_id == 'place_id_value' - assert response.matching_state == lfpstore.LfpStore.StoreMatchingState.STORE_MATCHING_STATE_MATCHED - assert response.matching_state_hint == 'matching_state_hint_value' - - -@pytest.mark.asyncio -async def test_get_lfp_store_async_from_dict(): - await test_get_lfp_store_async(request_type=dict) - -def test_get_lfp_store_field_headers(): - client = LfpStoreServiceClient( - 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 = lfpstore.GetLfpStoreRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_lfp_store), - '__call__') as call: - call.return_value = lfpstore.LfpStore() - client.get_lfp_store(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_lfp_store_field_headers_async(): - client = LfpStoreServiceAsyncClient( - 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 = lfpstore.GetLfpStoreRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_lfp_store), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpstore.LfpStore()) - await client.get_lfp_store(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_lfp_store_flattened(): - client = LfpStoreServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_lfp_store), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = lfpstore.LfpStore() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_lfp_store( - 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_lfp_store_flattened_error(): - client = LfpStoreServiceClient( - 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_lfp_store( - lfpstore.GetLfpStoreRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_lfp_store_flattened_async(): - client = LfpStoreServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_lfp_store), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = lfpstore.LfpStore() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpstore.LfpStore()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_lfp_store( - 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_lfp_store_flattened_error_async(): - client = LfpStoreServiceAsyncClient( - 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_lfp_store( - lfpstore.GetLfpStoreRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - lfpstore.InsertLfpStoreRequest, - dict, -]) -def test_insert_lfp_store(request_type, transport: str = 'grpc'): - client = LfpStoreServiceClient( - 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_lfp_store), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = lfpstore.LfpStore( - name='name_value', - target_account=1491, - store_code='store_code_value', - store_address='store_address_value', - store_name='store_name_value', - phone_number='phone_number_value', - website_uri='website_uri_value', - gcid_category=['gcid_category_value'], - place_id='place_id_value', - matching_state=lfpstore.LfpStore.StoreMatchingState.STORE_MATCHING_STATE_MATCHED, - matching_state_hint='matching_state_hint_value', - ) - response = client.insert_lfp_store(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = lfpstore.InsertLfpStoreRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, lfpstore.LfpStore) - assert response.name == 'name_value' - assert response.target_account == 1491 - assert response.store_code == 'store_code_value' - assert response.store_address == 'store_address_value' - assert response.store_name == 'store_name_value' - assert response.phone_number == 'phone_number_value' - assert response.website_uri == 'website_uri_value' - assert response.gcid_category == ['gcid_category_value'] - assert response.place_id == 'place_id_value' - assert response.matching_state == lfpstore.LfpStore.StoreMatchingState.STORE_MATCHING_STATE_MATCHED - assert response.matching_state_hint == 'matching_state_hint_value' - - -def test_insert_lfp_store_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 = LfpStoreServiceClient( - 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 = lfpstore.InsertLfpStoreRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.insert_lfp_store), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.insert_lfp_store(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == lfpstore.InsertLfpStoreRequest( - parent='parent_value', - ) - -def test_insert_lfp_store_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = LfpStoreServiceClient( - 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_lfp_store in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_lfp_store] = mock_rpc - request = {} - client.insert_lfp_store(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.insert_lfp_store(request) - - # Establish that a new wrapper 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_lfp_store_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = LfpStoreServiceAsyncClient( - 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_lfp_store in client._client._transport._wrapped_methods - - # 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_lfp_store] = mock_rpc - - request = {} - await client.insert_lfp_store(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.insert_lfp_store(request) - - # Establish that a new wrapper 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_lfp_store_async(transport: str = 'grpc_asyncio', request_type=lfpstore.InsertLfpStoreRequest): - client = LfpStoreServiceAsyncClient( - 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_lfp_store), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(lfpstore.LfpStore( - name='name_value', - target_account=1491, - store_code='store_code_value', - store_address='store_address_value', - store_name='store_name_value', - phone_number='phone_number_value', - website_uri='website_uri_value', - gcid_category=['gcid_category_value'], - place_id='place_id_value', - matching_state=lfpstore.LfpStore.StoreMatchingState.STORE_MATCHING_STATE_MATCHED, - matching_state_hint='matching_state_hint_value', - )) - response = await client.insert_lfp_store(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = lfpstore.InsertLfpStoreRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, lfpstore.LfpStore) - assert response.name == 'name_value' - assert response.target_account == 1491 - assert response.store_code == 'store_code_value' - assert response.store_address == 'store_address_value' - assert response.store_name == 'store_name_value' - assert response.phone_number == 'phone_number_value' - assert response.website_uri == 'website_uri_value' - assert response.gcid_category == ['gcid_category_value'] - assert response.place_id == 'place_id_value' - assert response.matching_state == lfpstore.LfpStore.StoreMatchingState.STORE_MATCHING_STATE_MATCHED - assert response.matching_state_hint == 'matching_state_hint_value' - - -@pytest.mark.asyncio -async def test_insert_lfp_store_async_from_dict(): - await test_insert_lfp_store_async(request_type=dict) - -def test_insert_lfp_store_field_headers(): - client = LfpStoreServiceClient( - 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 = lfpstore.InsertLfpStoreRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.insert_lfp_store), - '__call__') as call: - call.return_value = lfpstore.LfpStore() - client.insert_lfp_store(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_lfp_store_field_headers_async(): - client = LfpStoreServiceAsyncClient( - 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 = lfpstore.InsertLfpStoreRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.insert_lfp_store), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpstore.LfpStore()) - await client.insert_lfp_store(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_insert_lfp_store_flattened(): - client = LfpStoreServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.insert_lfp_store), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = lfpstore.LfpStore() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.insert_lfp_store( - parent='parent_value', - lfp_store=lfpstore.LfpStore(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].lfp_store - mock_val = lfpstore.LfpStore(name='name_value') - assert arg == mock_val - - -def test_insert_lfp_store_flattened_error(): - client = LfpStoreServiceClient( - 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.insert_lfp_store( - lfpstore.InsertLfpStoreRequest(), - parent='parent_value', - lfp_store=lfpstore.LfpStore(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_insert_lfp_store_flattened_async(): - client = LfpStoreServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.insert_lfp_store), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = lfpstore.LfpStore() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpstore.LfpStore()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.insert_lfp_store( - parent='parent_value', - lfp_store=lfpstore.LfpStore(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].lfp_store - mock_val = lfpstore.LfpStore(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_insert_lfp_store_flattened_error_async(): - client = LfpStoreServiceAsyncClient( - 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.insert_lfp_store( - lfpstore.InsertLfpStoreRequest(), - parent='parent_value', - lfp_store=lfpstore.LfpStore(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - lfpstore.DeleteLfpStoreRequest, - dict, -]) -def test_delete_lfp_store(request_type, transport: str = 'grpc'): - client = LfpStoreServiceClient( - 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_lfp_store), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_lfp_store(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = lfpstore.DeleteLfpStoreRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_lfp_store_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 = LfpStoreServiceClient( - 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 = lfpstore.DeleteLfpStoreRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_lfp_store), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_lfp_store(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == lfpstore.DeleteLfpStoreRequest( - name='name_value', - ) - -def test_delete_lfp_store_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = LfpStoreServiceClient( - 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_lfp_store in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_lfp_store] = mock_rpc - request = {} - client.delete_lfp_store(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_lfp_store(request) - - # Establish that a new wrapper 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_lfp_store_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = LfpStoreServiceAsyncClient( - 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_lfp_store in client._client._transport._wrapped_methods - - # 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_lfp_store] = mock_rpc - - request = {} - await client.delete_lfp_store(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.delete_lfp_store(request) - - # Establish that a new wrapper 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_lfp_store_async(transport: str = 'grpc_asyncio', request_type=lfpstore.DeleteLfpStoreRequest): - client = LfpStoreServiceAsyncClient( - 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_lfp_store), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_lfp_store(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = lfpstore.DeleteLfpStoreRequest() - 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_lfp_store_async_from_dict(): - await test_delete_lfp_store_async(request_type=dict) - -def test_delete_lfp_store_field_headers(): - client = LfpStoreServiceClient( - 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 = lfpstore.DeleteLfpStoreRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_lfp_store), - '__call__') as call: - call.return_value = None - client.delete_lfp_store(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_lfp_store_field_headers_async(): - client = LfpStoreServiceAsyncClient( - 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 = lfpstore.DeleteLfpStoreRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_lfp_store), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_lfp_store(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_lfp_store_flattened(): - client = LfpStoreServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_lfp_store), - '__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_lfp_store( - 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_lfp_store_flattened_error(): - client = LfpStoreServiceClient( - 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_lfp_store( - lfpstore.DeleteLfpStoreRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_lfp_store_flattened_async(): - client = LfpStoreServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_lfp_store), - '__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_lfp_store( - 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_lfp_store_flattened_error_async(): - client = LfpStoreServiceAsyncClient( - 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_lfp_store( - lfpstore.DeleteLfpStoreRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - lfpstore.ListLfpStoresRequest, - dict, -]) -def test_list_lfp_stores(request_type, transport: str = 'grpc'): - client = LfpStoreServiceClient( - 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_lfp_stores), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = lfpstore.ListLfpStoresResponse( - next_page_token='next_page_token_value', - ) - response = client.list_lfp_stores(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = lfpstore.ListLfpStoresRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListLfpStoresPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_lfp_stores_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 = LfpStoreServiceClient( - 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 = lfpstore.ListLfpStoresRequest( - 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_lfp_stores), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_lfp_stores(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == lfpstore.ListLfpStoresRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_lfp_stores_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = LfpStoreServiceClient( - 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_lfp_stores in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_lfp_stores] = mock_rpc - request = {} - client.list_lfp_stores(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_lfp_stores(request) - - # Establish that a new wrapper 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_lfp_stores_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = LfpStoreServiceAsyncClient( - 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_lfp_stores in client._client._transport._wrapped_methods - - # 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_lfp_stores] = mock_rpc - - request = {} - await client.list_lfp_stores(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_lfp_stores(request) - - # Establish that a new wrapper 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_lfp_stores_async(transport: str = 'grpc_asyncio', request_type=lfpstore.ListLfpStoresRequest): - client = LfpStoreServiceAsyncClient( - 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_lfp_stores), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(lfpstore.ListLfpStoresResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_lfp_stores(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = lfpstore.ListLfpStoresRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListLfpStoresAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_lfp_stores_async_from_dict(): - await test_list_lfp_stores_async(request_type=dict) - -def test_list_lfp_stores_field_headers(): - client = LfpStoreServiceClient( - 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 = lfpstore.ListLfpStoresRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_lfp_stores), - '__call__') as call: - call.return_value = lfpstore.ListLfpStoresResponse() - client.list_lfp_stores(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_lfp_stores_field_headers_async(): - client = LfpStoreServiceAsyncClient( - 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 = lfpstore.ListLfpStoresRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_lfp_stores), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpstore.ListLfpStoresResponse()) - await client.list_lfp_stores(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_lfp_stores_flattened(): - client = LfpStoreServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_lfp_stores), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = lfpstore.ListLfpStoresResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_lfp_stores( - 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_lfp_stores_flattened_error(): - client = LfpStoreServiceClient( - 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_lfp_stores( - lfpstore.ListLfpStoresRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_lfp_stores_flattened_async(): - client = LfpStoreServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_lfp_stores), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = lfpstore.ListLfpStoresResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpstore.ListLfpStoresResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_lfp_stores( - 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_lfp_stores_flattened_error_async(): - client = LfpStoreServiceAsyncClient( - 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_lfp_stores( - lfpstore.ListLfpStoresRequest(), - parent='parent_value', - ) - - -def test_list_lfp_stores_pager(transport_name: str = "grpc"): - client = LfpStoreServiceClient( - 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_lfp_stores), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - lfpstore.ListLfpStoresResponse( - lfp_stores=[ - lfpstore.LfpStore(), - lfpstore.LfpStore(), - lfpstore.LfpStore(), - ], - next_page_token='abc', - ), - lfpstore.ListLfpStoresResponse( - lfp_stores=[], - next_page_token='def', - ), - lfpstore.ListLfpStoresResponse( - lfp_stores=[ - lfpstore.LfpStore(), - ], - next_page_token='ghi', - ), - lfpstore.ListLfpStoresResponse( - lfp_stores=[ - lfpstore.LfpStore(), - lfpstore.LfpStore(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_lfp_stores(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, lfpstore.LfpStore) - for i in results) -def test_list_lfp_stores_pages(transport_name: str = "grpc"): - client = LfpStoreServiceClient( - 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_lfp_stores), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - lfpstore.ListLfpStoresResponse( - lfp_stores=[ - lfpstore.LfpStore(), - lfpstore.LfpStore(), - lfpstore.LfpStore(), - ], - next_page_token='abc', - ), - lfpstore.ListLfpStoresResponse( - lfp_stores=[], - next_page_token='def', - ), - lfpstore.ListLfpStoresResponse( - lfp_stores=[ - lfpstore.LfpStore(), - ], - next_page_token='ghi', - ), - lfpstore.ListLfpStoresResponse( - lfp_stores=[ - lfpstore.LfpStore(), - lfpstore.LfpStore(), - ], - ), - RuntimeError, - ) - pages = list(client.list_lfp_stores(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_lfp_stores_async_pager(): - client = LfpStoreServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_lfp_stores), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - lfpstore.ListLfpStoresResponse( - lfp_stores=[ - lfpstore.LfpStore(), - lfpstore.LfpStore(), - lfpstore.LfpStore(), - ], - next_page_token='abc', - ), - lfpstore.ListLfpStoresResponse( - lfp_stores=[], - next_page_token='def', - ), - lfpstore.ListLfpStoresResponse( - lfp_stores=[ - lfpstore.LfpStore(), - ], - next_page_token='ghi', - ), - lfpstore.ListLfpStoresResponse( - lfp_stores=[ - lfpstore.LfpStore(), - lfpstore.LfpStore(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_lfp_stores(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, lfpstore.LfpStore) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_lfp_stores_async_pages(): - client = LfpStoreServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_lfp_stores), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - lfpstore.ListLfpStoresResponse( - lfp_stores=[ - lfpstore.LfpStore(), - lfpstore.LfpStore(), - lfpstore.LfpStore(), - ], - next_page_token='abc', - ), - lfpstore.ListLfpStoresResponse( - lfp_stores=[], - next_page_token='def', - ), - lfpstore.ListLfpStoresResponse( - lfp_stores=[ - lfpstore.LfpStore(), - ], - next_page_token='ghi', - ), - lfpstore.ListLfpStoresResponse( - lfp_stores=[ - lfpstore.LfpStore(), - lfpstore.LfpStore(), - ], - ), - 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_lfp_stores(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_lfp_store_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 = LfpStoreServiceClient( - 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_lfp_store in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_lfp_store] = mock_rpc - - request = {} - client.get_lfp_store(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_lfp_store(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_lfp_store_rest_required_fields(request_type=lfpstore.GetLfpStoreRequest): - transport_class = transports.LfpStoreServiceRestTransport - - 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_lfp_store._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_lfp_store._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 = LfpStoreServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = lfpstore.LfpStore() - # 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 = lfpstore.LfpStore.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_lfp_store(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_lfp_store_rest_unset_required_fields(): - transport = transports.LfpStoreServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_lfp_store._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_lfp_store_rest_flattened(): - client = LfpStoreServiceClient( - 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 = lfpstore.LfpStore() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/lfpStores/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 = lfpstore.LfpStore.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_lfp_store(**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/lfp/v1beta/{name=accounts/*/lfpStores/*}" % client.transport._host, args[1]) - - -def test_get_lfp_store_rest_flattened_error(transport: str = 'rest'): - client = LfpStoreServiceClient( - 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_lfp_store( - lfpstore.GetLfpStoreRequest(), - name='name_value', - ) - - -def test_insert_lfp_store_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 = LfpStoreServiceClient( - 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_lfp_store in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_lfp_store] = mock_rpc - - request = {} - client.insert_lfp_store(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.insert_lfp_store(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_lfp_store_rest_required_fields(request_type=lfpstore.InsertLfpStoreRequest): - transport_class = transports.LfpStoreServiceRestTransport - - 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_lfp_store._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_lfp_store._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 = LfpStoreServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = lfpstore.LfpStore() - # 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 = lfpstore.LfpStore.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_lfp_store(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_insert_lfp_store_rest_unset_required_fields(): - transport = transports.LfpStoreServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.insert_lfp_store._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "lfpStore", ))) - - -def test_insert_lfp_store_rest_flattened(): - client = LfpStoreServiceClient( - 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 = lfpstore.LfpStore() - - # 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', - lfp_store=lfpstore.LfpStore(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 = lfpstore.LfpStore.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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.insert_lfp_store(**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/lfp/v1beta/{parent=accounts/*}/lfpStores:insert" % client.transport._host, args[1]) - - -def test_insert_lfp_store_rest_flattened_error(transport: str = 'rest'): - client = LfpStoreServiceClient( - 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.insert_lfp_store( - lfpstore.InsertLfpStoreRequest(), - parent='parent_value', - lfp_store=lfpstore.LfpStore(name='name_value'), - ) - - -def test_delete_lfp_store_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 = LfpStoreServiceClient( - 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_lfp_store in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_lfp_store] = mock_rpc - - request = {} - client.delete_lfp_store(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_lfp_store(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_lfp_store_rest_required_fields(request_type=lfpstore.DeleteLfpStoreRequest): - transport_class = transports.LfpStoreServiceRestTransport - - 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_lfp_store._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_lfp_store._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 = LfpStoreServiceClient( - 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_lfp_store(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_lfp_store_rest_unset_required_fields(): - transport = transports.LfpStoreServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_lfp_store._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_delete_lfp_store_rest_flattened(): - client = LfpStoreServiceClient( - 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/lfpStores/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_lfp_store(**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/lfp/v1beta/{name=accounts/*/lfpStores/*}" % client.transport._host, args[1]) - - -def test_delete_lfp_store_rest_flattened_error(transport: str = 'rest'): - client = LfpStoreServiceClient( - 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_lfp_store( - lfpstore.DeleteLfpStoreRequest(), - name='name_value', - ) - - -def test_list_lfp_stores_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 = LfpStoreServiceClient( - 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_lfp_stores in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_lfp_stores] = mock_rpc - - request = {} - client.list_lfp_stores(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_lfp_stores(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_lfp_stores_rest_required_fields(request_type=lfpstore.ListLfpStoresRequest): - transport_class = transports.LfpStoreServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["target_account"] = 0 - request = 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 "targetAccount" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_lfp_stores._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "targetAccount" in jsonified_request - assert jsonified_request["targetAccount"] == request_init["target_account"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["targetAccount"] = 1491 - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_lfp_stores._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", "target_account", )) - 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 "targetAccount" in jsonified_request - assert jsonified_request["targetAccount"] == 1491 - - client = LfpStoreServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = lfpstore.ListLfpStoresResponse() - # 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 = lfpstore.ListLfpStoresResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_lfp_stores(request) - - expected_params = [ - ( - "targetAccount", - str(0), - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_lfp_stores_rest_unset_required_fields(): - transport = transports.LfpStoreServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_lfp_stores._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", "targetAccount", )) & set(("parent", "targetAccount", ))) - - -def test_list_lfp_stores_rest_flattened(): - client = LfpStoreServiceClient( - 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 = lfpstore.ListLfpStoresResponse() - - # 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 = lfpstore.ListLfpStoresResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_lfp_stores(**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/lfp/v1beta/{parent=accounts/*}/lfpStores" % client.transport._host, args[1]) - - -def test_list_lfp_stores_rest_flattened_error(transport: str = 'rest'): - client = LfpStoreServiceClient( - 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_lfp_stores( - lfpstore.ListLfpStoresRequest(), - parent='parent_value', - ) - - -def test_list_lfp_stores_rest_pager(transport: str = 'rest'): - client = LfpStoreServiceClient( - 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 = ( - lfpstore.ListLfpStoresResponse( - lfp_stores=[ - lfpstore.LfpStore(), - lfpstore.LfpStore(), - lfpstore.LfpStore(), - ], - next_page_token='abc', - ), - lfpstore.ListLfpStoresResponse( - lfp_stores=[], - next_page_token='def', - ), - lfpstore.ListLfpStoresResponse( - lfp_stores=[ - lfpstore.LfpStore(), - ], - next_page_token='ghi', - ), - lfpstore.ListLfpStoresResponse( - lfp_stores=[ - lfpstore.LfpStore(), - lfpstore.LfpStore(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(lfpstore.ListLfpStoresResponse.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_lfp_stores(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, lfpstore.LfpStore) - for i in results) - - pages = list(client.list_lfp_stores(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.LfpStoreServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = LfpStoreServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.LfpStoreServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = LfpStoreServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.LfpStoreServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = LfpStoreServiceClient( - 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 = LfpStoreServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.LfpStoreServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = LfpStoreServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.LfpStoreServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = LfpStoreServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.LfpStoreServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.LfpStoreServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.LfpStoreServiceGrpcTransport, - transports.LfpStoreServiceGrpcAsyncIOTransport, - transports.LfpStoreServiceRestTransport, -]) -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 = LfpStoreServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = LfpStoreServiceClient( - 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_lfp_store_empty_call_grpc(): - client = LfpStoreServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_lfp_store), - '__call__') as call: - call.return_value = lfpstore.LfpStore() - client.get_lfp_store(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = lfpstore.GetLfpStoreRequest() - - assert args[0] == request_msg - - -# This 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_lfp_store_empty_call_grpc(): - client = LfpStoreServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.insert_lfp_store), - '__call__') as call: - call.return_value = lfpstore.LfpStore() - client.insert_lfp_store(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = lfpstore.InsertLfpStoreRequest() - - assert args[0] == request_msg - - -# This 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_lfp_store_empty_call_grpc(): - client = LfpStoreServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_lfp_store), - '__call__') as call: - call.return_value = None - client.delete_lfp_store(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = lfpstore.DeleteLfpStoreRequest() - - assert args[0] == request_msg - - -# This 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_lfp_stores_empty_call_grpc(): - client = LfpStoreServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_lfp_stores), - '__call__') as call: - call.return_value = lfpstore.ListLfpStoresResponse() - client.list_lfp_stores(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = lfpstore.ListLfpStoresRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = LfpStoreServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = LfpStoreServiceAsyncClient( - 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_lfp_store_empty_call_grpc_asyncio(): - client = LfpStoreServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_lfp_store), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpstore.LfpStore( - name='name_value', - target_account=1491, - store_code='store_code_value', - store_address='store_address_value', - store_name='store_name_value', - phone_number='phone_number_value', - website_uri='website_uri_value', - gcid_category=['gcid_category_value'], - place_id='place_id_value', - matching_state=lfpstore.LfpStore.StoreMatchingState.STORE_MATCHING_STATE_MATCHED, - matching_state_hint='matching_state_hint_value', - )) - await client.get_lfp_store(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = lfpstore.GetLfpStoreRequest() - - assert args[0] == request_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_lfp_store_empty_call_grpc_asyncio(): - client = LfpStoreServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.insert_lfp_store), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpstore.LfpStore( - name='name_value', - target_account=1491, - store_code='store_code_value', - store_address='store_address_value', - store_name='store_name_value', - phone_number='phone_number_value', - website_uri='website_uri_value', - gcid_category=['gcid_category_value'], - place_id='place_id_value', - matching_state=lfpstore.LfpStore.StoreMatchingState.STORE_MATCHING_STATE_MATCHED, - matching_state_hint='matching_state_hint_value', - )) - await client.insert_lfp_store(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = lfpstore.InsertLfpStoreRequest() - - assert args[0] == request_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_lfp_store_empty_call_grpc_asyncio(): - client = LfpStoreServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_lfp_store), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_lfp_store(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = lfpstore.DeleteLfpStoreRequest() - - assert args[0] == request_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_lfp_stores_empty_call_grpc_asyncio(): - client = LfpStoreServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_lfp_stores), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpstore.ListLfpStoresResponse( - next_page_token='next_page_token_value', - )) - await client.list_lfp_stores(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = lfpstore.ListLfpStoresRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = LfpStoreServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_get_lfp_store_rest_bad_request(request_type=lfpstore.GetLfpStoreRequest): - client = LfpStoreServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/lfpStores/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_lfp_store(request) - - -@pytest.mark.parametrize("request_type", [ - lfpstore.GetLfpStoreRequest, - dict, -]) -def test_get_lfp_store_rest_call_success(request_type): - client = LfpStoreServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/lfpStores/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 = lfpstore.LfpStore( - name='name_value', - target_account=1491, - store_code='store_code_value', - store_address='store_address_value', - store_name='store_name_value', - phone_number='phone_number_value', - website_uri='website_uri_value', - gcid_category=['gcid_category_value'], - place_id='place_id_value', - matching_state=lfpstore.LfpStore.StoreMatchingState.STORE_MATCHING_STATE_MATCHED, - matching_state_hint='matching_state_hint_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 = lfpstore.LfpStore.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_lfp_store(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, lfpstore.LfpStore) - assert response.name == 'name_value' - assert response.target_account == 1491 - assert response.store_code == 'store_code_value' - assert response.store_address == 'store_address_value' - assert response.store_name == 'store_name_value' - assert response.phone_number == 'phone_number_value' - assert response.website_uri == 'website_uri_value' - assert response.gcid_category == ['gcid_category_value'] - assert response.place_id == 'place_id_value' - assert response.matching_state == lfpstore.LfpStore.StoreMatchingState.STORE_MATCHING_STATE_MATCHED - assert response.matching_state_hint == 'matching_state_hint_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_lfp_store_rest_interceptors(null_interceptor): - transport = transports.LfpStoreServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.LfpStoreServiceRestInterceptor(), - ) - client = LfpStoreServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.LfpStoreServiceRestInterceptor, "post_get_lfp_store") as post, \ - mock.patch.object(transports.LfpStoreServiceRestInterceptor, "pre_get_lfp_store") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = lfpstore.GetLfpStoreRequest.pb(lfpstore.GetLfpStoreRequest()) - 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 = lfpstore.LfpStore.to_json(lfpstore.LfpStore()) - req.return_value.content = return_value - - request = lfpstore.GetLfpStoreRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = lfpstore.LfpStore() - - client.get_lfp_store(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_insert_lfp_store_rest_bad_request(request_type=lfpstore.InsertLfpStoreRequest): - client = LfpStoreServiceClient( - 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_lfp_store(request) - - -@pytest.mark.parametrize("request_type", [ - lfpstore.InsertLfpStoreRequest, - dict, -]) -def test_insert_lfp_store_rest_call_success(request_type): - client = LfpStoreServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} - request_init["lfp_store"] = {'name': 'name_value', 'target_account': 1491, 'store_code': 'store_code_value', 'store_address': 'store_address_value', 'store_name': 'store_name_value', 'phone_number': 'phone_number_value', 'website_uri': 'website_uri_value', 'gcid_category': ['gcid_category_value1', 'gcid_category_value2'], 'place_id': 'place_id_value', 'matching_state': 1, 'matching_state_hint': 'matching_state_hint_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 = lfpstore.InsertLfpStoreRequest.meta.fields["lfp_store"] - - 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["lfp_store"].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["lfp_store"][field])): - del request_init["lfp_store"][field][i][subfield] - else: - del request_init["lfp_store"][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 = lfpstore.LfpStore( - name='name_value', - target_account=1491, - store_code='store_code_value', - store_address='store_address_value', - store_name='store_name_value', - phone_number='phone_number_value', - website_uri='website_uri_value', - gcid_category=['gcid_category_value'], - place_id='place_id_value', - matching_state=lfpstore.LfpStore.StoreMatchingState.STORE_MATCHING_STATE_MATCHED, - matching_state_hint='matching_state_hint_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 = lfpstore.LfpStore.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_lfp_store(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, lfpstore.LfpStore) - assert response.name == 'name_value' - assert response.target_account == 1491 - assert response.store_code == 'store_code_value' - assert response.store_address == 'store_address_value' - assert response.store_name == 'store_name_value' - assert response.phone_number == 'phone_number_value' - assert response.website_uri == 'website_uri_value' - assert response.gcid_category == ['gcid_category_value'] - assert response.place_id == 'place_id_value' - assert response.matching_state == lfpstore.LfpStore.StoreMatchingState.STORE_MATCHING_STATE_MATCHED - assert response.matching_state_hint == 'matching_state_hint_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_insert_lfp_store_rest_interceptors(null_interceptor): - transport = transports.LfpStoreServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.LfpStoreServiceRestInterceptor(), - ) - client = LfpStoreServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.LfpStoreServiceRestInterceptor, "post_insert_lfp_store") as post, \ - mock.patch.object(transports.LfpStoreServiceRestInterceptor, "pre_insert_lfp_store") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = lfpstore.InsertLfpStoreRequest.pb(lfpstore.InsertLfpStoreRequest()) - 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 = lfpstore.LfpStore.to_json(lfpstore.LfpStore()) - req.return_value.content = return_value - - request = lfpstore.InsertLfpStoreRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = lfpstore.LfpStore() - - client.insert_lfp_store(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_lfp_store_rest_bad_request(request_type=lfpstore.DeleteLfpStoreRequest): - client = LfpStoreServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/lfpStores/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_lfp_store(request) - - -@pytest.mark.parametrize("request_type", [ - lfpstore.DeleteLfpStoreRequest, - dict, -]) -def test_delete_lfp_store_rest_call_success(request_type): - client = LfpStoreServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/lfpStores/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_lfp_store(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_lfp_store_rest_interceptors(null_interceptor): - transport = transports.LfpStoreServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.LfpStoreServiceRestInterceptor(), - ) - client = LfpStoreServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.LfpStoreServiceRestInterceptor, "pre_delete_lfp_store") as pre: - pre.assert_not_called() - pb_message = lfpstore.DeleteLfpStoreRequest.pb(lfpstore.DeleteLfpStoreRequest()) - 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 = lfpstore.DeleteLfpStoreRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_lfp_store(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_list_lfp_stores_rest_bad_request(request_type=lfpstore.ListLfpStoresRequest): - client = LfpStoreServiceClient( - 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_lfp_stores(request) - - -@pytest.mark.parametrize("request_type", [ - lfpstore.ListLfpStoresRequest, - dict, -]) -def test_list_lfp_stores_rest_call_success(request_type): - client = LfpStoreServiceClient( - 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 = lfpstore.ListLfpStoresResponse( - 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 = lfpstore.ListLfpStoresResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_lfp_stores(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListLfpStoresPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_lfp_stores_rest_interceptors(null_interceptor): - transport = transports.LfpStoreServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.LfpStoreServiceRestInterceptor(), - ) - client = LfpStoreServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.LfpStoreServiceRestInterceptor, "post_list_lfp_stores") as post, \ - mock.patch.object(transports.LfpStoreServiceRestInterceptor, "pre_list_lfp_stores") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = lfpstore.ListLfpStoresRequest.pb(lfpstore.ListLfpStoresRequest()) - 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 = lfpstore.ListLfpStoresResponse.to_json(lfpstore.ListLfpStoresResponse()) - req.return_value.content = return_value - - request = lfpstore.ListLfpStoresRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = lfpstore.ListLfpStoresResponse() - - client.list_lfp_stores(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - -def test_initialize_client_w_rest(): - client = LfpStoreServiceClient( - 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_lfp_store_empty_call_rest(): - client = LfpStoreServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_lfp_store), - '__call__') as call: - client.get_lfp_store(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = lfpstore.GetLfpStoreRequest() - - assert args[0] == request_msg - - -# This 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_lfp_store_empty_call_rest(): - client = LfpStoreServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.insert_lfp_store), - '__call__') as call: - client.insert_lfp_store(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = lfpstore.InsertLfpStoreRequest() - - assert args[0] == request_msg - - -# This 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_lfp_store_empty_call_rest(): - client = LfpStoreServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_lfp_store), - '__call__') as call: - client.delete_lfp_store(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = lfpstore.DeleteLfpStoreRequest() - - assert args[0] == request_msg - - -# This 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_lfp_stores_empty_call_rest(): - client = LfpStoreServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_lfp_stores), - '__call__') as call: - client.list_lfp_stores(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = lfpstore.ListLfpStoresRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = LfpStoreServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.LfpStoreServiceGrpcTransport, - ) - -def test_lfp_store_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.LfpStoreServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_lfp_store_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.shopping.merchant_lfp_v1beta.services.lfp_store_service.transports.LfpStoreServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.LfpStoreServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'get_lfp_store', - 'insert_lfp_store', - 'delete_lfp_store', - 'list_lfp_stores', - ) - 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_store_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_lfp_v1beta.services.lfp_store_service.transports.LfpStoreServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.LfpStoreServiceTransport( - 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_store_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_lfp_v1beta.services.lfp_store_service.transports.LfpStoreServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.LfpStoreServiceTransport() - adc.assert_called_once() - - -def test_lfp_store_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) - LfpStoreServiceClient() - 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.LfpStoreServiceGrpcTransport, - transports.LfpStoreServiceGrpcAsyncIOTransport, - ], -) -def test_lfp_store_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.LfpStoreServiceGrpcTransport, - transports.LfpStoreServiceGrpcAsyncIOTransport, - transports.LfpStoreServiceRestTransport, - ], -) -def test_lfp_store_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.LfpStoreServiceGrpcTransport, grpc_helpers), - (transports.LfpStoreServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_lfp_store_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.LfpStoreServiceGrpcTransport, transports.LfpStoreServiceGrpcAsyncIOTransport]) -def test_lfp_store_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_store_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.LfpStoreServiceRestTransport ( - 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_store_service_host_no_port(transport_name): - client = LfpStoreServiceClient( - 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_store_service_host_with_port(transport_name): - client = LfpStoreServiceClient( - 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_store_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = LfpStoreServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = LfpStoreServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.get_lfp_store._session - session2 = client2.transport.get_lfp_store._session - assert session1 != session2 - session1 = client1.transport.insert_lfp_store._session - session2 = client2.transport.insert_lfp_store._session - assert session1 != session2 - session1 = client1.transport.delete_lfp_store._session - session2 = client2.transport.delete_lfp_store._session - assert session1 != session2 - session1 = client1.transport.list_lfp_stores._session - session2 = client2.transport.list_lfp_stores._session - assert session1 != session2 -def test_lfp_store_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.LfpStoreServiceGrpcTransport( - 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_store_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.LfpStoreServiceGrpcAsyncIOTransport( - 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.LfpStoreServiceGrpcTransport, transports.LfpStoreServiceGrpcAsyncIOTransport]) -def test_lfp_store_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.LfpStoreServiceGrpcTransport, transports.LfpStoreServiceGrpcAsyncIOTransport]) -def test_lfp_store_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_store_path(): - account = "squid" - target_merchant = "clam" - store_code = "whelk" - expected = "accounts/{account}/lfpStores/{target_merchant}~{store_code}".format(account=account, target_merchant=target_merchant, store_code=store_code, ) - actual = LfpStoreServiceClient.lfp_store_path(account, target_merchant, store_code) - assert expected == actual - - -def test_parse_lfp_store_path(): - expected = { - "account": "octopus", - "target_merchant": "oyster", - "store_code": "nudibranch", - } - path = LfpStoreServiceClient.lfp_store_path(**expected) - - # Check that the path construction is reversible. - actual = LfpStoreServiceClient.parse_lfp_store_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = LfpStoreServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = LfpStoreServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = LfpStoreServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = LfpStoreServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = LfpStoreServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = LfpStoreServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = LfpStoreServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = LfpStoreServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = LfpStoreServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = LfpStoreServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = LfpStoreServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = LfpStoreServiceClient.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 = LfpStoreServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = LfpStoreServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = LfpStoreServiceClient.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.LfpStoreServiceTransport, '_prep_wrapped_messages') as prep: - client = LfpStoreServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.LfpStoreServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = LfpStoreServiceClient.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 = LfpStoreServiceClient( - 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 = LfpStoreServiceAsyncClient( - 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 = LfpStoreServiceClient( - 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 = LfpStoreServiceClient( - 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", [ - (LfpStoreServiceClient, transports.LfpStoreServiceGrpcTransport), - (LfpStoreServiceAsyncClient, transports.LfpStoreServiceGrpcAsyncIOTransport), -]) -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-notifications/v1beta/.coveragerc b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/.coveragerc deleted file mode 100644 index 0f8bd476cddd..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/shopping/merchant_notifications/__init__.py - google/shopping/merchant_notifications/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-notifications/v1beta/.flake8 b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/MANIFEST.in b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/MANIFEST.in deleted file mode 100644 index 9f4e45925603..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/shopping/merchant_notifications *.py -recursive-include google/shopping/merchant_notifications_v1beta *.py diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/README.rst b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/README.rst deleted file mode 100644 index 614a3e6e1d20..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Shopping Merchant Notifications 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 Notifications 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 diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/_static/custom.css b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/_static/custom.css +++ /dev/null @@ -1,3 +0,0 @@ -dl.field-list > dt { - min-width: 100px -} diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/conf.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/conf.py deleted file mode 100644 index f097792928e1..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-notifications 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("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# 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.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -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-notifications" -copyright = u"2023, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# 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 = 'en' - -# 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"] - -# 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 Python", - "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-notifications-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-notifications.tex", - u"google-shopping-merchant-notifications 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-notifications", - u"Google Shopping Merchant Notifications 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-notifications", - u"google-shopping-merchant-notifications Documentation", - author, - "google-shopping-merchant-notifications", - "GAPIC library for Google Shopping Merchant Notifications API", - "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": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", 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-notifications/v1beta/docs/index.rst b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/index.rst deleted file mode 100644 index 19ecfb85828e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - merchant_notifications_v1beta/services_ - merchant_notifications_v1beta/types_ diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/merchant_notifications_v1beta/notifications_api_service.rst b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/merchant_notifications_v1beta/notifications_api_service.rst deleted file mode 100644 index ed3e6760500b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/merchant_notifications_v1beta/notifications_api_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -NotificationsApiService ------------------------------------------ - -.. automodule:: google.shopping.merchant_notifications_v1beta.services.notifications_api_service - :members: - :inherited-members: - -.. automodule:: google.shopping.merchant_notifications_v1beta.services.notifications_api_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/merchant_notifications_v1beta/services_.rst b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/merchant_notifications_v1beta/services_.rst deleted file mode 100644 index 92e0d93e8fbb..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/merchant_notifications_v1beta/services_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Shopping Merchant Notifications v1beta API -============================================================== -.. toctree:: - :maxdepth: 2 - - notifications_api_service diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/merchant_notifications_v1beta/types_.rst b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/merchant_notifications_v1beta/types_.rst deleted file mode 100644 index 8fd3b768b617..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/docs/merchant_notifications_v1beta/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Shopping Merchant Notifications v1beta API -=========================================================== - -.. automodule:: google.shopping.merchant_notifications_v1beta.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications/__init__.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications/__init__.py deleted file mode 100644 index a8de8d42680b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications/__init__.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_notifications import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.shopping.merchant_notifications_v1beta.services.notifications_api_service.client import NotificationsApiServiceClient -from google.shopping.merchant_notifications_v1beta.services.notifications_api_service.async_client import NotificationsApiServiceAsyncClient - -from google.shopping.merchant_notifications_v1beta.types.notificationsapi import CreateNotificationSubscriptionRequest -from google.shopping.merchant_notifications_v1beta.types.notificationsapi import DeleteNotificationSubscriptionRequest -from google.shopping.merchant_notifications_v1beta.types.notificationsapi import GetNotificationSubscriptionRequest -from google.shopping.merchant_notifications_v1beta.types.notificationsapi import ListNotificationSubscriptionsRequest -from google.shopping.merchant_notifications_v1beta.types.notificationsapi import ListNotificationSubscriptionsResponse -from google.shopping.merchant_notifications_v1beta.types.notificationsapi import NotificationSubscription -from google.shopping.merchant_notifications_v1beta.types.notificationsapi import ProductChange -from google.shopping.merchant_notifications_v1beta.types.notificationsapi import ProductStatusChangeMessage -from google.shopping.merchant_notifications_v1beta.types.notificationsapi import UpdateNotificationSubscriptionRequest -from google.shopping.merchant_notifications_v1beta.types.notificationsapi import Attribute -from google.shopping.merchant_notifications_v1beta.types.notificationsapi import Resource - -__all__ = ('NotificationsApiServiceClient', - 'NotificationsApiServiceAsyncClient', - 'CreateNotificationSubscriptionRequest', - 'DeleteNotificationSubscriptionRequest', - 'GetNotificationSubscriptionRequest', - 'ListNotificationSubscriptionsRequest', - 'ListNotificationSubscriptionsResponse', - 'NotificationSubscription', - 'ProductChange', - 'ProductStatusChangeMessage', - 'UpdateNotificationSubscriptionRequest', - 'Attribute', - 'Resource', -) diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications/gapic_version.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-notifications/v1beta/google/shopping/merchant_notifications/py.typed b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications/py.typed deleted file mode 100644 index 1ce34936b424..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-shopping-merchant-notifications package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/__init__.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/__init__.py deleted file mode 100644 index 4eed2bdb1813..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/__init__.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_notifications_v1beta import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.notifications_api_service import NotificationsApiServiceClient -from .services.notifications_api_service import NotificationsApiServiceAsyncClient - -from .types.notificationsapi import CreateNotificationSubscriptionRequest -from .types.notificationsapi import DeleteNotificationSubscriptionRequest -from .types.notificationsapi import GetNotificationSubscriptionRequest -from .types.notificationsapi import ListNotificationSubscriptionsRequest -from .types.notificationsapi import ListNotificationSubscriptionsResponse -from .types.notificationsapi import NotificationSubscription -from .types.notificationsapi import ProductChange -from .types.notificationsapi import ProductStatusChangeMessage -from .types.notificationsapi import UpdateNotificationSubscriptionRequest -from .types.notificationsapi import Attribute -from .types.notificationsapi import Resource - -__all__ = ( - 'NotificationsApiServiceAsyncClient', -'Attribute', -'CreateNotificationSubscriptionRequest', -'DeleteNotificationSubscriptionRequest', -'GetNotificationSubscriptionRequest', -'ListNotificationSubscriptionsRequest', -'ListNotificationSubscriptionsResponse', -'NotificationSubscription', -'NotificationsApiServiceClient', -'ProductChange', -'ProductStatusChangeMessage', -'Resource', -'UpdateNotificationSubscriptionRequest', -) diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/gapic_metadata.json b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/gapic_metadata.json deleted file mode 100644 index 1c9f742e51f9..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/gapic_metadata.json +++ /dev/null @@ -1,103 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.shopping.merchant_notifications_v1beta", - "protoPackage": "google.shopping.merchant.notifications.v1beta", - "schema": "1.0", - "services": { - "NotificationsApiService": { - "clients": { - "grpc": { - "libraryClient": "NotificationsApiServiceClient", - "rpcs": { - "CreateNotificationSubscription": { - "methods": [ - "create_notification_subscription" - ] - }, - "DeleteNotificationSubscription": { - "methods": [ - "delete_notification_subscription" - ] - }, - "GetNotificationSubscription": { - "methods": [ - "get_notification_subscription" - ] - }, - "ListNotificationSubscriptions": { - "methods": [ - "list_notification_subscriptions" - ] - }, - "UpdateNotificationSubscription": { - "methods": [ - "update_notification_subscription" - ] - } - } - }, - "grpc-async": { - "libraryClient": "NotificationsApiServiceAsyncClient", - "rpcs": { - "CreateNotificationSubscription": { - "methods": [ - "create_notification_subscription" - ] - }, - "DeleteNotificationSubscription": { - "methods": [ - "delete_notification_subscription" - ] - }, - "GetNotificationSubscription": { - "methods": [ - "get_notification_subscription" - ] - }, - "ListNotificationSubscriptions": { - "methods": [ - "list_notification_subscriptions" - ] - }, - "UpdateNotificationSubscription": { - "methods": [ - "update_notification_subscription" - ] - } - } - }, - "rest": { - "libraryClient": "NotificationsApiServiceClient", - "rpcs": { - "CreateNotificationSubscription": { - "methods": [ - "create_notification_subscription" - ] - }, - "DeleteNotificationSubscription": { - "methods": [ - "delete_notification_subscription" - ] - }, - "GetNotificationSubscription": { - "methods": [ - "get_notification_subscription" - ] - }, - "ListNotificationSubscriptions": { - "methods": [ - "list_notification_subscriptions" - ] - }, - "UpdateNotificationSubscription": { - "methods": [ - "update_notification_subscription" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/gapic_version.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-notifications/v1beta/google/shopping/merchant_notifications_v1beta/py.typed b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/py.typed deleted file mode 100644 index 1ce34936b424..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-shopping-merchant-notifications package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/__init__.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/__init__.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/__init__.py deleted file mode 100644 index 8698b4100c81..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 NotificationsApiServiceClient -from .async_client import NotificationsApiServiceAsyncClient - -__all__ = ( - 'NotificationsApiServiceClient', - 'NotificationsApiServiceAsyncClient', -) diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/async_client.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/async_client.py deleted file mode 100644 index 6dd0a4e1ca9c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/async_client.py +++ /dev/null @@ -1,836 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_notifications_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 - - -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_notifications_v1beta.services.notifications_api_service import pagers -from google.shopping.merchant_notifications_v1beta.types import notificationsapi -from .transports.base import NotificationsApiServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import NotificationsApiServiceGrpcAsyncIOTransport -from .client import NotificationsApiServiceClient - -try: - from google.api_core import client_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 NotificationsApiServiceAsyncClient: - """Service to manage notification subscriptions for merchants""" - - _client: NotificationsApiServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = NotificationsApiServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = NotificationsApiServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = NotificationsApiServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = NotificationsApiServiceClient._DEFAULT_UNIVERSE - - notification_subscription_path = staticmethod(NotificationsApiServiceClient.notification_subscription_path) - parse_notification_subscription_path = staticmethod(NotificationsApiServiceClient.parse_notification_subscription_path) - common_billing_account_path = staticmethod(NotificationsApiServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(NotificationsApiServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(NotificationsApiServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(NotificationsApiServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(NotificationsApiServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(NotificationsApiServiceClient.parse_common_organization_path) - common_project_path = staticmethod(NotificationsApiServiceClient.common_project_path) - parse_common_project_path = staticmethod(NotificationsApiServiceClient.parse_common_project_path) - common_location_path = staticmethod(NotificationsApiServiceClient.common_location_path) - parse_common_location_path = staticmethod(NotificationsApiServiceClient.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: - NotificationsApiServiceAsyncClient: The constructed client. - """ - return NotificationsApiServiceClient.from_service_account_info.__func__(NotificationsApiServiceAsyncClient, 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: - NotificationsApiServiceAsyncClient: The constructed client. - """ - return NotificationsApiServiceClient.from_service_account_file.__func__(NotificationsApiServiceAsyncClient, 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 NotificationsApiServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> NotificationsApiServiceTransport: - """Returns the transport used by the client instance. - - Returns: - NotificationsApiServiceTransport: 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 = NotificationsApiServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, NotificationsApiServiceTransport, Callable[..., NotificationsApiServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the notifications api 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,NotificationsApiServiceTransport,Callable[..., NotificationsApiServiceTransport]]]): - 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 NotificationsApiServiceTransport 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 = NotificationsApiServiceClient( - 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.notifications_v1beta.NotificationsApiServiceAsyncClient`.", - extra = { - "serviceName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", - "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.notifications.v1beta.NotificationsApiService", - "credentialsType": None, - } - ) - - async def get_notification_subscription(self, - request: Optional[Union[notificationsapi.GetNotificationSubscriptionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> notificationsapi.NotificationSubscription: - r"""Gets notification subscriptions for 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_notifications_v1beta - - async def sample_get_notification_subscription(): - # Create a client - client = merchant_notifications_v1beta.NotificationsApiServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_notifications_v1beta.GetNotificationSubscriptionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_notification_subscription(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_notifications_v1beta.types.GetNotificationSubscriptionRequest, dict]]): - The request object. Request message for the - GetNotificationSubscription method. - name (:class:`str`): - Required. The ``name`` of the notification subscription. - 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_notifications_v1beta.types.NotificationSubscription: - Represents a notification - subscription 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, notificationsapi.GetNotificationSubscriptionRequest): - request = notificationsapi.GetNotificationSubscriptionRequest(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_notification_subscription] - - # Certain 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_notification_subscription(self, - request: Optional[Union[notificationsapi.CreateNotificationSubscriptionRequest, dict]] = None, - *, - parent: Optional[str] = None, - notification_subscription: Optional[notificationsapi.NotificationSubscription] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> notificationsapi.NotificationSubscription: - r"""Creates a notification subscription for a merchant. - We will allow the following types of notification - subscriptions to exist together (per merchant as a - subscriber per event type): - - 1. Subscription for all managed accounts + subscription - for self - 2. Multiple "partial" subscriptions for managed accounts - + subscription for self - - we will not allow (per merchant as a subscriber per - event type): - - 1. multiple self subscriptions. - 2. multiple "all managed accounts" subscriptions. - 3. all and partial subscriptions at the same time. - 4. multiple partial subscriptions for the same target - 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_notifications_v1beta - - async def sample_create_notification_subscription(): - # Create a client - client = merchant_notifications_v1beta.NotificationsApiServiceAsyncClient() - - # Initialize request argument(s) - notification_subscription = merchant_notifications_v1beta.NotificationSubscription() - notification_subscription.all_managed_accounts = True - - request = merchant_notifications_v1beta.CreateNotificationSubscriptionRequest( - parent="parent_value", - notification_subscription=notification_subscription, - ) - - # Make the request - response = await client.create_notification_subscription(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_notifications_v1beta.types.CreateNotificationSubscriptionRequest, dict]]): - The request object. Request message for the - CreateNotificationSubscription method. - parent (:class:`str`): - Required. The merchant account that owns the new - notification subscription. Format: - ``accounts/{account}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - notification_subscription (:class:`google.shopping.merchant_notifications_v1beta.types.NotificationSubscription`): - Required. The notification - subscription to create. - - This corresponds to the ``notification_subscription`` 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_notifications_v1beta.types.NotificationSubscription: - Represents a notification - subscription 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. - has_flattened_params = any([parent, notification_subscription]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, notificationsapi.CreateNotificationSubscriptionRequest): - request = notificationsapi.CreateNotificationSubscriptionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if notification_subscription is not None: - request.notification_subscription = notification_subscription - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_notification_subscription] - - # Certain 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_notification_subscription(self, - request: Optional[Union[notificationsapi.UpdateNotificationSubscriptionRequest, dict]] = None, - *, - notification_subscription: Optional[notificationsapi.NotificationSubscription] = 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]]] = (), - ) -> notificationsapi.NotificationSubscription: - r"""Updates an existing notification subscription 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_notifications_v1beta - - async def sample_update_notification_subscription(): - # Create a client - client = merchant_notifications_v1beta.NotificationsApiServiceAsyncClient() - - # Initialize request argument(s) - notification_subscription = merchant_notifications_v1beta.NotificationSubscription() - notification_subscription.all_managed_accounts = True - - request = merchant_notifications_v1beta.UpdateNotificationSubscriptionRequest( - notification_subscription=notification_subscription, - ) - - # Make the request - response = await client.update_notification_subscription(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_notifications_v1beta.types.UpdateNotificationSubscriptionRequest, dict]]): - The request object. Request message for the - UpdateNotificationSubscription method. - notification_subscription (:class:`google.shopping.merchant_notifications_v1beta.types.NotificationSubscription`): - Required. The new version of the - notification subscription that should be - updated. - - This corresponds to the ``notification_subscription`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - 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_notifications_v1beta.types.NotificationSubscription: - Represents a notification - subscription 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. - has_flattened_params = any([notification_subscription, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, notificationsapi.UpdateNotificationSubscriptionRequest): - request = notificationsapi.UpdateNotificationSubscriptionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if notification_subscription is not None: - request.notification_subscription = notification_subscription - 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_notification_subscription] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("notification_subscription.name", request.notification_subscription.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_notification_subscription(self, - request: Optional[Union[notificationsapi.DeleteNotificationSubscriptionRequest, dict]] = None, - *, - name: Optional[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 notification subscription 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_notifications_v1beta - - async def sample_delete_notification_subscription(): - # Create a client - client = merchant_notifications_v1beta.NotificationsApiServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_notifications_v1beta.DeleteNotificationSubscriptionRequest( - name="name_value", - ) - - # Make the request - await client.delete_notification_subscription(request=request) - - Args: - request (Optional[Union[google.shopping.merchant_notifications_v1beta.types.DeleteNotificationSubscriptionRequest, dict]]): - The request object. Request message for the - DeleteNotificationSubscription method. - name (:class:`str`): - Required. The name of the - notification subscription to be deleted. - - 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, notificationsapi.DeleteNotificationSubscriptionRequest): - request = notificationsapi.DeleteNotificationSubscriptionRequest(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_notification_subscription] - - # Certain 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_notification_subscriptions(self, - request: Optional[Union[notificationsapi.ListNotificationSubscriptionsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListNotificationSubscriptionsAsyncPager: - r"""Gets all the notification subscriptions 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_notifications_v1beta - - async def sample_list_notification_subscriptions(): - # Create a client - client = merchant_notifications_v1beta.NotificationsApiServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_notifications_v1beta.ListNotificationSubscriptionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_notification_subscriptions(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_notifications_v1beta.types.ListNotificationSubscriptionsRequest, dict]]): - The request object. Request message for the - ListNotificationSubscription method. - parent (:class:`str`): - Required. The merchant account who owns the notification - subscriptions. 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_notifications_v1beta.services.notifications_api_service.pagers.ListNotificationSubscriptionsAsyncPager: - Response message for the - ListNotificationSubscription 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, notificationsapi.ListNotificationSubscriptionsRequest): - request = notificationsapi.ListNotificationSubscriptionsRequest(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_notification_subscriptions] - - # Certain 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.ListNotificationSubscriptionsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self) -> "NotificationsApiServiceAsyncClient": - 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__) - - -__all__ = ( - "NotificationsApiServiceAsyncClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/client.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/client.py deleted file mode 100644 index cd34d69acb8c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/client.py +++ /dev/null @@ -1,1167 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -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_notifications_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 - -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_notifications_v1beta.services.notifications_api_service import pagers -from google.shopping.merchant_notifications_v1beta.types import notificationsapi -from .transports.base import NotificationsApiServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import NotificationsApiServiceGrpcTransport -from .transports.grpc_asyncio import NotificationsApiServiceGrpcAsyncIOTransport -from .transports.rest import NotificationsApiServiceRestTransport - - -class NotificationsApiServiceClientMeta(type): - """Metaclass for the NotificationsApiService 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[NotificationsApiServiceTransport]] - _transport_registry["grpc"] = NotificationsApiServiceGrpcTransport - _transport_registry["grpc_asyncio"] = NotificationsApiServiceGrpcAsyncIOTransport - _transport_registry["rest"] = NotificationsApiServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[NotificationsApiServiceTransport]: - """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 NotificationsApiServiceClient(metaclass=NotificationsApiServiceClientMeta): - """Service to manage notification subscriptions for merchants""" - - @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: - NotificationsApiServiceClient: 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: - NotificationsApiServiceClient: 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) -> NotificationsApiServiceTransport: - """Returns the transport used by the client instance. - - Returns: - NotificationsApiServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def notification_subscription_path(account: str,notification_subscription: str,) -> str: - """Returns a fully-qualified notification_subscription string.""" - return "accounts/{account}/notificationsubscriptions/{notification_subscription}".format(account=account, notification_subscription=notification_subscription, ) - - @staticmethod - def parse_notification_subscription_path(path: str) -> Dict[str,str]: - """Parses a notification_subscription path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/notificationsubscriptions/(?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 = NotificationsApiServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = NotificationsApiServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = NotificationsApiServiceClient._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 = NotificationsApiServiceClient._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 - - @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, NotificationsApiServiceTransport, Callable[..., NotificationsApiServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the notifications api 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,NotificationsApiServiceTransport,Callable[..., NotificationsApiServiceTransport]]]): - 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 NotificationsApiServiceTransport 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 = NotificationsApiServiceClient._read_environment_variables() - self._client_cert_source = NotificationsApiServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = NotificationsApiServiceClient._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, NotificationsApiServiceTransport) - if transport_provided: - # transport is a NotificationsApiServiceTransport 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(NotificationsApiServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - NotificationsApiServiceClient._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[NotificationsApiServiceTransport], Callable[..., NotificationsApiServiceTransport]] = ( - NotificationsApiServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., NotificationsApiServiceTransport], 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.notifications_v1beta.NotificationsApiServiceClient`.", - extra = { - "serviceName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", - "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.notifications.v1beta.NotificationsApiService", - "credentialsType": None, - } - ) - - def get_notification_subscription(self, - request: Optional[Union[notificationsapi.GetNotificationSubscriptionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> notificationsapi.NotificationSubscription: - r"""Gets notification subscriptions for 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_notifications_v1beta - - def sample_get_notification_subscription(): - # Create a client - client = merchant_notifications_v1beta.NotificationsApiServiceClient() - - # Initialize request argument(s) - request = merchant_notifications_v1beta.GetNotificationSubscriptionRequest( - name="name_value", - ) - - # Make the request - response = client.get_notification_subscription(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_notifications_v1beta.types.GetNotificationSubscriptionRequest, dict]): - The request object. Request message for the - GetNotificationSubscription method. - name (str): - Required. The ``name`` of the notification subscription. - 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_notifications_v1beta.types.NotificationSubscription: - Represents a notification - subscription 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, notificationsapi.GetNotificationSubscriptionRequest): - request = notificationsapi.GetNotificationSubscriptionRequest(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_notification_subscription] - - # Certain 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_notification_subscription(self, - request: Optional[Union[notificationsapi.CreateNotificationSubscriptionRequest, dict]] = None, - *, - parent: Optional[str] = None, - notification_subscription: Optional[notificationsapi.NotificationSubscription] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> notificationsapi.NotificationSubscription: - r"""Creates a notification subscription for a merchant. - We will allow the following types of notification - subscriptions to exist together (per merchant as a - subscriber per event type): - - 1. Subscription for all managed accounts + subscription - for self - 2. Multiple "partial" subscriptions for managed accounts - + subscription for self - - we will not allow (per merchant as a subscriber per - event type): - - 1. multiple self subscriptions. - 2. multiple "all managed accounts" subscriptions. - 3. all and partial subscriptions at the same time. - 4. multiple partial subscriptions for the same target - 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_notifications_v1beta - - def sample_create_notification_subscription(): - # Create a client - client = merchant_notifications_v1beta.NotificationsApiServiceClient() - - # Initialize request argument(s) - notification_subscription = merchant_notifications_v1beta.NotificationSubscription() - notification_subscription.all_managed_accounts = True - - request = merchant_notifications_v1beta.CreateNotificationSubscriptionRequest( - parent="parent_value", - notification_subscription=notification_subscription, - ) - - # Make the request - response = client.create_notification_subscription(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_notifications_v1beta.types.CreateNotificationSubscriptionRequest, dict]): - The request object. Request message for the - CreateNotificationSubscription method. - parent (str): - Required. The merchant account that owns the new - notification subscription. Format: - ``accounts/{account}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - notification_subscription (google.shopping.merchant_notifications_v1beta.types.NotificationSubscription): - Required. The notification - subscription to create. - - This corresponds to the ``notification_subscription`` 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_notifications_v1beta.types.NotificationSubscription: - Represents a notification - subscription 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. - has_flattened_params = any([parent, notification_subscription]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, notificationsapi.CreateNotificationSubscriptionRequest): - request = notificationsapi.CreateNotificationSubscriptionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if notification_subscription is not None: - request.notification_subscription = notification_subscription - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_notification_subscription] - - # Certain 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_notification_subscription(self, - request: Optional[Union[notificationsapi.UpdateNotificationSubscriptionRequest, dict]] = None, - *, - notification_subscription: Optional[notificationsapi.NotificationSubscription] = 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]]] = (), - ) -> notificationsapi.NotificationSubscription: - r"""Updates an existing notification subscription 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_notifications_v1beta - - def sample_update_notification_subscription(): - # Create a client - client = merchant_notifications_v1beta.NotificationsApiServiceClient() - - # Initialize request argument(s) - notification_subscription = merchant_notifications_v1beta.NotificationSubscription() - notification_subscription.all_managed_accounts = True - - request = merchant_notifications_v1beta.UpdateNotificationSubscriptionRequest( - notification_subscription=notification_subscription, - ) - - # Make the request - response = client.update_notification_subscription(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_notifications_v1beta.types.UpdateNotificationSubscriptionRequest, dict]): - The request object. Request message for the - UpdateNotificationSubscription method. - notification_subscription (google.shopping.merchant_notifications_v1beta.types.NotificationSubscription): - Required. The new version of the - notification subscription that should be - updated. - - This corresponds to the ``notification_subscription`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - 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_notifications_v1beta.types.NotificationSubscription: - Represents a notification - subscription 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. - has_flattened_params = any([notification_subscription, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, notificationsapi.UpdateNotificationSubscriptionRequest): - request = notificationsapi.UpdateNotificationSubscriptionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if notification_subscription is not None: - request.notification_subscription = notification_subscription - 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_notification_subscription] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("notification_subscription.name", request.notification_subscription.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_notification_subscription(self, - request: Optional[Union[notificationsapi.DeleteNotificationSubscriptionRequest, dict]] = None, - *, - name: Optional[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 notification subscription 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_notifications_v1beta - - def sample_delete_notification_subscription(): - # Create a client - client = merchant_notifications_v1beta.NotificationsApiServiceClient() - - # Initialize request argument(s) - request = merchant_notifications_v1beta.DeleteNotificationSubscriptionRequest( - name="name_value", - ) - - # Make the request - client.delete_notification_subscription(request=request) - - Args: - request (Union[google.shopping.merchant_notifications_v1beta.types.DeleteNotificationSubscriptionRequest, dict]): - The request object. Request message for the - DeleteNotificationSubscription method. - name (str): - Required. The name of the - notification subscription to be deleted. - - 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, notificationsapi.DeleteNotificationSubscriptionRequest): - request = notificationsapi.DeleteNotificationSubscriptionRequest(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_notification_subscription] - - # Certain 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_notification_subscriptions(self, - request: Optional[Union[notificationsapi.ListNotificationSubscriptionsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListNotificationSubscriptionsPager: - r"""Gets all the notification subscriptions 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_notifications_v1beta - - def sample_list_notification_subscriptions(): - # Create a client - client = merchant_notifications_v1beta.NotificationsApiServiceClient() - - # Initialize request argument(s) - request = merchant_notifications_v1beta.ListNotificationSubscriptionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_notification_subscriptions(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.shopping.merchant_notifications_v1beta.types.ListNotificationSubscriptionsRequest, dict]): - The request object. Request message for the - ListNotificationSubscription method. - parent (str): - Required. The merchant account who owns the notification - subscriptions. 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_notifications_v1beta.services.notifications_api_service.pagers.ListNotificationSubscriptionsPager: - Response message for the - ListNotificationSubscription 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, notificationsapi.ListNotificationSubscriptionsRequest): - request = notificationsapi.ListNotificationSubscriptionsRequest(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_notification_subscriptions] - - # Certain 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.ListNotificationSubscriptionsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "NotificationsApiServiceClient": - 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__) - - -__all__ = ( - "NotificationsApiServiceClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/pagers.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/pagers.py deleted file mode 100644 index 9184edf322ec..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/pagers.py +++ /dev/null @@ -1,166 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_notifications_v1beta.types import notificationsapi - - -class ListNotificationSubscriptionsPager: - """A pager for iterating through ``list_notification_subscriptions`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_notifications_v1beta.types.ListNotificationSubscriptionsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``notification_subscriptions`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListNotificationSubscriptions`` requests and continue to iterate - through the ``notification_subscriptions`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_notifications_v1beta.types.ListNotificationSubscriptionsResponse` - 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[..., notificationsapi.ListNotificationSubscriptionsResponse], - request: notificationsapi.ListNotificationSubscriptionsRequest, - response: notificationsapi.ListNotificationSubscriptionsResponse, - *, - 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_notifications_v1beta.types.ListNotificationSubscriptionsRequest): - The initial request object. - response (google.shopping.merchant_notifications_v1beta.types.ListNotificationSubscriptionsResponse): - 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 = notificationsapi.ListNotificationSubscriptionsRequest(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[notificationsapi.ListNotificationSubscriptionsResponse]: - 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[notificationsapi.NotificationSubscription]: - for page in self.pages: - yield from page.notification_subscriptions - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListNotificationSubscriptionsAsyncPager: - """A pager for iterating through ``list_notification_subscriptions`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_notifications_v1beta.types.ListNotificationSubscriptionsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``notification_subscriptions`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListNotificationSubscriptions`` requests and continue to iterate - through the ``notification_subscriptions`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_notifications_v1beta.types.ListNotificationSubscriptionsResponse` - 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[notificationsapi.ListNotificationSubscriptionsResponse]], - request: notificationsapi.ListNotificationSubscriptionsRequest, - response: notificationsapi.ListNotificationSubscriptionsResponse, - *, - 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_notifications_v1beta.types.ListNotificationSubscriptionsRequest): - The initial request object. - response (google.shopping.merchant_notifications_v1beta.types.ListNotificationSubscriptionsResponse): - 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 = notificationsapi.ListNotificationSubscriptionsRequest(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[notificationsapi.ListNotificationSubscriptionsResponse]: - 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[notificationsapi.NotificationSubscription]: - async def async_generator(): - async for page in self.pages: - for response in page.notification_subscriptions: - 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-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/README.rst deleted file mode 100644 index e82a831890a4..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`NotificationsApiServiceTransport` is the ABC for all transports. -- public child `NotificationsApiServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `NotificationsApiServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseNotificationsApiServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `NotificationsApiServiceRestTransport` 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-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/__init__.py deleted file mode 100644 index fbc95bf86509..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 NotificationsApiServiceTransport -from .grpc import NotificationsApiServiceGrpcTransport -from .grpc_asyncio import NotificationsApiServiceGrpcAsyncIOTransport -from .rest import NotificationsApiServiceRestTransport -from .rest import NotificationsApiServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[NotificationsApiServiceTransport]] -_transport_registry['grpc'] = NotificationsApiServiceGrpcTransport -_transport_registry['grpc_asyncio'] = NotificationsApiServiceGrpcAsyncIOTransport -_transport_registry['rest'] = NotificationsApiServiceRestTransport - -__all__ = ( - 'NotificationsApiServiceTransport', - 'NotificationsApiServiceGrpcTransport', - 'NotificationsApiServiceGrpcAsyncIOTransport', - 'NotificationsApiServiceRestTransport', - 'NotificationsApiServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/base.py deleted file mode 100644 index 4b8680eaaea3..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/base.py +++ /dev/null @@ -1,211 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_notifications_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 - -from google.protobuf import empty_pb2 # type: ignore -from google.shopping.merchant_notifications_v1beta.types import notificationsapi - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class NotificationsApiServiceTransport(abc.ABC): - """Abstract transport class for NotificationsApiService.""" - - 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_notification_subscription: gapic_v1.method.wrap_method( - self.get_notification_subscription, - default_timeout=None, - client_info=client_info, - ), - self.create_notification_subscription: gapic_v1.method.wrap_method( - self.create_notification_subscription, - default_timeout=None, - client_info=client_info, - ), - self.update_notification_subscription: gapic_v1.method.wrap_method( - self.update_notification_subscription, - default_timeout=None, - client_info=client_info, - ), - self.delete_notification_subscription: gapic_v1.method.wrap_method( - self.delete_notification_subscription, - default_timeout=None, - client_info=client_info, - ), - self.list_notification_subscriptions: gapic_v1.method.wrap_method( - self.list_notification_subscriptions, - 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_notification_subscription(self) -> Callable[ - [notificationsapi.GetNotificationSubscriptionRequest], - Union[ - notificationsapi.NotificationSubscription, - Awaitable[notificationsapi.NotificationSubscription] - ]]: - raise NotImplementedError() - - @property - def create_notification_subscription(self) -> Callable[ - [notificationsapi.CreateNotificationSubscriptionRequest], - Union[ - notificationsapi.NotificationSubscription, - Awaitable[notificationsapi.NotificationSubscription] - ]]: - raise NotImplementedError() - - @property - def update_notification_subscription(self) -> Callable[ - [notificationsapi.UpdateNotificationSubscriptionRequest], - Union[ - notificationsapi.NotificationSubscription, - Awaitable[notificationsapi.NotificationSubscription] - ]]: - raise NotImplementedError() - - @property - def delete_notification_subscription(self) -> Callable[ - [notificationsapi.DeleteNotificationSubscriptionRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def list_notification_subscriptions(self) -> Callable[ - [notificationsapi.ListNotificationSubscriptionsRequest], - Union[ - notificationsapi.ListNotificationSubscriptionsResponse, - Awaitable[notificationsapi.ListNotificationSubscriptionsResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'NotificationsApiServiceTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/grpc.py deleted file mode 100644 index 46e0337f5471..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/grpc.py +++ /dev/null @@ -1,475 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_notifications_v1beta.types import notificationsapi -from .base import NotificationsApiServiceTransport, 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.notifications.v1beta.NotificationsApiService", - "rpcName": 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.notifications.v1beta.NotificationsApiService", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class NotificationsApiServiceGrpcTransport(NotificationsApiServiceTransport): - """gRPC backend transport for NotificationsApiService. - - Service to manage notification subscriptions for merchants - - This 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_notification_subscription(self) -> Callable[ - [notificationsapi.GetNotificationSubscriptionRequest], - notificationsapi.NotificationSubscription]: - r"""Return a callable for the get notification subscription method over gRPC. - - Gets notification subscriptions for an account. - - Returns: - Callable[[~.GetNotificationSubscriptionRequest], - ~.NotificationSubscription]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_notification_subscription' not in self._stubs: - self._stubs['get_notification_subscription'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.notifications.v1beta.NotificationsApiService/GetNotificationSubscription', - request_serializer=notificationsapi.GetNotificationSubscriptionRequest.serialize, - response_deserializer=notificationsapi.NotificationSubscription.deserialize, - ) - return self._stubs['get_notification_subscription'] - - @property - def create_notification_subscription(self) -> Callable[ - [notificationsapi.CreateNotificationSubscriptionRequest], - notificationsapi.NotificationSubscription]: - r"""Return a callable for the create notification - subscription method over gRPC. - - Creates a notification subscription for a merchant. - We will allow the following types of notification - subscriptions to exist together (per merchant as a - subscriber per event type): - - 1. Subscription for all managed accounts + subscription - for self - 2. Multiple "partial" subscriptions for managed accounts - + subscription for self - - we will not allow (per merchant as a subscriber per - event type): - - 1. multiple self subscriptions. - 2. multiple "all managed accounts" subscriptions. - 3. all and partial subscriptions at the same time. - 4. multiple partial subscriptions for the same target - account - - Returns: - Callable[[~.CreateNotificationSubscriptionRequest], - ~.NotificationSubscription]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_notification_subscription' not in self._stubs: - self._stubs['create_notification_subscription'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.notifications.v1beta.NotificationsApiService/CreateNotificationSubscription', - request_serializer=notificationsapi.CreateNotificationSubscriptionRequest.serialize, - response_deserializer=notificationsapi.NotificationSubscription.deserialize, - ) - return self._stubs['create_notification_subscription'] - - @property - def update_notification_subscription(self) -> Callable[ - [notificationsapi.UpdateNotificationSubscriptionRequest], - notificationsapi.NotificationSubscription]: - r"""Return a callable for the update notification - subscription method over gRPC. - - Updates an existing notification subscription for a - merchant. - - Returns: - Callable[[~.UpdateNotificationSubscriptionRequest], - ~.NotificationSubscription]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_notification_subscription' not in self._stubs: - self._stubs['update_notification_subscription'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.notifications.v1beta.NotificationsApiService/UpdateNotificationSubscription', - request_serializer=notificationsapi.UpdateNotificationSubscriptionRequest.serialize, - response_deserializer=notificationsapi.NotificationSubscription.deserialize, - ) - return self._stubs['update_notification_subscription'] - - @property - def delete_notification_subscription(self) -> Callable[ - [notificationsapi.DeleteNotificationSubscriptionRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete notification - subscription method over gRPC. - - Deletes a notification subscription for a merchant. - - Returns: - Callable[[~.DeleteNotificationSubscriptionRequest], - ~.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_notification_subscription' not in self._stubs: - self._stubs['delete_notification_subscription'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.notifications.v1beta.NotificationsApiService/DeleteNotificationSubscription', - request_serializer=notificationsapi.DeleteNotificationSubscriptionRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_notification_subscription'] - - @property - def list_notification_subscriptions(self) -> Callable[ - [notificationsapi.ListNotificationSubscriptionsRequest], - notificationsapi.ListNotificationSubscriptionsResponse]: - r"""Return a callable for the list notification - subscriptions method over gRPC. - - Gets all the notification subscriptions for a - merchant. - - Returns: - Callable[[~.ListNotificationSubscriptionsRequest], - ~.ListNotificationSubscriptionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_notification_subscriptions' not in self._stubs: - self._stubs['list_notification_subscriptions'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.notifications.v1beta.NotificationsApiService/ListNotificationSubscriptions', - request_serializer=notificationsapi.ListNotificationSubscriptionsRequest.serialize, - response_deserializer=notificationsapi.ListNotificationSubscriptionsResponse.deserialize, - ) - return self._stubs['list_notification_subscriptions'] - - def close(self): - self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'NotificationsApiServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/grpc_asyncio.py deleted file mode 100644 index dd19eebdba6c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,515 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_notifications_v1beta.types import notificationsapi -from .base import NotificationsApiServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import NotificationsApiServiceGrpcTransport - -try: - from google.api_core import client_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.notifications.v1beta.NotificationsApiService", - "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.notifications.v1beta.NotificationsApiService", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class NotificationsApiServiceGrpcAsyncIOTransport(NotificationsApiServiceTransport): - """gRPC AsyncIO backend transport for NotificationsApiService. - - Service to manage notification subscriptions for merchants - - This 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_notification_subscription(self) -> Callable[ - [notificationsapi.GetNotificationSubscriptionRequest], - Awaitable[notificationsapi.NotificationSubscription]]: - r"""Return a callable for the get notification subscription method over gRPC. - - Gets notification subscriptions for an account. - - Returns: - Callable[[~.GetNotificationSubscriptionRequest], - Awaitable[~.NotificationSubscription]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_notification_subscription' not in self._stubs: - self._stubs['get_notification_subscription'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.notifications.v1beta.NotificationsApiService/GetNotificationSubscription', - request_serializer=notificationsapi.GetNotificationSubscriptionRequest.serialize, - response_deserializer=notificationsapi.NotificationSubscription.deserialize, - ) - return self._stubs['get_notification_subscription'] - - @property - def create_notification_subscription(self) -> Callable[ - [notificationsapi.CreateNotificationSubscriptionRequest], - Awaitable[notificationsapi.NotificationSubscription]]: - r"""Return a callable for the create notification - subscription method over gRPC. - - Creates a notification subscription for a merchant. - We will allow the following types of notification - subscriptions to exist together (per merchant as a - subscriber per event type): - - 1. Subscription for all managed accounts + subscription - for self - 2. Multiple "partial" subscriptions for managed accounts - + subscription for self - - we will not allow (per merchant as a subscriber per - event type): - - 1. multiple self subscriptions. - 2. multiple "all managed accounts" subscriptions. - 3. all and partial subscriptions at the same time. - 4. multiple partial subscriptions for the same target - account - - Returns: - Callable[[~.CreateNotificationSubscriptionRequest], - Awaitable[~.NotificationSubscription]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_notification_subscription' not in self._stubs: - self._stubs['create_notification_subscription'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.notifications.v1beta.NotificationsApiService/CreateNotificationSubscription', - request_serializer=notificationsapi.CreateNotificationSubscriptionRequest.serialize, - response_deserializer=notificationsapi.NotificationSubscription.deserialize, - ) - return self._stubs['create_notification_subscription'] - - @property - def update_notification_subscription(self) -> Callable[ - [notificationsapi.UpdateNotificationSubscriptionRequest], - Awaitable[notificationsapi.NotificationSubscription]]: - r"""Return a callable for the update notification - subscription method over gRPC. - - Updates an existing notification subscription for a - merchant. - - Returns: - Callable[[~.UpdateNotificationSubscriptionRequest], - Awaitable[~.NotificationSubscription]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_notification_subscription' not in self._stubs: - self._stubs['update_notification_subscription'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.notifications.v1beta.NotificationsApiService/UpdateNotificationSubscription', - request_serializer=notificationsapi.UpdateNotificationSubscriptionRequest.serialize, - response_deserializer=notificationsapi.NotificationSubscription.deserialize, - ) - return self._stubs['update_notification_subscription'] - - @property - def delete_notification_subscription(self) -> Callable[ - [notificationsapi.DeleteNotificationSubscriptionRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete notification - subscription method over gRPC. - - Deletes a notification subscription for a merchant. - - Returns: - Callable[[~.DeleteNotificationSubscriptionRequest], - 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_notification_subscription' not in self._stubs: - self._stubs['delete_notification_subscription'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.notifications.v1beta.NotificationsApiService/DeleteNotificationSubscription', - request_serializer=notificationsapi.DeleteNotificationSubscriptionRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_notification_subscription'] - - @property - def list_notification_subscriptions(self) -> Callable[ - [notificationsapi.ListNotificationSubscriptionsRequest], - Awaitable[notificationsapi.ListNotificationSubscriptionsResponse]]: - r"""Return a callable for the list notification - subscriptions method over gRPC. - - Gets all the notification subscriptions for a - merchant. - - Returns: - Callable[[~.ListNotificationSubscriptionsRequest], - Awaitable[~.ListNotificationSubscriptionsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_notification_subscriptions' not in self._stubs: - self._stubs['list_notification_subscriptions'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.notifications.v1beta.NotificationsApiService/ListNotificationSubscriptions', - request_serializer=notificationsapi.ListNotificationSubscriptionsRequest.serialize, - response_deserializer=notificationsapi.ListNotificationSubscriptionsResponse.deserialize, - ) - return self._stubs['list_notification_subscriptions'] - - 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_notification_subscription: self._wrap_method( - self.get_notification_subscription, - default_timeout=None, - client_info=client_info, - ), - self.create_notification_subscription: self._wrap_method( - self.create_notification_subscription, - default_timeout=None, - client_info=client_info, - ), - self.update_notification_subscription: self._wrap_method( - self.update_notification_subscription, - default_timeout=None, - client_info=client_info, - ), - self.delete_notification_subscription: self._wrap_method( - self.delete_notification_subscription, - default_timeout=None, - client_info=client_info, - ), - self.list_notification_subscriptions: self._wrap_method( - self.list_notification_subscriptions, - 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__ = ( - 'NotificationsApiServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/rest.py deleted file mode 100644 index 1b7eb10db2be..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/rest.py +++ /dev/null @@ -1,909 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -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_notifications_v1beta.types import notificationsapi - - -from .rest_base import _BaseNotificationsApiServiceRestTransport -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}", -) - - -class NotificationsApiServiceRestInterceptor: - """Interceptor for NotificationsApiService. - - 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 NotificationsApiServiceRestTransport. - - .. code-block:: python - class MyCustomNotificationsApiServiceInterceptor(NotificationsApiServiceRestInterceptor): - def pre_create_notification_subscription(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_notification_subscription(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_notification_subscription(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_notification_subscription(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_notification_subscription(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_notification_subscriptions(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_notification_subscriptions(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_notification_subscription(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_notification_subscription(self, response): - logging.log(f"Received response: {response}") - return response - - transport = NotificationsApiServiceRestTransport(interceptor=MyCustomNotificationsApiServiceInterceptor()) - client = NotificationsApiServiceClient(transport=transport) - - - """ - def pre_create_notification_subscription(self, request: notificationsapi.CreateNotificationSubscriptionRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[notificationsapi.CreateNotificationSubscriptionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for create_notification_subscription - - Override in a subclass to manipulate the request or metadata - before they are sent to the NotificationsApiService server. - """ - return request, metadata - - def post_create_notification_subscription(self, response: notificationsapi.NotificationSubscription) -> notificationsapi.NotificationSubscription: - """Post-rpc interceptor for create_notification_subscription - - Override in a subclass to manipulate the response - after it is returned by the NotificationsApiService server but before - it is returned to user code. - """ - return response - - def pre_delete_notification_subscription(self, request: notificationsapi.DeleteNotificationSubscriptionRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[notificationsapi.DeleteNotificationSubscriptionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_notification_subscription - - Override in a subclass to manipulate the request or metadata - before they are sent to the NotificationsApiService server. - """ - return request, metadata - - def pre_get_notification_subscription(self, request: notificationsapi.GetNotificationSubscriptionRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[notificationsapi.GetNotificationSubscriptionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_notification_subscription - - Override in a subclass to manipulate the request or metadata - before they are sent to the NotificationsApiService server. - """ - return request, metadata - - def post_get_notification_subscription(self, response: notificationsapi.NotificationSubscription) -> notificationsapi.NotificationSubscription: - """Post-rpc interceptor for get_notification_subscription - - Override in a subclass to manipulate the response - after it is returned by the NotificationsApiService server but before - it is returned to user code. - """ - return response - - def pre_list_notification_subscriptions(self, request: notificationsapi.ListNotificationSubscriptionsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[notificationsapi.ListNotificationSubscriptionsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_notification_subscriptions - - Override in a subclass to manipulate the request or metadata - before they are sent to the NotificationsApiService server. - """ - return request, metadata - - def post_list_notification_subscriptions(self, response: notificationsapi.ListNotificationSubscriptionsResponse) -> notificationsapi.ListNotificationSubscriptionsResponse: - """Post-rpc interceptor for list_notification_subscriptions - - Override in a subclass to manipulate the response - after it is returned by the NotificationsApiService server but before - it is returned to user code. - """ - return response - - def pre_update_notification_subscription(self, request: notificationsapi.UpdateNotificationSubscriptionRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[notificationsapi.UpdateNotificationSubscriptionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for update_notification_subscription - - Override in a subclass to manipulate the request or metadata - before they are sent to the NotificationsApiService server. - """ - return request, metadata - - def post_update_notification_subscription(self, response: notificationsapi.NotificationSubscription) -> notificationsapi.NotificationSubscription: - """Post-rpc interceptor for update_notification_subscription - - Override in a subclass to manipulate the response - after it is returned by the NotificationsApiService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class NotificationsApiServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: NotificationsApiServiceRestInterceptor - - -class NotificationsApiServiceRestTransport(_BaseNotificationsApiServiceRestTransport): - """REST backend synchronous transport for NotificationsApiService. - - Service to manage notification subscriptions for merchants - - This 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[NotificationsApiServiceRestInterceptor] = 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 NotificationsApiServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _CreateNotificationSubscription(_BaseNotificationsApiServiceRestTransport._BaseCreateNotificationSubscription, NotificationsApiServiceRestStub): - def __hash__(self): - return hash("NotificationsApiServiceRestTransport.CreateNotificationSubscription") - - @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: notificationsapi.CreateNotificationSubscriptionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> notificationsapi.NotificationSubscription: - r"""Call the create notification - subscription method over HTTP. - - Args: - request (~.notificationsapi.CreateNotificationSubscriptionRequest): - The request object. Request message for the - CreateNotificationSubscription method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.notificationsapi.NotificationSubscription: - Represents a notification - subscription owned by a Merchant - account. - - """ - - http_options = _BaseNotificationsApiServiceRestTransport._BaseCreateNotificationSubscription._get_http_options() - - request, metadata = self._interceptor.pre_create_notification_subscription(request, metadata) - transcoded_request = _BaseNotificationsApiServiceRestTransport._BaseCreateNotificationSubscription._get_transcoded_request(http_options, request) - - body = _BaseNotificationsApiServiceRestTransport._BaseCreateNotificationSubscription._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseNotificationsApiServiceRestTransport._BaseCreateNotificationSubscription._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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.notifications_v1beta.NotificationsApiServiceClient.CreateNotificationSubscription", - extra = { - "serviceName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", - "rpcName": "CreateNotificationSubscription", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = NotificationsApiServiceRestTransport._CreateNotificationSubscription._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 = notificationsapi.NotificationSubscription() - pb_resp = notificationsapi.NotificationSubscription.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_create_notification_subscription(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = notificationsapi.NotificationSubscription.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.notifications_v1beta.NotificationsApiServiceClient.create_notification_subscription", - extra = { - "serviceName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", - "rpcName": "CreateNotificationSubscription", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _DeleteNotificationSubscription(_BaseNotificationsApiServiceRestTransport._BaseDeleteNotificationSubscription, NotificationsApiServiceRestStub): - def __hash__(self): - return hash("NotificationsApiServiceRestTransport.DeleteNotificationSubscription") - - @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: notificationsapi.DeleteNotificationSubscriptionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ): - r"""Call the delete notification - subscription method over HTTP. - - Args: - request (~.notificationsapi.DeleteNotificationSubscriptionRequest): - The request object. Request message for the - DeleteNotificationSubscription method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, 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 = _BaseNotificationsApiServiceRestTransport._BaseDeleteNotificationSubscription._get_http_options() - - request, metadata = self._interceptor.pre_delete_notification_subscription(request, metadata) - transcoded_request = _BaseNotificationsApiServiceRestTransport._BaseDeleteNotificationSubscription._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseNotificationsApiServiceRestTransport._BaseDeleteNotificationSubscription._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(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.notifications_v1beta.NotificationsApiServiceClient.DeleteNotificationSubscription", - extra = { - "serviceName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", - "rpcName": "DeleteNotificationSubscription", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = NotificationsApiServiceRestTransport._DeleteNotificationSubscription._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 _GetNotificationSubscription(_BaseNotificationsApiServiceRestTransport._BaseGetNotificationSubscription, NotificationsApiServiceRestStub): - def __hash__(self): - return hash("NotificationsApiServiceRestTransport.GetNotificationSubscription") - - @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: notificationsapi.GetNotificationSubscriptionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> notificationsapi.NotificationSubscription: - r"""Call the get notification - subscription method over HTTP. - - Args: - request (~.notificationsapi.GetNotificationSubscriptionRequest): - The request object. Request message for the - GetNotificationSubscription method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.notificationsapi.NotificationSubscription: - Represents a notification - subscription owned by a Merchant - account. - - """ - - http_options = _BaseNotificationsApiServiceRestTransport._BaseGetNotificationSubscription._get_http_options() - - request, metadata = self._interceptor.pre_get_notification_subscription(request, metadata) - transcoded_request = _BaseNotificationsApiServiceRestTransport._BaseGetNotificationSubscription._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseNotificationsApiServiceRestTransport._BaseGetNotificationSubscription._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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.notifications_v1beta.NotificationsApiServiceClient.GetNotificationSubscription", - extra = { - "serviceName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", - "rpcName": "GetNotificationSubscription", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = NotificationsApiServiceRestTransport._GetNotificationSubscription._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 = notificationsapi.NotificationSubscription() - pb_resp = notificationsapi.NotificationSubscription.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_notification_subscription(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = notificationsapi.NotificationSubscription.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.notifications_v1beta.NotificationsApiServiceClient.get_notification_subscription", - extra = { - "serviceName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", - "rpcName": "GetNotificationSubscription", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListNotificationSubscriptions(_BaseNotificationsApiServiceRestTransport._BaseListNotificationSubscriptions, NotificationsApiServiceRestStub): - def __hash__(self): - return hash("NotificationsApiServiceRestTransport.ListNotificationSubscriptions") - - @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: notificationsapi.ListNotificationSubscriptionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> notificationsapi.ListNotificationSubscriptionsResponse: - r"""Call the list notification - subscriptions method over HTTP. - - Args: - request (~.notificationsapi.ListNotificationSubscriptionsRequest): - The request object. Request message for the - ListNotificationSubscription method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.notificationsapi.ListNotificationSubscriptionsResponse: - Response message for the - ListNotificationSubscription method. - - """ - - http_options = _BaseNotificationsApiServiceRestTransport._BaseListNotificationSubscriptions._get_http_options() - - request, metadata = self._interceptor.pre_list_notification_subscriptions(request, metadata) - transcoded_request = _BaseNotificationsApiServiceRestTransport._BaseListNotificationSubscriptions._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseNotificationsApiServiceRestTransport._BaseListNotificationSubscriptions._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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.notifications_v1beta.NotificationsApiServiceClient.ListNotificationSubscriptions", - extra = { - "serviceName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", - "rpcName": "ListNotificationSubscriptions", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = NotificationsApiServiceRestTransport._ListNotificationSubscriptions._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 = notificationsapi.ListNotificationSubscriptionsResponse() - pb_resp = notificationsapi.ListNotificationSubscriptionsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_notification_subscriptions(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = notificationsapi.ListNotificationSubscriptionsResponse.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.notifications_v1beta.NotificationsApiServiceClient.list_notification_subscriptions", - extra = { - "serviceName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", - "rpcName": "ListNotificationSubscriptions", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UpdateNotificationSubscription(_BaseNotificationsApiServiceRestTransport._BaseUpdateNotificationSubscription, NotificationsApiServiceRestStub): - def __hash__(self): - return hash("NotificationsApiServiceRestTransport.UpdateNotificationSubscription") - - @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: notificationsapi.UpdateNotificationSubscriptionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> notificationsapi.NotificationSubscription: - r"""Call the update notification - subscription method over HTTP. - - Args: - request (~.notificationsapi.UpdateNotificationSubscriptionRequest): - The request object. Request message for the - UpdateNotificationSubscription method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.notificationsapi.NotificationSubscription: - Represents a notification - subscription owned by a Merchant - account. - - """ - - http_options = _BaseNotificationsApiServiceRestTransport._BaseUpdateNotificationSubscription._get_http_options() - - request, metadata = self._interceptor.pre_update_notification_subscription(request, metadata) - transcoded_request = _BaseNotificationsApiServiceRestTransport._BaseUpdateNotificationSubscription._get_transcoded_request(http_options, request) - - body = _BaseNotificationsApiServiceRestTransport._BaseUpdateNotificationSubscription._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseNotificationsApiServiceRestTransport._BaseUpdateNotificationSubscription._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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.notifications_v1beta.NotificationsApiServiceClient.UpdateNotificationSubscription", - extra = { - "serviceName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", - "rpcName": "UpdateNotificationSubscription", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = NotificationsApiServiceRestTransport._UpdateNotificationSubscription._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 = notificationsapi.NotificationSubscription() - pb_resp = notificationsapi.NotificationSubscription.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_update_notification_subscription(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = notificationsapi.NotificationSubscription.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.notifications_v1beta.NotificationsApiServiceClient.update_notification_subscription", - extra = { - "serviceName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", - "rpcName": "UpdateNotificationSubscription", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def create_notification_subscription(self) -> Callable[ - [notificationsapi.CreateNotificationSubscriptionRequest], - notificationsapi.NotificationSubscription]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateNotificationSubscription(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_notification_subscription(self) -> Callable[ - [notificationsapi.DeleteNotificationSubscriptionRequest], - 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._DeleteNotificationSubscription(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_notification_subscription(self) -> Callable[ - [notificationsapi.GetNotificationSubscriptionRequest], - notificationsapi.NotificationSubscription]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetNotificationSubscription(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_notification_subscriptions(self) -> Callable[ - [notificationsapi.ListNotificationSubscriptionsRequest], - notificationsapi.ListNotificationSubscriptionsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListNotificationSubscriptions(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_notification_subscription(self) -> Callable[ - [notificationsapi.UpdateNotificationSubscriptionRequest], - notificationsapi.NotificationSubscription]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateNotificationSubscription(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'NotificationsApiServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/rest_base.py deleted file mode 100644 index b49003310c84..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/rest_base.py +++ /dev/null @@ -1,297 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 NotificationsApiServiceTransport, 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_notifications_v1beta.types import notificationsapi - - -class _BaseNotificationsApiServiceRestTransport(NotificationsApiServiceTransport): - """Base REST backend transport for NotificationsApiService. - - 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 _BaseCreateNotificationSubscription: - 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': '/notifications/v1beta/{parent=accounts/*}/notificationsubscriptions', - 'body': 'notification_subscription', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = notificationsapi.CreateNotificationSubscriptionRequest.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(_BaseNotificationsApiServiceRestTransport._BaseCreateNotificationSubscription._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteNotificationSubscription: - 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': '/notifications/v1beta/{name=accounts/*/notificationsubscriptions/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = notificationsapi.DeleteNotificationSubscriptionRequest.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(_BaseNotificationsApiServiceRestTransport._BaseDeleteNotificationSubscription._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetNotificationSubscription: - 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': '/notifications/v1beta/{name=accounts/*/notificationsubscriptions/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = notificationsapi.GetNotificationSubscriptionRequest.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(_BaseNotificationsApiServiceRestTransport._BaseGetNotificationSubscription._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListNotificationSubscriptions: - 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': '/notifications/v1beta/{parent=accounts/*}/notificationsubscriptions', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = notificationsapi.ListNotificationSubscriptionsRequest.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(_BaseNotificationsApiServiceRestTransport._BaseListNotificationSubscriptions._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateNotificationSubscription: - 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': '/notifications/v1beta/{notification_subscription.name=accounts/*/notificationsubscriptions/*}', - 'body': 'notification_subscription', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = notificationsapi.UpdateNotificationSubscriptionRequest.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(_BaseNotificationsApiServiceRestTransport._BaseUpdateNotificationSubscription._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseNotificationsApiServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/types/__init__.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/types/__init__.py deleted file mode 100644 index a24323759992..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/types/__init__.py +++ /dev/null @@ -1,42 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .notificationsapi import ( - CreateNotificationSubscriptionRequest, - DeleteNotificationSubscriptionRequest, - GetNotificationSubscriptionRequest, - ListNotificationSubscriptionsRequest, - ListNotificationSubscriptionsResponse, - NotificationSubscription, - ProductChange, - ProductStatusChangeMessage, - UpdateNotificationSubscriptionRequest, - Attribute, - Resource, -) - -__all__ = ( - 'CreateNotificationSubscriptionRequest', - 'DeleteNotificationSubscriptionRequest', - 'GetNotificationSubscriptionRequest', - 'ListNotificationSubscriptionsRequest', - 'ListNotificationSubscriptionsResponse', - 'NotificationSubscription', - 'ProductChange', - 'ProductStatusChangeMessage', - 'UpdateNotificationSubscriptionRequest', - 'Attribute', - 'Resource', -) diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/types/notificationsapi.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/types/notificationsapi.py deleted file mode 100644 index b28be34db58d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/types/notificationsapi.py +++ /dev/null @@ -1,424 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.notifications.v1beta', - manifest={ - 'Resource', - 'Attribute', - 'GetNotificationSubscriptionRequest', - 'CreateNotificationSubscriptionRequest', - 'UpdateNotificationSubscriptionRequest', - 'DeleteNotificationSubscriptionRequest', - 'ListNotificationSubscriptionsRequest', - 'ListNotificationSubscriptionsResponse', - 'NotificationSubscription', - 'ProductChange', - 'ProductStatusChangeMessage', - }, -) - - -class Resource(proto.Enum): - r"""Enum to specify the resource that is being changed to notify - the merchant about. - - Values: - RESOURCE_UNSPECIFIED (0): - Unspecified resource - PRODUCT (1): - Resource type : product - """ - RESOURCE_UNSPECIFIED = 0 - PRODUCT = 1 - - -class Attribute(proto.Enum): - r"""Enum to specify the attribute in the resource that is being - changed to notify the merchant about. - - Values: - ATTRIBUTE_UNSPECIFIED (0): - Unspecified attribute - STATUS (1): - Status of the changed entity - """ - ATTRIBUTE_UNSPECIFIED = 0 - STATUS = 1 - - -class GetNotificationSubscriptionRequest(proto.Message): - r"""Request message for the GetNotificationSubscription method. - - Attributes: - name (str): - Required. The ``name`` of the notification subscription. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateNotificationSubscriptionRequest(proto.Message): - r"""Request message for the CreateNotificationSubscription - method. - - Attributes: - parent (str): - Required. The merchant account that owns the new - notification subscription. Format: ``accounts/{account}`` - notification_subscription (google.shopping.merchant_notifications_v1beta.types.NotificationSubscription): - Required. The notification subscription to - create. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - notification_subscription: 'NotificationSubscription' = proto.Field( - proto.MESSAGE, - number=2, - message='NotificationSubscription', - ) - - -class UpdateNotificationSubscriptionRequest(proto.Message): - r"""Request message for the UpdateNotificationSubscription - method. - - Attributes: - notification_subscription (google.shopping.merchant_notifications_v1beta.types.NotificationSubscription): - Required. The new version of the notification - subscription that should be updated. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - List of fields being updated. - """ - - notification_subscription: 'NotificationSubscription' = proto.Field( - proto.MESSAGE, - number=1, - message='NotificationSubscription', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteNotificationSubscriptionRequest(proto.Message): - r"""Request message for the DeleteNotificationSubscription - method. - - Attributes: - name (str): - Required. The name of the notification - subscription to be deleted. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListNotificationSubscriptionsRequest(proto.Message): - r"""Request message for the ListNotificationSubscription method. - - Attributes: - parent (str): - Required. The merchant account who owns the notification - subscriptions. Format: ``accounts/{account}`` - page_size (int): - The maximum number of notification subscriptions to return - in a page. The default value for ``page_size`` is 100. The - maximum value is ``200``. Values above ``200`` will be - coerced to ``200``. - page_token (str): - Token (if provided) to retrieve the - subsequent page. All other parameters must match - the original 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 ListNotificationSubscriptionsResponse(proto.Message): - r"""Response message for the ListNotificationSubscription method. - - Attributes: - notification_subscriptions (MutableSequence[google.shopping.merchant_notifications_v1beta.types.NotificationSubscription]): - The list of notification subscriptions - requested by the 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 - - notification_subscriptions: MutableSequence['NotificationSubscription'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='NotificationSubscription', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class NotificationSubscription(proto.Message): - r"""Represents a notification subscription owned by a Merchant - account. - - 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: - all_managed_accounts (bool): - If this value is true, the requesting account - is notified of the specified event for all - managed accounts (can be subaccounts or other - linked accounts) including newly added accounts - on a daily basis. - - This field is a member of `oneof`_ ``interested_in``. - target_account (str): - The ``name`` of the account you want to receive - notifications for. Format: ``accounts/{account}`` - - This field is a member of `oneof`_ ``interested_in``. - name (str): - Output only. The ``name`` of the notification configuration. - Generated by the Content API upon creation of a new - ``NotificationSubscription``. The ``account`` represents the - merchant ID of the merchant that owns the configuration. - Format: - ``accounts/{account}/notificationsubscriptions/{notification_subscription}`` - registered_event (google.shopping.merchant_notifications_v1beta.types.NotificationSubscription.NotificationEventType): - The event that the merchant wants to be - notified about. - call_back_uri (str): - URL to be used to push the notification to - the merchant. - """ - class NotificationEventType(proto.Enum): - r"""Represents the event type that the merchant is interested in - receiving notifications for. - - Values: - NOTIFICATION_EVENT_TYPE_UNSPECIFIED (0): - Notifications event type is unspecified. - PRODUCT_STATUS_CHANGE (1): - Notification of product status changes, for - example when product becomes disapproved. - """ - NOTIFICATION_EVENT_TYPE_UNSPECIFIED = 0 - PRODUCT_STATUS_CHANGE = 1 - - all_managed_accounts: bool = proto.Field( - proto.BOOL, - number=3, - oneof='interested_in', - ) - target_account: str = proto.Field( - proto.STRING, - number=4, - oneof='interested_in', - ) - name: str = proto.Field( - proto.STRING, - number=1, - ) - registered_event: NotificationEventType = proto.Field( - proto.ENUM, - number=2, - enum=NotificationEventType, - ) - call_back_uri: str = proto.Field( - proto.STRING, - number=5, - ) - - -class ProductChange(proto.Message): - r"""The change that happened to the product including old value, - new value, country code as the region code and reporting - context. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - old_value (str): - The old value of the changed resource or - attribute. - - This field is a member of `oneof`_ ``_old_value``. - new_value (str): - The new value of the changed resource or - attribute. - - This field is a member of `oneof`_ ``_new_value``. - region_code (str): - Countries that have the change (if - applicable) - - This field is a member of `oneof`_ ``_region_code``. - reporting_context (google.shopping.type.types.ReportingContext.ReportingContextEnum): - Reporting contexts that have the change (if - applicable) - - This field is a member of `oneof`_ ``_reporting_context``. - """ - - old_value: str = proto.Field( - proto.STRING, - number=1, - optional=True, - ) - new_value: str = proto.Field( - proto.STRING, - number=2, - optional=True, - ) - region_code: str = proto.Field( - proto.STRING, - number=3, - optional=True, - ) - reporting_context: types.ReportingContext.ReportingContextEnum = proto.Field( - proto.ENUM, - number=4, - optional=True, - enum=types.ReportingContext.ReportingContextEnum, - ) - - -class ProductStatusChangeMessage(proto.Message): - r"""The message that the merchant will receive to notify about - product status change event - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - account (str): - The target account that owns the entity that changed. Format - : ``accounts/{merchant_id}`` - - This field is a member of `oneof`_ ``_account``. - managing_account (str): - The account that manages the merchant's account. can be the - same as merchant id if it is standalone account. Format : - ``accounts/{service_provider_id}`` - - This field is a member of `oneof`_ ``_managing_account``. - resource_type (google.shopping.merchant_notifications_v1beta.types.Resource): - The resource that changed, in this case it will always be - ``Product``. - - This field is a member of `oneof`_ ``_resource_type``. - attribute (google.shopping.merchant_notifications_v1beta.types.Attribute): - The attribute in the resource that changed, in this case it - will be always ``Status``. - - This field is a member of `oneof`_ ``_attribute``. - changes (MutableSequence[google.shopping.merchant_notifications_v1beta.types.ProductChange]): - A message to describe the change that - happened to the product - resource_id (str): - The product id. - - This field is a member of `oneof`_ ``_resource_id``. - resource (str): - The product name. Format: - ``{product.name=accounts/{account}/products/{product}}`` - - This field is a member of `oneof`_ ``_resource``. - """ - - account: str = proto.Field( - proto.STRING, - number=1, - optional=True, - ) - managing_account: str = proto.Field( - proto.STRING, - number=2, - optional=True, - ) - resource_type: 'Resource' = proto.Field( - proto.ENUM, - number=3, - optional=True, - enum='Resource', - ) - attribute: 'Attribute' = proto.Field( - proto.ENUM, - number=4, - optional=True, - enum='Attribute', - ) - changes: MutableSequence['ProductChange'] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message='ProductChange', - ) - resource_id: str = proto.Field( - proto.STRING, - number=6, - optional=True, - ) - resource: str = proto.Field( - proto.STRING, - number=7, - optional=True, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/mypy.ini b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/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-notifications/v1beta/noxfile.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/noxfile.py deleted file mode 100644 index 486d3948542f..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/noxfile.py +++ /dev/null @@ -1,280 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", - "3.12", - "3.13", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = 'google-shopping-merchant-notifications' - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.13" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "prerelease_deps", -] - -@nox.session(python=ALL_PYTHON) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def unit(session, protobuf_implementation): - """Run the unit test suite.""" - - 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+") - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") - - # 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") - - session.run( - 'py.test', - '--quiet', - '--cov=google/shopping/merchant_notifications_v1beta/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - -@nox.session(python=ALL_PYTHON[-1]) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def prerelease_deps(session, protobuf_implementation): - """Run the unit test suite against pre-release versions of dependencies.""" - - 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 test environment dependencies - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - - # Install the package without dependencies - session.install('-e', '.', '--no-deps') - - # We test the minimum dependency versions using the minimum Python - # version so the lowest python runtime that we test has a corresponding constraints - # file, located at `testing/constraints--.txt`, which contains all of the - # 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 - ) - ] - - session.install(*constraints_deps) - - prerel_deps = [ - "googleapis-common-protos", - "google-api-core", - "google-auth", - # Exclude grpcio!=1.67.0rc1 which does not support python 3.13 - "grpcio!=1.67.0rc1", - "grpcio-status", - "protobuf", - "proto-plus", - ] - - for dep in prerel_deps: - session.install("--pre", "--no-deps", "--upgrade", dep) - - # Remaining dependencies - other_deps = [ - "requests", - ] - session.install(*other_deps) - - # Print out prerelease package versions - - session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") - session.run("python", "-c", "import google.auth; print(google.auth.__version__)") - session.run("python", "-c", "import grpc; print(grpc.__version__)") - session.run( - "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" - ) - session.run( - "python", "-c", "import proto; print(proto.__version__)" - ) - - session.run( - 'py.test', - '--quiet', - '--cov=google/shopping/merchant_notifications_v1beta/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - - -@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=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 docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==7.0.1", "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=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", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_create_notification_subscription_async.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_create_notification_subscription_async.py deleted file mode 100644 index 11afd393a147..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_create_notification_subscription_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateNotificationSubscription -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-notifications - - -# [START merchantapi_v1beta_generated_NotificationsApiService_CreateNotificationSubscription_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_notifications_v1beta - - -async def sample_create_notification_subscription(): - # Create a client - client = merchant_notifications_v1beta.NotificationsApiServiceAsyncClient() - - # Initialize request argument(s) - notification_subscription = merchant_notifications_v1beta.NotificationSubscription() - notification_subscription.all_managed_accounts = True - - request = merchant_notifications_v1beta.CreateNotificationSubscriptionRequest( - parent="parent_value", - notification_subscription=notification_subscription, - ) - - # Make the request - response = await client.create_notification_subscription(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_NotificationsApiService_CreateNotificationSubscription_async] diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_create_notification_subscription_sync.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_create_notification_subscription_sync.py deleted file mode 100644 index af214ecce4e1..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_create_notification_subscription_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateNotificationSubscription -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-notifications - - -# [START merchantapi_v1beta_generated_NotificationsApiService_CreateNotificationSubscription_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_notifications_v1beta - - -def sample_create_notification_subscription(): - # Create a client - client = merchant_notifications_v1beta.NotificationsApiServiceClient() - - # Initialize request argument(s) - notification_subscription = merchant_notifications_v1beta.NotificationSubscription() - notification_subscription.all_managed_accounts = True - - request = merchant_notifications_v1beta.CreateNotificationSubscriptionRequest( - parent="parent_value", - notification_subscription=notification_subscription, - ) - - # Make the request - response = client.create_notification_subscription(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_NotificationsApiService_CreateNotificationSubscription_sync] diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_delete_notification_subscription_async.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_delete_notification_subscription_async.py deleted file mode 100644 index 575ba1c51c3f..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_delete_notification_subscription_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteNotificationSubscription -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-notifications - - -# [START merchantapi_v1beta_generated_NotificationsApiService_DeleteNotificationSubscription_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_notifications_v1beta - - -async def sample_delete_notification_subscription(): - # Create a client - client = merchant_notifications_v1beta.NotificationsApiServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_notifications_v1beta.DeleteNotificationSubscriptionRequest( - name="name_value", - ) - - # Make the request - await client.delete_notification_subscription(request=request) - - -# [END merchantapi_v1beta_generated_NotificationsApiService_DeleteNotificationSubscription_async] diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_delete_notification_subscription_sync.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_delete_notification_subscription_sync.py deleted file mode 100644 index 32cbbdca5280..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_delete_notification_subscription_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteNotificationSubscription -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-notifications - - -# [START merchantapi_v1beta_generated_NotificationsApiService_DeleteNotificationSubscription_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_notifications_v1beta - - -def sample_delete_notification_subscription(): - # Create a client - client = merchant_notifications_v1beta.NotificationsApiServiceClient() - - # Initialize request argument(s) - request = merchant_notifications_v1beta.DeleteNotificationSubscriptionRequest( - name="name_value", - ) - - # Make the request - client.delete_notification_subscription(request=request) - - -# [END merchantapi_v1beta_generated_NotificationsApiService_DeleteNotificationSubscription_sync] diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_get_notification_subscription_async.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_get_notification_subscription_async.py deleted file mode 100644 index 620d1dbcba47..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_get_notification_subscription_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetNotificationSubscription -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-notifications - - -# [START merchantapi_v1beta_generated_NotificationsApiService_GetNotificationSubscription_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_notifications_v1beta - - -async def sample_get_notification_subscription(): - # Create a client - client = merchant_notifications_v1beta.NotificationsApiServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_notifications_v1beta.GetNotificationSubscriptionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_notification_subscription(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_NotificationsApiService_GetNotificationSubscription_async] diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_get_notification_subscription_sync.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_get_notification_subscription_sync.py deleted file mode 100644 index b51236045fda..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_get_notification_subscription_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetNotificationSubscription -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-notifications - - -# [START merchantapi_v1beta_generated_NotificationsApiService_GetNotificationSubscription_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_notifications_v1beta - - -def sample_get_notification_subscription(): - # Create a client - client = merchant_notifications_v1beta.NotificationsApiServiceClient() - - # Initialize request argument(s) - request = merchant_notifications_v1beta.GetNotificationSubscriptionRequest( - name="name_value", - ) - - # Make the request - response = client.get_notification_subscription(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_NotificationsApiService_GetNotificationSubscription_sync] diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_list_notification_subscriptions_async.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_list_notification_subscriptions_async.py deleted file mode 100644 index 58b97c1734ab..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_list_notification_subscriptions_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListNotificationSubscriptions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-notifications - - -# [START merchantapi_v1beta_generated_NotificationsApiService_ListNotificationSubscriptions_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_notifications_v1beta - - -async def sample_list_notification_subscriptions(): - # Create a client - client = merchant_notifications_v1beta.NotificationsApiServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_notifications_v1beta.ListNotificationSubscriptionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_notification_subscriptions(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_NotificationsApiService_ListNotificationSubscriptions_async] diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_list_notification_subscriptions_sync.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_list_notification_subscriptions_sync.py deleted file mode 100644 index 54b882cffe95..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_list_notification_subscriptions_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListNotificationSubscriptions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-notifications - - -# [START merchantapi_v1beta_generated_NotificationsApiService_ListNotificationSubscriptions_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_notifications_v1beta - - -def sample_list_notification_subscriptions(): - # Create a client - client = merchant_notifications_v1beta.NotificationsApiServiceClient() - - # Initialize request argument(s) - request = merchant_notifications_v1beta.ListNotificationSubscriptionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_notification_subscriptions(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_NotificationsApiService_ListNotificationSubscriptions_sync] diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_update_notification_subscription_async.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_update_notification_subscription_async.py deleted file mode 100644 index cf8732747efe..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_update_notification_subscription_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateNotificationSubscription -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-notifications - - -# [START merchantapi_v1beta_generated_NotificationsApiService_UpdateNotificationSubscription_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_notifications_v1beta - - -async def sample_update_notification_subscription(): - # Create a client - client = merchant_notifications_v1beta.NotificationsApiServiceAsyncClient() - - # Initialize request argument(s) - notification_subscription = merchant_notifications_v1beta.NotificationSubscription() - notification_subscription.all_managed_accounts = True - - request = merchant_notifications_v1beta.UpdateNotificationSubscriptionRequest( - notification_subscription=notification_subscription, - ) - - # Make the request - response = await client.update_notification_subscription(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_NotificationsApiService_UpdateNotificationSubscription_async] diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_update_notification_subscription_sync.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_update_notification_subscription_sync.py deleted file mode 100644 index e921cd95cc4c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/merchantapi_v1beta_generated_notifications_api_service_update_notification_subscription_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateNotificationSubscription -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-notifications - - -# [START merchantapi_v1beta_generated_NotificationsApiService_UpdateNotificationSubscription_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_notifications_v1beta - - -def sample_update_notification_subscription(): - # Create a client - client = merchant_notifications_v1beta.NotificationsApiServiceClient() - - # Initialize request argument(s) - notification_subscription = merchant_notifications_v1beta.NotificationSubscription() - notification_subscription.all_managed_accounts = True - - request = merchant_notifications_v1beta.UpdateNotificationSubscriptionRequest( - notification_subscription=notification_subscription, - ) - - # Make the request - response = client.update_notification_subscription(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_NotificationsApiService_UpdateNotificationSubscription_sync] diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.notifications.v1beta.json b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.notifications.v1beta.json deleted file mode 100644 index b27b3eb2144a..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.notifications.v1beta.json +++ /dev/null @@ -1,830 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.shopping.merchant.notifications.v1beta", - "version": "v1beta" - } - ], - "language": "PYTHON", - "name": "google-shopping-merchant-notifications", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_notifications_v1beta.NotificationsApiServiceAsyncClient", - "shortName": "NotificationsApiServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_notifications_v1beta.NotificationsApiServiceAsyncClient.create_notification_subscription", - "method": { - "fullName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService.CreateNotificationSubscription", - "service": { - "fullName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", - "shortName": "NotificationsApiService" - }, - "shortName": "CreateNotificationSubscription" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_notifications_v1beta.types.CreateNotificationSubscriptionRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "notification_subscription", - "type": "google.shopping.merchant_notifications_v1beta.types.NotificationSubscription" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.shopping.merchant_notifications_v1beta.types.NotificationSubscription", - "shortName": "create_notification_subscription" - }, - "description": "Sample for CreateNotificationSubscription", - "file": "merchantapi_v1beta_generated_notifications_api_service_create_notification_subscription_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_NotificationsApiService_CreateNotificationSubscription_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_notifications_api_service_create_notification_subscription_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_notifications_v1beta.NotificationsApiServiceClient", - "shortName": "NotificationsApiServiceClient" - }, - "fullName": "google.shopping.merchant_notifications_v1beta.NotificationsApiServiceClient.create_notification_subscription", - "method": { - "fullName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService.CreateNotificationSubscription", - "service": { - "fullName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", - "shortName": "NotificationsApiService" - }, - "shortName": "CreateNotificationSubscription" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_notifications_v1beta.types.CreateNotificationSubscriptionRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "notification_subscription", - "type": "google.shopping.merchant_notifications_v1beta.types.NotificationSubscription" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.shopping.merchant_notifications_v1beta.types.NotificationSubscription", - "shortName": "create_notification_subscription" - }, - "description": "Sample for CreateNotificationSubscription", - "file": "merchantapi_v1beta_generated_notifications_api_service_create_notification_subscription_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_NotificationsApiService_CreateNotificationSubscription_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_notifications_api_service_create_notification_subscription_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_notifications_v1beta.NotificationsApiServiceAsyncClient", - "shortName": "NotificationsApiServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_notifications_v1beta.NotificationsApiServiceAsyncClient.delete_notification_subscription", - "method": { - "fullName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService.DeleteNotificationSubscription", - "service": { - "fullName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", - "shortName": "NotificationsApiService" - }, - "shortName": "DeleteNotificationSubscription" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_notifications_v1beta.types.DeleteNotificationSubscriptionRequest" - }, - { - "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_notification_subscription" - }, - "description": "Sample for DeleteNotificationSubscription", - "file": "merchantapi_v1beta_generated_notifications_api_service_delete_notification_subscription_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_NotificationsApiService_DeleteNotificationSubscription_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_notifications_api_service_delete_notification_subscription_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_notifications_v1beta.NotificationsApiServiceClient", - "shortName": "NotificationsApiServiceClient" - }, - "fullName": "google.shopping.merchant_notifications_v1beta.NotificationsApiServiceClient.delete_notification_subscription", - "method": { - "fullName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService.DeleteNotificationSubscription", - "service": { - "fullName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", - "shortName": "NotificationsApiService" - }, - "shortName": "DeleteNotificationSubscription" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_notifications_v1beta.types.DeleteNotificationSubscriptionRequest" - }, - { - "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_notification_subscription" - }, - "description": "Sample for DeleteNotificationSubscription", - "file": "merchantapi_v1beta_generated_notifications_api_service_delete_notification_subscription_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_NotificationsApiService_DeleteNotificationSubscription_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_notifications_api_service_delete_notification_subscription_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_notifications_v1beta.NotificationsApiServiceAsyncClient", - "shortName": "NotificationsApiServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_notifications_v1beta.NotificationsApiServiceAsyncClient.get_notification_subscription", - "method": { - "fullName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService.GetNotificationSubscription", - "service": { - "fullName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", - "shortName": "NotificationsApiService" - }, - "shortName": "GetNotificationSubscription" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_notifications_v1beta.types.GetNotificationSubscriptionRequest" - }, - { - "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_notifications_v1beta.types.NotificationSubscription", - "shortName": "get_notification_subscription" - }, - "description": "Sample for GetNotificationSubscription", - "file": "merchantapi_v1beta_generated_notifications_api_service_get_notification_subscription_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_NotificationsApiService_GetNotificationSubscription_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_notifications_api_service_get_notification_subscription_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_notifications_v1beta.NotificationsApiServiceClient", - "shortName": "NotificationsApiServiceClient" - }, - "fullName": "google.shopping.merchant_notifications_v1beta.NotificationsApiServiceClient.get_notification_subscription", - "method": { - "fullName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService.GetNotificationSubscription", - "service": { - "fullName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", - "shortName": "NotificationsApiService" - }, - "shortName": "GetNotificationSubscription" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_notifications_v1beta.types.GetNotificationSubscriptionRequest" - }, - { - "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_notifications_v1beta.types.NotificationSubscription", - "shortName": "get_notification_subscription" - }, - "description": "Sample for GetNotificationSubscription", - "file": "merchantapi_v1beta_generated_notifications_api_service_get_notification_subscription_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_NotificationsApiService_GetNotificationSubscription_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_notifications_api_service_get_notification_subscription_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_notifications_v1beta.NotificationsApiServiceAsyncClient", - "shortName": "NotificationsApiServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_notifications_v1beta.NotificationsApiServiceAsyncClient.list_notification_subscriptions", - "method": { - "fullName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService.ListNotificationSubscriptions", - "service": { - "fullName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", - "shortName": "NotificationsApiService" - }, - "shortName": "ListNotificationSubscriptions" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_notifications_v1beta.types.ListNotificationSubscriptionsRequest" - }, - { - "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_notifications_v1beta.services.notifications_api_service.pagers.ListNotificationSubscriptionsAsyncPager", - "shortName": "list_notification_subscriptions" - }, - "description": "Sample for ListNotificationSubscriptions", - "file": "merchantapi_v1beta_generated_notifications_api_service_list_notification_subscriptions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_NotificationsApiService_ListNotificationSubscriptions_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_notifications_api_service_list_notification_subscriptions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_notifications_v1beta.NotificationsApiServiceClient", - "shortName": "NotificationsApiServiceClient" - }, - "fullName": "google.shopping.merchant_notifications_v1beta.NotificationsApiServiceClient.list_notification_subscriptions", - "method": { - "fullName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService.ListNotificationSubscriptions", - "service": { - "fullName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", - "shortName": "NotificationsApiService" - }, - "shortName": "ListNotificationSubscriptions" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_notifications_v1beta.types.ListNotificationSubscriptionsRequest" - }, - { - "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_notifications_v1beta.services.notifications_api_service.pagers.ListNotificationSubscriptionsPager", - "shortName": "list_notification_subscriptions" - }, - "description": "Sample for ListNotificationSubscriptions", - "file": "merchantapi_v1beta_generated_notifications_api_service_list_notification_subscriptions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_NotificationsApiService_ListNotificationSubscriptions_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_notifications_api_service_list_notification_subscriptions_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_notifications_v1beta.NotificationsApiServiceAsyncClient", - "shortName": "NotificationsApiServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_notifications_v1beta.NotificationsApiServiceAsyncClient.update_notification_subscription", - "method": { - "fullName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService.UpdateNotificationSubscription", - "service": { - "fullName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", - "shortName": "NotificationsApiService" - }, - "shortName": "UpdateNotificationSubscription" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_notifications_v1beta.types.UpdateNotificationSubscriptionRequest" - }, - { - "name": "notification_subscription", - "type": "google.shopping.merchant_notifications_v1beta.types.NotificationSubscription" - }, - { - "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_notifications_v1beta.types.NotificationSubscription", - "shortName": "update_notification_subscription" - }, - "description": "Sample for UpdateNotificationSubscription", - "file": "merchantapi_v1beta_generated_notifications_api_service_update_notification_subscription_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_NotificationsApiService_UpdateNotificationSubscription_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_notifications_api_service_update_notification_subscription_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_notifications_v1beta.NotificationsApiServiceClient", - "shortName": "NotificationsApiServiceClient" - }, - "fullName": "google.shopping.merchant_notifications_v1beta.NotificationsApiServiceClient.update_notification_subscription", - "method": { - "fullName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService.UpdateNotificationSubscription", - "service": { - "fullName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", - "shortName": "NotificationsApiService" - }, - "shortName": "UpdateNotificationSubscription" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_notifications_v1beta.types.UpdateNotificationSubscriptionRequest" - }, - { - "name": "notification_subscription", - "type": "google.shopping.merchant_notifications_v1beta.types.NotificationSubscription" - }, - { - "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_notifications_v1beta.types.NotificationSubscription", - "shortName": "update_notification_subscription" - }, - "description": "Sample for UpdateNotificationSubscription", - "file": "merchantapi_v1beta_generated_notifications_api_service_update_notification_subscription_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_NotificationsApiService_UpdateNotificationSubscription_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_notifications_api_service_update_notification_subscription_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/scripts/fixup_merchant_notifications_v1beta_keywords.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/scripts/fixup_merchant_notifications_v1beta_keywords.py deleted file mode 100644 index d05f3b942dcb..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/scripts/fixup_merchant_notifications_v1beta_keywords.py +++ /dev/null @@ -1,180 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_notificationsCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_notification_subscription': ('parent', 'notification_subscription', ), - 'delete_notification_subscription': ('name', ), - 'get_notification_subscription': ('name', ), - 'list_notification_subscriptions': ('parent', 'page_size', 'page_token', ), - 'update_notification_subscription': ('notification_subscription', '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_notificationsCallTransformer(), -): - """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_notifications 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-notifications/v1beta/setup.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/setup.py deleted file mode 100644 index bac7d3ecd5e8..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/setup.py +++ /dev/null @@ -1,99 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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-notifications' - - -description = "Google Shopping Merchant Notifications API client library" - -version = None - -with open(os.path.join(package_root, 'google/shopping/merchant_notifications/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.0dev,!=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.0dev,!=2.24.0,!=2.25.0", - "proto-plus >= 1.22.3, <2.0.0dev", - "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'", - "protobuf>=3.20.2,<6.0.0dev,!=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.0dev", -] -extras = { -} -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-notifications" - -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-notifications/v1beta/testing/constraints-3.10.txt b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/testing/constraints-3.10.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/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-notifications/v1beta/testing/constraints-3.11.txt b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/testing/constraints-3.11.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/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-notifications/v1beta/testing/constraints-3.12.txt b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/testing/constraints-3.12.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/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-notifications/v1beta/testing/constraints-3.13.txt b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/testing/constraints-3.13.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/testing/constraints-3.13.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-notifications/v1beta/testing/constraints-3.7.txt b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/testing/constraints-3.7.txt deleted file mode 100644 index 130a0c0f80ab..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/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.0dev", -# 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-notifications/v1beta/testing/constraints-3.8.txt b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/testing/constraints-3.8.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/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-notifications/v1beta/testing/constraints-3.9.txt b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/testing/constraints-3.9.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/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-notifications/v1beta/tests/__init__.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-notifications/v1beta/tests/unit/__init__.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-notifications/v1beta/tests/unit/gapic/__init__.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-notifications/v1beta/tests/unit/gapic/merchant_notifications_v1beta/__init__.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/tests/unit/gapic/merchant_notifications_v1beta/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/tests/unit/gapic/merchant_notifications_v1beta/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-notifications/v1beta/tests/unit/gapic/merchant_notifications_v1beta/test_notifications_api_service.py b/owl-bot-staging/google-shopping-merchant-notifications/v1beta/tests/unit/gapic/merchant_notifications_v1beta/test_notifications_api_service.py deleted file mode 100644 index c7917334ffb9..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/tests/unit/gapic/merchant_notifications_v1beta/test_notifications_api_service.py +++ /dev/null @@ -1,5136 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_notifications_v1beta.services.notifications_api_service import NotificationsApiServiceAsyncClient -from google.shopping.merchant_notifications_v1beta.services.notifications_api_service import NotificationsApiServiceClient -from google.shopping.merchant_notifications_v1beta.services.notifications_api_service import pagers -from google.shopping.merchant_notifications_v1beta.services.notifications_api_service import transports -from google.shopping.merchant_notifications_v1beta.types import notificationsapi -import google.auth - - -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 NotificationsApiServiceClient._get_default_mtls_endpoint(None) is None - assert NotificationsApiServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert NotificationsApiServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert NotificationsApiServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert NotificationsApiServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert NotificationsApiServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert NotificationsApiServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert NotificationsApiServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert NotificationsApiServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - NotificationsApiServiceClient._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 NotificationsApiServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert NotificationsApiServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert NotificationsApiServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - NotificationsApiServiceClient._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 NotificationsApiServiceClient._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 NotificationsApiServiceClient._get_client_cert_source(None, False) is None - assert NotificationsApiServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert NotificationsApiServiceClient._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 NotificationsApiServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert NotificationsApiServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(NotificationsApiServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NotificationsApiServiceClient)) -@mock.patch.object(NotificationsApiServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NotificationsApiServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = NotificationsApiServiceClient._DEFAULT_UNIVERSE - default_endpoint = NotificationsApiServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = NotificationsApiServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert NotificationsApiServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert NotificationsApiServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == NotificationsApiServiceClient.DEFAULT_MTLS_ENDPOINT - assert NotificationsApiServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert NotificationsApiServiceClient._get_api_endpoint(None, None, default_universe, "always") == NotificationsApiServiceClient.DEFAULT_MTLS_ENDPOINT - assert NotificationsApiServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == NotificationsApiServiceClient.DEFAULT_MTLS_ENDPOINT - assert NotificationsApiServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert NotificationsApiServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - NotificationsApiServiceClient._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 NotificationsApiServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert NotificationsApiServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert NotificationsApiServiceClient._get_universe_domain(None, None) == NotificationsApiServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - NotificationsApiServiceClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - - -@pytest.mark.parametrize("client_class,transport_name", [ - (NotificationsApiServiceClient, "grpc"), - (NotificationsApiServiceAsyncClient, "grpc_asyncio"), - (NotificationsApiServiceClient, "rest"), -]) -def test_notifications_api_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.NotificationsApiServiceGrpcTransport, "grpc"), - (transports.NotificationsApiServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.NotificationsApiServiceRestTransport, "rest"), -]) -def test_notifications_api_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", [ - (NotificationsApiServiceClient, "grpc"), - (NotificationsApiServiceAsyncClient, "grpc_asyncio"), - (NotificationsApiServiceClient, "rest"), -]) -def test_notifications_api_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_notifications_api_service_client_get_transport_class(): - transport = NotificationsApiServiceClient.get_transport_class() - available_transports = [ - transports.NotificationsApiServiceGrpcTransport, - transports.NotificationsApiServiceRestTransport, - ] - assert transport in available_transports - - transport = NotificationsApiServiceClient.get_transport_class("grpc") - assert transport == transports.NotificationsApiServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (NotificationsApiServiceClient, transports.NotificationsApiServiceGrpcTransport, "grpc"), - (NotificationsApiServiceAsyncClient, transports.NotificationsApiServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (NotificationsApiServiceClient, transports.NotificationsApiServiceRestTransport, "rest"), -]) -@mock.patch.object(NotificationsApiServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NotificationsApiServiceClient)) -@mock.patch.object(NotificationsApiServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NotificationsApiServiceAsyncClient)) -def test_notifications_api_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(NotificationsApiServiceClient, '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(NotificationsApiServiceClient, '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", [ - (NotificationsApiServiceClient, transports.NotificationsApiServiceGrpcTransport, "grpc", "true"), - (NotificationsApiServiceAsyncClient, transports.NotificationsApiServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (NotificationsApiServiceClient, transports.NotificationsApiServiceGrpcTransport, "grpc", "false"), - (NotificationsApiServiceAsyncClient, transports.NotificationsApiServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (NotificationsApiServiceClient, transports.NotificationsApiServiceRestTransport, "rest", "true"), - (NotificationsApiServiceClient, transports.NotificationsApiServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(NotificationsApiServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NotificationsApiServiceClient)) -@mock.patch.object(NotificationsApiServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NotificationsApiServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_notifications_api_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", [ - NotificationsApiServiceClient, NotificationsApiServiceAsyncClient -]) -@mock.patch.object(NotificationsApiServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(NotificationsApiServiceClient)) -@mock.patch.object(NotificationsApiServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(NotificationsApiServiceAsyncClient)) -def test_notifications_api_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", [ - NotificationsApiServiceClient, NotificationsApiServiceAsyncClient -]) -@mock.patch.object(NotificationsApiServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NotificationsApiServiceClient)) -@mock.patch.object(NotificationsApiServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NotificationsApiServiceAsyncClient)) -def test_notifications_api_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = NotificationsApiServiceClient._DEFAULT_UNIVERSE - default_endpoint = NotificationsApiServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = NotificationsApiServiceClient._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", [ - (NotificationsApiServiceClient, transports.NotificationsApiServiceGrpcTransport, "grpc"), - (NotificationsApiServiceAsyncClient, transports.NotificationsApiServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (NotificationsApiServiceClient, transports.NotificationsApiServiceRestTransport, "rest"), -]) -def test_notifications_api_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", [ - (NotificationsApiServiceClient, transports.NotificationsApiServiceGrpcTransport, "grpc", grpc_helpers), - (NotificationsApiServiceAsyncClient, transports.NotificationsApiServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (NotificationsApiServiceClient, transports.NotificationsApiServiceRestTransport, "rest", None), -]) -def test_notifications_api_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_notifications_api_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_notifications_v1beta.services.notifications_api_service.transports.NotificationsApiServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = NotificationsApiServiceClient( - 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", [ - (NotificationsApiServiceClient, transports.NotificationsApiServiceGrpcTransport, "grpc", grpc_helpers), - (NotificationsApiServiceAsyncClient, transports.NotificationsApiServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_notifications_api_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", [ - notificationsapi.GetNotificationSubscriptionRequest, - dict, -]) -def test_get_notification_subscription(request_type, transport: str = 'grpc'): - client = NotificationsApiServiceClient( - 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_notification_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = notificationsapi.NotificationSubscription( - name='name_value', - registered_event=notificationsapi.NotificationSubscription.NotificationEventType.PRODUCT_STATUS_CHANGE, - call_back_uri='call_back_uri_value', - all_managed_accounts=True, - ) - response = client.get_notification_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = notificationsapi.GetNotificationSubscriptionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, notificationsapi.NotificationSubscription) - assert response.name == 'name_value' - assert response.registered_event == notificationsapi.NotificationSubscription.NotificationEventType.PRODUCT_STATUS_CHANGE - assert response.call_back_uri == 'call_back_uri_value' - - -def test_get_notification_subscription_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 = NotificationsApiServiceClient( - 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 = notificationsapi.GetNotificationSubscriptionRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_notification_subscription), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_notification_subscription(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == notificationsapi.GetNotificationSubscriptionRequest( - name='name_value', - ) - -def test_get_notification_subscription_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NotificationsApiServiceClient( - 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_notification_subscription in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_notification_subscription] = mock_rpc - request = {} - client.get_notification_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_notification_subscription(request) - - # Establish that a new wrapper 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_notification_subscription_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = NotificationsApiServiceAsyncClient( - 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_notification_subscription in client._client._transport._wrapped_methods - - # 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_notification_subscription] = mock_rpc - - request = {} - await client.get_notification_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_notification_subscription(request) - - # Establish that a new wrapper 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_notification_subscription_async(transport: str = 'grpc_asyncio', request_type=notificationsapi.GetNotificationSubscriptionRequest): - client = NotificationsApiServiceAsyncClient( - 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_notification_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(notificationsapi.NotificationSubscription( - name='name_value', - registered_event=notificationsapi.NotificationSubscription.NotificationEventType.PRODUCT_STATUS_CHANGE, - call_back_uri='call_back_uri_value', - )) - response = await client.get_notification_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = notificationsapi.GetNotificationSubscriptionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, notificationsapi.NotificationSubscription) - assert response.name == 'name_value' - assert response.registered_event == notificationsapi.NotificationSubscription.NotificationEventType.PRODUCT_STATUS_CHANGE - assert response.call_back_uri == 'call_back_uri_value' - - -@pytest.mark.asyncio -async def test_get_notification_subscription_async_from_dict(): - await test_get_notification_subscription_async(request_type=dict) - -def test_get_notification_subscription_field_headers(): - client = NotificationsApiServiceClient( - 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 = notificationsapi.GetNotificationSubscriptionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_notification_subscription), - '__call__') as call: - call.return_value = notificationsapi.NotificationSubscription() - client.get_notification_subscription(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_notification_subscription_field_headers_async(): - client = NotificationsApiServiceAsyncClient( - 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 = notificationsapi.GetNotificationSubscriptionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_notification_subscription), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notificationsapi.NotificationSubscription()) - await client.get_notification_subscription(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_notification_subscription_flattened(): - client = NotificationsApiServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_notification_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = notificationsapi.NotificationSubscription() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_notification_subscription( - 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_notification_subscription_flattened_error(): - client = NotificationsApiServiceClient( - 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_notification_subscription( - notificationsapi.GetNotificationSubscriptionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_notification_subscription_flattened_async(): - client = NotificationsApiServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_notification_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = notificationsapi.NotificationSubscription() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notificationsapi.NotificationSubscription()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_notification_subscription( - 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_notification_subscription_flattened_error_async(): - client = NotificationsApiServiceAsyncClient( - 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_notification_subscription( - notificationsapi.GetNotificationSubscriptionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - notificationsapi.CreateNotificationSubscriptionRequest, - dict, -]) -def test_create_notification_subscription(request_type, transport: str = 'grpc'): - client = NotificationsApiServiceClient( - 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_notification_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = notificationsapi.NotificationSubscription( - name='name_value', - registered_event=notificationsapi.NotificationSubscription.NotificationEventType.PRODUCT_STATUS_CHANGE, - call_back_uri='call_back_uri_value', - all_managed_accounts=True, - ) - response = client.create_notification_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = notificationsapi.CreateNotificationSubscriptionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, notificationsapi.NotificationSubscription) - assert response.name == 'name_value' - assert response.registered_event == notificationsapi.NotificationSubscription.NotificationEventType.PRODUCT_STATUS_CHANGE - assert response.call_back_uri == 'call_back_uri_value' - - -def test_create_notification_subscription_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 = NotificationsApiServiceClient( - 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 = notificationsapi.CreateNotificationSubscriptionRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_notification_subscription), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_notification_subscription(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == notificationsapi.CreateNotificationSubscriptionRequest( - parent='parent_value', - ) - -def test_create_notification_subscription_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NotificationsApiServiceClient( - 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_notification_subscription in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_notification_subscription] = mock_rpc - request = {} - client.create_notification_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_notification_subscription(request) - - # Establish that a new wrapper 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_notification_subscription_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = NotificationsApiServiceAsyncClient( - 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_notification_subscription in client._client._transport._wrapped_methods - - # 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_notification_subscription] = mock_rpc - - request = {} - await client.create_notification_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.create_notification_subscription(request) - - # Establish that a new wrapper 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_notification_subscription_async(transport: str = 'grpc_asyncio', request_type=notificationsapi.CreateNotificationSubscriptionRequest): - client = NotificationsApiServiceAsyncClient( - 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_notification_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(notificationsapi.NotificationSubscription( - name='name_value', - registered_event=notificationsapi.NotificationSubscription.NotificationEventType.PRODUCT_STATUS_CHANGE, - call_back_uri='call_back_uri_value', - )) - response = await client.create_notification_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = notificationsapi.CreateNotificationSubscriptionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, notificationsapi.NotificationSubscription) - assert response.name == 'name_value' - assert response.registered_event == notificationsapi.NotificationSubscription.NotificationEventType.PRODUCT_STATUS_CHANGE - assert response.call_back_uri == 'call_back_uri_value' - - -@pytest.mark.asyncio -async def test_create_notification_subscription_async_from_dict(): - await test_create_notification_subscription_async(request_type=dict) - -def test_create_notification_subscription_field_headers(): - client = NotificationsApiServiceClient( - 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 = notificationsapi.CreateNotificationSubscriptionRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_notification_subscription), - '__call__') as call: - call.return_value = notificationsapi.NotificationSubscription() - client.create_notification_subscription(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_notification_subscription_field_headers_async(): - client = NotificationsApiServiceAsyncClient( - 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 = notificationsapi.CreateNotificationSubscriptionRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_notification_subscription), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notificationsapi.NotificationSubscription()) - await client.create_notification_subscription(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_notification_subscription_flattened(): - client = NotificationsApiServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_notification_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = notificationsapi.NotificationSubscription() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_notification_subscription( - parent='parent_value', - notification_subscription=notificationsapi.NotificationSubscription(all_managed_accounts=True), - ) - - # 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].notification_subscription - mock_val = notificationsapi.NotificationSubscription(all_managed_accounts=True) - assert arg == mock_val - - -def test_create_notification_subscription_flattened_error(): - client = NotificationsApiServiceClient( - 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_notification_subscription( - notificationsapi.CreateNotificationSubscriptionRequest(), - parent='parent_value', - notification_subscription=notificationsapi.NotificationSubscription(all_managed_accounts=True), - ) - -@pytest.mark.asyncio -async def test_create_notification_subscription_flattened_async(): - client = NotificationsApiServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_notification_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = notificationsapi.NotificationSubscription() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notificationsapi.NotificationSubscription()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_notification_subscription( - parent='parent_value', - notification_subscription=notificationsapi.NotificationSubscription(all_managed_accounts=True), - ) - - # 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].notification_subscription - mock_val = notificationsapi.NotificationSubscription(all_managed_accounts=True) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_notification_subscription_flattened_error_async(): - client = NotificationsApiServiceAsyncClient( - 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_notification_subscription( - notificationsapi.CreateNotificationSubscriptionRequest(), - parent='parent_value', - notification_subscription=notificationsapi.NotificationSubscription(all_managed_accounts=True), - ) - - -@pytest.mark.parametrize("request_type", [ - notificationsapi.UpdateNotificationSubscriptionRequest, - dict, -]) -def test_update_notification_subscription(request_type, transport: str = 'grpc'): - client = NotificationsApiServiceClient( - 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_notification_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = notificationsapi.NotificationSubscription( - name='name_value', - registered_event=notificationsapi.NotificationSubscription.NotificationEventType.PRODUCT_STATUS_CHANGE, - call_back_uri='call_back_uri_value', - all_managed_accounts=True, - ) - response = client.update_notification_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = notificationsapi.UpdateNotificationSubscriptionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, notificationsapi.NotificationSubscription) - assert response.name == 'name_value' - assert response.registered_event == notificationsapi.NotificationSubscription.NotificationEventType.PRODUCT_STATUS_CHANGE - assert response.call_back_uri == 'call_back_uri_value' - - -def test_update_notification_subscription_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 = NotificationsApiServiceClient( - 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 = notificationsapi.UpdateNotificationSubscriptionRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_subscription), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_notification_subscription(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == notificationsapi.UpdateNotificationSubscriptionRequest( - ) - -def test_update_notification_subscription_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NotificationsApiServiceClient( - 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_notification_subscription in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_notification_subscription] = mock_rpc - request = {} - client.update_notification_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_notification_subscription(request) - - # Establish that a new wrapper 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_notification_subscription_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = NotificationsApiServiceAsyncClient( - 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_notification_subscription in client._client._transport._wrapped_methods - - # 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_notification_subscription] = mock_rpc - - request = {} - await client.update_notification_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_notification_subscription(request) - - # Establish that a new wrapper 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_notification_subscription_async(transport: str = 'grpc_asyncio', request_type=notificationsapi.UpdateNotificationSubscriptionRequest): - client = NotificationsApiServiceAsyncClient( - 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_notification_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(notificationsapi.NotificationSubscription( - name='name_value', - registered_event=notificationsapi.NotificationSubscription.NotificationEventType.PRODUCT_STATUS_CHANGE, - call_back_uri='call_back_uri_value', - )) - response = await client.update_notification_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = notificationsapi.UpdateNotificationSubscriptionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, notificationsapi.NotificationSubscription) - assert response.name == 'name_value' - assert response.registered_event == notificationsapi.NotificationSubscription.NotificationEventType.PRODUCT_STATUS_CHANGE - assert response.call_back_uri == 'call_back_uri_value' - - -@pytest.mark.asyncio -async def test_update_notification_subscription_async_from_dict(): - await test_update_notification_subscription_async(request_type=dict) - -def test_update_notification_subscription_field_headers(): - client = NotificationsApiServiceClient( - 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 = notificationsapi.UpdateNotificationSubscriptionRequest() - - request.notification_subscription.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_subscription), - '__call__') as call: - call.return_value = notificationsapi.NotificationSubscription() - client.update_notification_subscription(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', - 'notification_subscription.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_notification_subscription_field_headers_async(): - client = NotificationsApiServiceAsyncClient( - 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 = notificationsapi.UpdateNotificationSubscriptionRequest() - - request.notification_subscription.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_subscription), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notificationsapi.NotificationSubscription()) - await client.update_notification_subscription(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', - 'notification_subscription.name=name_value', - ) in kw['metadata'] - - -def test_update_notification_subscription_flattened(): - client = NotificationsApiServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = notificationsapi.NotificationSubscription() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_notification_subscription( - notification_subscription=notificationsapi.NotificationSubscription(all_managed_accounts=True), - 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].notification_subscription - mock_val = notificationsapi.NotificationSubscription(all_managed_accounts=True) - 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_notification_subscription_flattened_error(): - client = NotificationsApiServiceClient( - 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_notification_subscription( - notificationsapi.UpdateNotificationSubscriptionRequest(), - notification_subscription=notificationsapi.NotificationSubscription(all_managed_accounts=True), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_notification_subscription_flattened_async(): - client = NotificationsApiServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = notificationsapi.NotificationSubscription() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notificationsapi.NotificationSubscription()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_notification_subscription( - notification_subscription=notificationsapi.NotificationSubscription(all_managed_accounts=True), - 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].notification_subscription - mock_val = notificationsapi.NotificationSubscription(all_managed_accounts=True) - 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_notification_subscription_flattened_error_async(): - client = NotificationsApiServiceAsyncClient( - 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_notification_subscription( - notificationsapi.UpdateNotificationSubscriptionRequest(), - notification_subscription=notificationsapi.NotificationSubscription(all_managed_accounts=True), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - notificationsapi.DeleteNotificationSubscriptionRequest, - dict, -]) -def test_delete_notification_subscription(request_type, transport: str = 'grpc'): - client = NotificationsApiServiceClient( - 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_notification_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_notification_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = notificationsapi.DeleteNotificationSubscriptionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_notification_subscription_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 = NotificationsApiServiceClient( - 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 = notificationsapi.DeleteNotificationSubscriptionRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_notification_subscription), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_notification_subscription(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == notificationsapi.DeleteNotificationSubscriptionRequest( - name='name_value', - ) - -def test_delete_notification_subscription_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NotificationsApiServiceClient( - 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_notification_subscription in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_notification_subscription] = mock_rpc - request = {} - client.delete_notification_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_notification_subscription(request) - - # Establish that a new wrapper 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_notification_subscription_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = NotificationsApiServiceAsyncClient( - 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_notification_subscription in client._client._transport._wrapped_methods - - # 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_notification_subscription] = mock_rpc - - request = {} - await client.delete_notification_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.delete_notification_subscription(request) - - # Establish that a new wrapper 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_notification_subscription_async(transport: str = 'grpc_asyncio', request_type=notificationsapi.DeleteNotificationSubscriptionRequest): - client = NotificationsApiServiceAsyncClient( - 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_notification_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_notification_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = notificationsapi.DeleteNotificationSubscriptionRequest() - 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_notification_subscription_async_from_dict(): - await test_delete_notification_subscription_async(request_type=dict) - -def test_delete_notification_subscription_field_headers(): - client = NotificationsApiServiceClient( - 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 = notificationsapi.DeleteNotificationSubscriptionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_notification_subscription), - '__call__') as call: - call.return_value = None - client.delete_notification_subscription(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_notification_subscription_field_headers_async(): - client = NotificationsApiServiceAsyncClient( - 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 = notificationsapi.DeleteNotificationSubscriptionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_notification_subscription), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_notification_subscription(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_notification_subscription_flattened(): - client = NotificationsApiServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_notification_subscription), - '__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_notification_subscription( - 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_notification_subscription_flattened_error(): - client = NotificationsApiServiceClient( - 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_notification_subscription( - notificationsapi.DeleteNotificationSubscriptionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_notification_subscription_flattened_async(): - client = NotificationsApiServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_notification_subscription), - '__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_notification_subscription( - 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_notification_subscription_flattened_error_async(): - client = NotificationsApiServiceAsyncClient( - 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_notification_subscription( - notificationsapi.DeleteNotificationSubscriptionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - notificationsapi.ListNotificationSubscriptionsRequest, - dict, -]) -def test_list_notification_subscriptions(request_type, transport: str = 'grpc'): - client = NotificationsApiServiceClient( - 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_notification_subscriptions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = notificationsapi.ListNotificationSubscriptionsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_notification_subscriptions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = notificationsapi.ListNotificationSubscriptionsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNotificationSubscriptionsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_notification_subscriptions_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 = NotificationsApiServiceClient( - 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 = notificationsapi.ListNotificationSubscriptionsRequest( - 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_notification_subscriptions), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_notification_subscriptions(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == notificationsapi.ListNotificationSubscriptionsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_notification_subscriptions_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NotificationsApiServiceClient( - 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_notification_subscriptions in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_notification_subscriptions] = mock_rpc - request = {} - client.list_notification_subscriptions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_notification_subscriptions(request) - - # Establish that a new wrapper 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_notification_subscriptions_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = NotificationsApiServiceAsyncClient( - 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_notification_subscriptions in client._client._transport._wrapped_methods - - # 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_notification_subscriptions] = mock_rpc - - request = {} - await client.list_notification_subscriptions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_notification_subscriptions(request) - - # Establish that a new wrapper 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_notification_subscriptions_async(transport: str = 'grpc_asyncio', request_type=notificationsapi.ListNotificationSubscriptionsRequest): - client = NotificationsApiServiceAsyncClient( - 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_notification_subscriptions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(notificationsapi.ListNotificationSubscriptionsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_notification_subscriptions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = notificationsapi.ListNotificationSubscriptionsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNotificationSubscriptionsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_notification_subscriptions_async_from_dict(): - await test_list_notification_subscriptions_async(request_type=dict) - -def test_list_notification_subscriptions_field_headers(): - client = NotificationsApiServiceClient( - 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 = notificationsapi.ListNotificationSubscriptionsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notification_subscriptions), - '__call__') as call: - call.return_value = notificationsapi.ListNotificationSubscriptionsResponse() - client.list_notification_subscriptions(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_notification_subscriptions_field_headers_async(): - client = NotificationsApiServiceAsyncClient( - 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 = notificationsapi.ListNotificationSubscriptionsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notification_subscriptions), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notificationsapi.ListNotificationSubscriptionsResponse()) - await client.list_notification_subscriptions(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_notification_subscriptions_flattened(): - client = NotificationsApiServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notification_subscriptions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = notificationsapi.ListNotificationSubscriptionsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_notification_subscriptions( - 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_notification_subscriptions_flattened_error(): - client = NotificationsApiServiceClient( - 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_notification_subscriptions( - notificationsapi.ListNotificationSubscriptionsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_notification_subscriptions_flattened_async(): - client = NotificationsApiServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notification_subscriptions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = notificationsapi.ListNotificationSubscriptionsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notificationsapi.ListNotificationSubscriptionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_notification_subscriptions( - 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_notification_subscriptions_flattened_error_async(): - client = NotificationsApiServiceAsyncClient( - 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_notification_subscriptions( - notificationsapi.ListNotificationSubscriptionsRequest(), - parent='parent_value', - ) - - -def test_list_notification_subscriptions_pager(transport_name: str = "grpc"): - client = NotificationsApiServiceClient( - 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_notification_subscriptions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - notificationsapi.ListNotificationSubscriptionsResponse( - notification_subscriptions=[ - notificationsapi.NotificationSubscription(), - notificationsapi.NotificationSubscription(), - notificationsapi.NotificationSubscription(), - ], - next_page_token='abc', - ), - notificationsapi.ListNotificationSubscriptionsResponse( - notification_subscriptions=[], - next_page_token='def', - ), - notificationsapi.ListNotificationSubscriptionsResponse( - notification_subscriptions=[ - notificationsapi.NotificationSubscription(), - ], - next_page_token='ghi', - ), - notificationsapi.ListNotificationSubscriptionsResponse( - notification_subscriptions=[ - notificationsapi.NotificationSubscription(), - notificationsapi.NotificationSubscription(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_notification_subscriptions(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, notificationsapi.NotificationSubscription) - for i in results) -def test_list_notification_subscriptions_pages(transport_name: str = "grpc"): - client = NotificationsApiServiceClient( - 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_notification_subscriptions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - notificationsapi.ListNotificationSubscriptionsResponse( - notification_subscriptions=[ - notificationsapi.NotificationSubscription(), - notificationsapi.NotificationSubscription(), - notificationsapi.NotificationSubscription(), - ], - next_page_token='abc', - ), - notificationsapi.ListNotificationSubscriptionsResponse( - notification_subscriptions=[], - next_page_token='def', - ), - notificationsapi.ListNotificationSubscriptionsResponse( - notification_subscriptions=[ - notificationsapi.NotificationSubscription(), - ], - next_page_token='ghi', - ), - notificationsapi.ListNotificationSubscriptionsResponse( - notification_subscriptions=[ - notificationsapi.NotificationSubscription(), - notificationsapi.NotificationSubscription(), - ], - ), - RuntimeError, - ) - pages = list(client.list_notification_subscriptions(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_notification_subscriptions_async_pager(): - client = NotificationsApiServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notification_subscriptions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - notificationsapi.ListNotificationSubscriptionsResponse( - notification_subscriptions=[ - notificationsapi.NotificationSubscription(), - notificationsapi.NotificationSubscription(), - notificationsapi.NotificationSubscription(), - ], - next_page_token='abc', - ), - notificationsapi.ListNotificationSubscriptionsResponse( - notification_subscriptions=[], - next_page_token='def', - ), - notificationsapi.ListNotificationSubscriptionsResponse( - notification_subscriptions=[ - notificationsapi.NotificationSubscription(), - ], - next_page_token='ghi', - ), - notificationsapi.ListNotificationSubscriptionsResponse( - notification_subscriptions=[ - notificationsapi.NotificationSubscription(), - notificationsapi.NotificationSubscription(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_notification_subscriptions(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, notificationsapi.NotificationSubscription) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_notification_subscriptions_async_pages(): - client = NotificationsApiServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notification_subscriptions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - notificationsapi.ListNotificationSubscriptionsResponse( - notification_subscriptions=[ - notificationsapi.NotificationSubscription(), - notificationsapi.NotificationSubscription(), - notificationsapi.NotificationSubscription(), - ], - next_page_token='abc', - ), - notificationsapi.ListNotificationSubscriptionsResponse( - notification_subscriptions=[], - next_page_token='def', - ), - notificationsapi.ListNotificationSubscriptionsResponse( - notification_subscriptions=[ - notificationsapi.NotificationSubscription(), - ], - next_page_token='ghi', - ), - notificationsapi.ListNotificationSubscriptionsResponse( - notification_subscriptions=[ - notificationsapi.NotificationSubscription(), - notificationsapi.NotificationSubscription(), - ], - ), - 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_notification_subscriptions(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_notification_subscription_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 = NotificationsApiServiceClient( - 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_notification_subscription in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_notification_subscription] = mock_rpc - - request = {} - client.get_notification_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_notification_subscription(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_notification_subscription_rest_required_fields(request_type=notificationsapi.GetNotificationSubscriptionRequest): - transport_class = transports.NotificationsApiServiceRestTransport - - 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_notification_subscription._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_notification_subscription._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 = NotificationsApiServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = notificationsapi.NotificationSubscription() - # 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 = notificationsapi.NotificationSubscription.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_notification_subscription(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_notification_subscription_rest_unset_required_fields(): - transport = transports.NotificationsApiServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_notification_subscription._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_notification_subscription_rest_flattened(): - client = NotificationsApiServiceClient( - 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 = notificationsapi.NotificationSubscription() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/notificationsubscriptions/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 = notificationsapi.NotificationSubscription.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_notification_subscription(**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/notifications/v1beta/{name=accounts/*/notificationsubscriptions/*}" % client.transport._host, args[1]) - - -def test_get_notification_subscription_rest_flattened_error(transport: str = 'rest'): - client = NotificationsApiServiceClient( - 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_notification_subscription( - notificationsapi.GetNotificationSubscriptionRequest(), - name='name_value', - ) - - -def test_create_notification_subscription_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 = NotificationsApiServiceClient( - 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_notification_subscription in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_notification_subscription] = mock_rpc - - request = {} - client.create_notification_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_notification_subscription(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_notification_subscription_rest_required_fields(request_type=notificationsapi.CreateNotificationSubscriptionRequest): - transport_class = transports.NotificationsApiServiceRestTransport - - 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_notification_subscription._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_notification_subscription._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 = NotificationsApiServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = notificationsapi.NotificationSubscription() - # 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 = notificationsapi.NotificationSubscription.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_notification_subscription(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_notification_subscription_rest_unset_required_fields(): - transport = transports.NotificationsApiServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_notification_subscription._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "notificationSubscription", ))) - - -def test_create_notification_subscription_rest_flattened(): - client = NotificationsApiServiceClient( - 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 = notificationsapi.NotificationSubscription() - - # 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', - notification_subscription=notificationsapi.NotificationSubscription(all_managed_accounts=True), - ) - 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 = notificationsapi.NotificationSubscription.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_notification_subscription(**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/notifications/v1beta/{parent=accounts/*}/notificationsubscriptions" % client.transport._host, args[1]) - - -def test_create_notification_subscription_rest_flattened_error(transport: str = 'rest'): - client = NotificationsApiServiceClient( - 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_notification_subscription( - notificationsapi.CreateNotificationSubscriptionRequest(), - parent='parent_value', - notification_subscription=notificationsapi.NotificationSubscription(all_managed_accounts=True), - ) - - -def test_update_notification_subscription_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 = NotificationsApiServiceClient( - 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_notification_subscription in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_notification_subscription] = mock_rpc - - request = {} - client.update_notification_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_notification_subscription(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_notification_subscription_rest_required_fields(request_type=notificationsapi.UpdateNotificationSubscriptionRequest): - transport_class = transports.NotificationsApiServiceRestTransport - - 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_notification_subscription._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_notification_subscription._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 = NotificationsApiServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = notificationsapi.NotificationSubscription() - # 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 = notificationsapi.NotificationSubscription.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_notification_subscription(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_notification_subscription_rest_unset_required_fields(): - transport = transports.NotificationsApiServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_notification_subscription._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("notificationSubscription", ))) - - -def test_update_notification_subscription_rest_flattened(): - client = NotificationsApiServiceClient( - 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 = notificationsapi.NotificationSubscription() - - # get arguments that satisfy an http rule for this method - sample_request = {'notification_subscription': {'name': 'accounts/sample1/notificationsubscriptions/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - notification_subscription=notificationsapi.NotificationSubscription(all_managed_accounts=True), - 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 = notificationsapi.NotificationSubscription.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_notification_subscription(**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/notifications/v1beta/{notification_subscription.name=accounts/*/notificationsubscriptions/*}" % client.transport._host, args[1]) - - -def test_update_notification_subscription_rest_flattened_error(transport: str = 'rest'): - client = NotificationsApiServiceClient( - 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_notification_subscription( - notificationsapi.UpdateNotificationSubscriptionRequest(), - notification_subscription=notificationsapi.NotificationSubscription(all_managed_accounts=True), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_notification_subscription_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 = NotificationsApiServiceClient( - 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_notification_subscription in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_notification_subscription] = mock_rpc - - request = {} - client.delete_notification_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_notification_subscription(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_notification_subscription_rest_required_fields(request_type=notificationsapi.DeleteNotificationSubscriptionRequest): - transport_class = transports.NotificationsApiServiceRestTransport - - 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_notification_subscription._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_notification_subscription._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 = NotificationsApiServiceClient( - 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_notification_subscription(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_notification_subscription_rest_unset_required_fields(): - transport = transports.NotificationsApiServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_notification_subscription._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_delete_notification_subscription_rest_flattened(): - client = NotificationsApiServiceClient( - 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/notificationsubscriptions/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_notification_subscription(**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/notifications/v1beta/{name=accounts/*/notificationsubscriptions/*}" % client.transport._host, args[1]) - - -def test_delete_notification_subscription_rest_flattened_error(transport: str = 'rest'): - client = NotificationsApiServiceClient( - 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_notification_subscription( - notificationsapi.DeleteNotificationSubscriptionRequest(), - name='name_value', - ) - - -def test_list_notification_subscriptions_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 = NotificationsApiServiceClient( - 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_notification_subscriptions in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_notification_subscriptions] = mock_rpc - - request = {} - client.list_notification_subscriptions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_notification_subscriptions(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_notification_subscriptions_rest_required_fields(request_type=notificationsapi.ListNotificationSubscriptionsRequest): - transport_class = transports.NotificationsApiServiceRestTransport - - 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_notification_subscriptions._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_notification_subscriptions._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 = NotificationsApiServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = notificationsapi.ListNotificationSubscriptionsResponse() - # 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 = notificationsapi.ListNotificationSubscriptionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_notification_subscriptions(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_notification_subscriptions_rest_unset_required_fields(): - transport = transports.NotificationsApiServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_notification_subscriptions._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_notification_subscriptions_rest_flattened(): - client = NotificationsApiServiceClient( - 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 = notificationsapi.ListNotificationSubscriptionsResponse() - - # 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 = notificationsapi.ListNotificationSubscriptionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_notification_subscriptions(**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/notifications/v1beta/{parent=accounts/*}/notificationsubscriptions" % client.transport._host, args[1]) - - -def test_list_notification_subscriptions_rest_flattened_error(transport: str = 'rest'): - client = NotificationsApiServiceClient( - 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_notification_subscriptions( - notificationsapi.ListNotificationSubscriptionsRequest(), - parent='parent_value', - ) - - -def test_list_notification_subscriptions_rest_pager(transport: str = 'rest'): - client = NotificationsApiServiceClient( - 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 = ( - notificationsapi.ListNotificationSubscriptionsResponse( - notification_subscriptions=[ - notificationsapi.NotificationSubscription(), - notificationsapi.NotificationSubscription(), - notificationsapi.NotificationSubscription(), - ], - next_page_token='abc', - ), - notificationsapi.ListNotificationSubscriptionsResponse( - notification_subscriptions=[], - next_page_token='def', - ), - notificationsapi.ListNotificationSubscriptionsResponse( - notification_subscriptions=[ - notificationsapi.NotificationSubscription(), - ], - next_page_token='ghi', - ), - notificationsapi.ListNotificationSubscriptionsResponse( - notification_subscriptions=[ - notificationsapi.NotificationSubscription(), - notificationsapi.NotificationSubscription(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(notificationsapi.ListNotificationSubscriptionsResponse.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_notification_subscriptions(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, notificationsapi.NotificationSubscription) - for i in results) - - pages = list(client.list_notification_subscriptions(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.NotificationsApiServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = NotificationsApiServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.NotificationsApiServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = NotificationsApiServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.NotificationsApiServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = NotificationsApiServiceClient( - 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 = NotificationsApiServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.NotificationsApiServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = NotificationsApiServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.NotificationsApiServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = NotificationsApiServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.NotificationsApiServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.NotificationsApiServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.NotificationsApiServiceGrpcTransport, - transports.NotificationsApiServiceGrpcAsyncIOTransport, - transports.NotificationsApiServiceRestTransport, -]) -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 = NotificationsApiServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = NotificationsApiServiceClient( - 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_notification_subscription_empty_call_grpc(): - client = NotificationsApiServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_notification_subscription), - '__call__') as call: - call.return_value = notificationsapi.NotificationSubscription() - client.get_notification_subscription(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = notificationsapi.GetNotificationSubscriptionRequest() - - assert args[0] == request_msg - - -# This 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_notification_subscription_empty_call_grpc(): - client = NotificationsApiServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_notification_subscription), - '__call__') as call: - call.return_value = notificationsapi.NotificationSubscription() - client.create_notification_subscription(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = notificationsapi.CreateNotificationSubscriptionRequest() - - assert args[0] == request_msg - - -# This 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_notification_subscription_empty_call_grpc(): - client = NotificationsApiServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_subscription), - '__call__') as call: - call.return_value = notificationsapi.NotificationSubscription() - client.update_notification_subscription(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = notificationsapi.UpdateNotificationSubscriptionRequest() - - assert args[0] == request_msg - - -# This 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_notification_subscription_empty_call_grpc(): - client = NotificationsApiServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_notification_subscription), - '__call__') as call: - call.return_value = None - client.delete_notification_subscription(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = notificationsapi.DeleteNotificationSubscriptionRequest() - - assert args[0] == request_msg - - -# This 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_notification_subscriptions_empty_call_grpc(): - client = NotificationsApiServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_notification_subscriptions), - '__call__') as call: - call.return_value = notificationsapi.ListNotificationSubscriptionsResponse() - client.list_notification_subscriptions(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = notificationsapi.ListNotificationSubscriptionsRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = NotificationsApiServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = NotificationsApiServiceAsyncClient( - 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_notification_subscription_empty_call_grpc_asyncio(): - client = NotificationsApiServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_notification_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notificationsapi.NotificationSubscription( - name='name_value', - registered_event=notificationsapi.NotificationSubscription.NotificationEventType.PRODUCT_STATUS_CHANGE, - call_back_uri='call_back_uri_value', - )) - await client.get_notification_subscription(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = notificationsapi.GetNotificationSubscriptionRequest() - - assert args[0] == request_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_notification_subscription_empty_call_grpc_asyncio(): - client = NotificationsApiServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_notification_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notificationsapi.NotificationSubscription( - name='name_value', - registered_event=notificationsapi.NotificationSubscription.NotificationEventType.PRODUCT_STATUS_CHANGE, - call_back_uri='call_back_uri_value', - )) - await client.create_notification_subscription(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = notificationsapi.CreateNotificationSubscriptionRequest() - - assert args[0] == request_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_notification_subscription_empty_call_grpc_asyncio(): - client = NotificationsApiServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notificationsapi.NotificationSubscription( - name='name_value', - registered_event=notificationsapi.NotificationSubscription.NotificationEventType.PRODUCT_STATUS_CHANGE, - call_back_uri='call_back_uri_value', - )) - await client.update_notification_subscription(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = notificationsapi.UpdateNotificationSubscriptionRequest() - - assert args[0] == request_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_notification_subscription_empty_call_grpc_asyncio(): - client = NotificationsApiServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_notification_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_notification_subscription(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = notificationsapi.DeleteNotificationSubscriptionRequest() - - assert args[0] == request_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_notification_subscriptions_empty_call_grpc_asyncio(): - client = NotificationsApiServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_notification_subscriptions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notificationsapi.ListNotificationSubscriptionsResponse( - next_page_token='next_page_token_value', - )) - await client.list_notification_subscriptions(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = notificationsapi.ListNotificationSubscriptionsRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = NotificationsApiServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_get_notification_subscription_rest_bad_request(request_type=notificationsapi.GetNotificationSubscriptionRequest): - client = NotificationsApiServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/notificationsubscriptions/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_notification_subscription(request) - - -@pytest.mark.parametrize("request_type", [ - notificationsapi.GetNotificationSubscriptionRequest, - dict, -]) -def test_get_notification_subscription_rest_call_success(request_type): - client = NotificationsApiServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/notificationsubscriptions/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 = notificationsapi.NotificationSubscription( - name='name_value', - registered_event=notificationsapi.NotificationSubscription.NotificationEventType.PRODUCT_STATUS_CHANGE, - call_back_uri='call_back_uri_value', - all_managed_accounts=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 = notificationsapi.NotificationSubscription.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_notification_subscription(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, notificationsapi.NotificationSubscription) - assert response.name == 'name_value' - assert response.registered_event == notificationsapi.NotificationSubscription.NotificationEventType.PRODUCT_STATUS_CHANGE - assert response.call_back_uri == 'call_back_uri_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_notification_subscription_rest_interceptors(null_interceptor): - transport = transports.NotificationsApiServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NotificationsApiServiceRestInterceptor(), - ) - client = NotificationsApiServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.NotificationsApiServiceRestInterceptor, "post_get_notification_subscription") as post, \ - mock.patch.object(transports.NotificationsApiServiceRestInterceptor, "pre_get_notification_subscription") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = notificationsapi.GetNotificationSubscriptionRequest.pb(notificationsapi.GetNotificationSubscriptionRequest()) - 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 = notificationsapi.NotificationSubscription.to_json(notificationsapi.NotificationSubscription()) - req.return_value.content = return_value - - request = notificationsapi.GetNotificationSubscriptionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = notificationsapi.NotificationSubscription() - - client.get_notification_subscription(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_notification_subscription_rest_bad_request(request_type=notificationsapi.CreateNotificationSubscriptionRequest): - client = NotificationsApiServiceClient( - 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_notification_subscription(request) - - -@pytest.mark.parametrize("request_type", [ - notificationsapi.CreateNotificationSubscriptionRequest, - dict, -]) -def test_create_notification_subscription_rest_call_success(request_type): - client = NotificationsApiServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} - request_init["notification_subscription"] = {'all_managed_accounts': True, 'target_account': 'target_account_value', 'name': 'name_value', 'registered_event': 1, 'call_back_uri': 'call_back_uri_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 = notificationsapi.CreateNotificationSubscriptionRequest.meta.fields["notification_subscription"] - - 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["notification_subscription"].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["notification_subscription"][field])): - del request_init["notification_subscription"][field][i][subfield] - else: - del request_init["notification_subscription"][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 = notificationsapi.NotificationSubscription( - name='name_value', - registered_event=notificationsapi.NotificationSubscription.NotificationEventType.PRODUCT_STATUS_CHANGE, - call_back_uri='call_back_uri_value', - all_managed_accounts=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 = notificationsapi.NotificationSubscription.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_notification_subscription(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, notificationsapi.NotificationSubscription) - assert response.name == 'name_value' - assert response.registered_event == notificationsapi.NotificationSubscription.NotificationEventType.PRODUCT_STATUS_CHANGE - assert response.call_back_uri == 'call_back_uri_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_notification_subscription_rest_interceptors(null_interceptor): - transport = transports.NotificationsApiServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NotificationsApiServiceRestInterceptor(), - ) - client = NotificationsApiServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.NotificationsApiServiceRestInterceptor, "post_create_notification_subscription") as post, \ - mock.patch.object(transports.NotificationsApiServiceRestInterceptor, "pre_create_notification_subscription") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = notificationsapi.CreateNotificationSubscriptionRequest.pb(notificationsapi.CreateNotificationSubscriptionRequest()) - 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 = notificationsapi.NotificationSubscription.to_json(notificationsapi.NotificationSubscription()) - req.return_value.content = return_value - - request = notificationsapi.CreateNotificationSubscriptionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = notificationsapi.NotificationSubscription() - - client.create_notification_subscription(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_notification_subscription_rest_bad_request(request_type=notificationsapi.UpdateNotificationSubscriptionRequest): - client = NotificationsApiServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'notification_subscription': {'name': 'accounts/sample1/notificationsubscriptions/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_notification_subscription(request) - - -@pytest.mark.parametrize("request_type", [ - notificationsapi.UpdateNotificationSubscriptionRequest, - dict, -]) -def test_update_notification_subscription_rest_call_success(request_type): - client = NotificationsApiServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'notification_subscription': {'name': 'accounts/sample1/notificationsubscriptions/sample2'}} - request_init["notification_subscription"] = {'all_managed_accounts': True, 'target_account': 'target_account_value', 'name': 'accounts/sample1/notificationsubscriptions/sample2', 'registered_event': 1, 'call_back_uri': 'call_back_uri_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 = notificationsapi.UpdateNotificationSubscriptionRequest.meta.fields["notification_subscription"] - - 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["notification_subscription"].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["notification_subscription"][field])): - del request_init["notification_subscription"][field][i][subfield] - else: - del request_init["notification_subscription"][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 = notificationsapi.NotificationSubscription( - name='name_value', - registered_event=notificationsapi.NotificationSubscription.NotificationEventType.PRODUCT_STATUS_CHANGE, - call_back_uri='call_back_uri_value', - all_managed_accounts=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 = notificationsapi.NotificationSubscription.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_notification_subscription(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, notificationsapi.NotificationSubscription) - assert response.name == 'name_value' - assert response.registered_event == notificationsapi.NotificationSubscription.NotificationEventType.PRODUCT_STATUS_CHANGE - assert response.call_back_uri == 'call_back_uri_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_notification_subscription_rest_interceptors(null_interceptor): - transport = transports.NotificationsApiServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NotificationsApiServiceRestInterceptor(), - ) - client = NotificationsApiServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.NotificationsApiServiceRestInterceptor, "post_update_notification_subscription") as post, \ - mock.patch.object(transports.NotificationsApiServiceRestInterceptor, "pre_update_notification_subscription") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = notificationsapi.UpdateNotificationSubscriptionRequest.pb(notificationsapi.UpdateNotificationSubscriptionRequest()) - 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 = notificationsapi.NotificationSubscription.to_json(notificationsapi.NotificationSubscription()) - req.return_value.content = return_value - - request = notificationsapi.UpdateNotificationSubscriptionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = notificationsapi.NotificationSubscription() - - client.update_notification_subscription(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_notification_subscription_rest_bad_request(request_type=notificationsapi.DeleteNotificationSubscriptionRequest): - client = NotificationsApiServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/notificationsubscriptions/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_notification_subscription(request) - - -@pytest.mark.parametrize("request_type", [ - notificationsapi.DeleteNotificationSubscriptionRequest, - dict, -]) -def test_delete_notification_subscription_rest_call_success(request_type): - client = NotificationsApiServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/notificationsubscriptions/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_notification_subscription(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_notification_subscription_rest_interceptors(null_interceptor): - transport = transports.NotificationsApiServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NotificationsApiServiceRestInterceptor(), - ) - client = NotificationsApiServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.NotificationsApiServiceRestInterceptor, "pre_delete_notification_subscription") as pre: - pre.assert_not_called() - pb_message = notificationsapi.DeleteNotificationSubscriptionRequest.pb(notificationsapi.DeleteNotificationSubscriptionRequest()) - 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 = notificationsapi.DeleteNotificationSubscriptionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_notification_subscription(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_list_notification_subscriptions_rest_bad_request(request_type=notificationsapi.ListNotificationSubscriptionsRequest): - client = NotificationsApiServiceClient( - 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_notification_subscriptions(request) - - -@pytest.mark.parametrize("request_type", [ - notificationsapi.ListNotificationSubscriptionsRequest, - dict, -]) -def test_list_notification_subscriptions_rest_call_success(request_type): - client = NotificationsApiServiceClient( - 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 = notificationsapi.ListNotificationSubscriptionsResponse( - 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 = notificationsapi.ListNotificationSubscriptionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_notification_subscriptions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNotificationSubscriptionsPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_notification_subscriptions_rest_interceptors(null_interceptor): - transport = transports.NotificationsApiServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NotificationsApiServiceRestInterceptor(), - ) - client = NotificationsApiServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.NotificationsApiServiceRestInterceptor, "post_list_notification_subscriptions") as post, \ - mock.patch.object(transports.NotificationsApiServiceRestInterceptor, "pre_list_notification_subscriptions") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = notificationsapi.ListNotificationSubscriptionsRequest.pb(notificationsapi.ListNotificationSubscriptionsRequest()) - 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 = notificationsapi.ListNotificationSubscriptionsResponse.to_json(notificationsapi.ListNotificationSubscriptionsResponse()) - req.return_value.content = return_value - - request = notificationsapi.ListNotificationSubscriptionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = notificationsapi.ListNotificationSubscriptionsResponse() - - client.list_notification_subscriptions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - -def test_initialize_client_w_rest(): - client = NotificationsApiServiceClient( - 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_notification_subscription_empty_call_rest(): - client = NotificationsApiServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_notification_subscription), - '__call__') as call: - client.get_notification_subscription(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = notificationsapi.GetNotificationSubscriptionRequest() - - assert args[0] == request_msg - - -# This 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_notification_subscription_empty_call_rest(): - client = NotificationsApiServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_notification_subscription), - '__call__') as call: - client.create_notification_subscription(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = notificationsapi.CreateNotificationSubscriptionRequest() - - assert args[0] == request_msg - - -# This 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_notification_subscription_empty_call_rest(): - client = NotificationsApiServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_subscription), - '__call__') as call: - client.update_notification_subscription(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = notificationsapi.UpdateNotificationSubscriptionRequest() - - assert args[0] == request_msg - - -# This 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_notification_subscription_empty_call_rest(): - client = NotificationsApiServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_notification_subscription), - '__call__') as call: - client.delete_notification_subscription(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = notificationsapi.DeleteNotificationSubscriptionRequest() - - assert args[0] == request_msg - - -# This 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_notification_subscriptions_empty_call_rest(): - client = NotificationsApiServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_notification_subscriptions), - '__call__') as call: - client.list_notification_subscriptions(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = notificationsapi.ListNotificationSubscriptionsRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = NotificationsApiServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.NotificationsApiServiceGrpcTransport, - ) - -def test_notifications_api_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.NotificationsApiServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_notifications_api_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.shopping.merchant_notifications_v1beta.services.notifications_api_service.transports.NotificationsApiServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.NotificationsApiServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'get_notification_subscription', - 'create_notification_subscription', - 'update_notification_subscription', - 'delete_notification_subscription', - 'list_notification_subscriptions', - ) - 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_notifications_api_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_notifications_v1beta.services.notifications_api_service.transports.NotificationsApiServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.NotificationsApiServiceTransport( - 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_notifications_api_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_notifications_v1beta.services.notifications_api_service.transports.NotificationsApiServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.NotificationsApiServiceTransport() - adc.assert_called_once() - - -def test_notifications_api_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) - NotificationsApiServiceClient() - 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.NotificationsApiServiceGrpcTransport, - transports.NotificationsApiServiceGrpcAsyncIOTransport, - ], -) -def test_notifications_api_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.NotificationsApiServiceGrpcTransport, - transports.NotificationsApiServiceGrpcAsyncIOTransport, - transports.NotificationsApiServiceRestTransport, - ], -) -def test_notifications_api_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.NotificationsApiServiceGrpcTransport, grpc_helpers), - (transports.NotificationsApiServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_notifications_api_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.NotificationsApiServiceGrpcTransport, transports.NotificationsApiServiceGrpcAsyncIOTransport]) -def test_notifications_api_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_notifications_api_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.NotificationsApiServiceRestTransport ( - 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_notifications_api_service_host_no_port(transport_name): - client = NotificationsApiServiceClient( - 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_notifications_api_service_host_with_port(transport_name): - client = NotificationsApiServiceClient( - 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_notifications_api_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = NotificationsApiServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = NotificationsApiServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.get_notification_subscription._session - session2 = client2.transport.get_notification_subscription._session - assert session1 != session2 - session1 = client1.transport.create_notification_subscription._session - session2 = client2.transport.create_notification_subscription._session - assert session1 != session2 - session1 = client1.transport.update_notification_subscription._session - session2 = client2.transport.update_notification_subscription._session - assert session1 != session2 - session1 = client1.transport.delete_notification_subscription._session - session2 = client2.transport.delete_notification_subscription._session - assert session1 != session2 - session1 = client1.transport.list_notification_subscriptions._session - session2 = client2.transport.list_notification_subscriptions._session - assert session1 != session2 -def test_notifications_api_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.NotificationsApiServiceGrpcTransport( - 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_notifications_api_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.NotificationsApiServiceGrpcAsyncIOTransport( - 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.NotificationsApiServiceGrpcTransport, transports.NotificationsApiServiceGrpcAsyncIOTransport]) -def test_notifications_api_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.NotificationsApiServiceGrpcTransport, transports.NotificationsApiServiceGrpcAsyncIOTransport]) -def test_notifications_api_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_notification_subscription_path(): - account = "squid" - notification_subscription = "clam" - expected = "accounts/{account}/notificationsubscriptions/{notification_subscription}".format(account=account, notification_subscription=notification_subscription, ) - actual = NotificationsApiServiceClient.notification_subscription_path(account, notification_subscription) - assert expected == actual - - -def test_parse_notification_subscription_path(): - expected = { - "account": "whelk", - "notification_subscription": "octopus", - } - path = NotificationsApiServiceClient.notification_subscription_path(**expected) - - # Check that the path construction is reversible. - actual = NotificationsApiServiceClient.parse_notification_subscription_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = NotificationsApiServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = NotificationsApiServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = NotificationsApiServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = NotificationsApiServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = NotificationsApiServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = NotificationsApiServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = NotificationsApiServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = NotificationsApiServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = NotificationsApiServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = NotificationsApiServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = NotificationsApiServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = NotificationsApiServiceClient.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 = NotificationsApiServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = NotificationsApiServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = NotificationsApiServiceClient.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.NotificationsApiServiceTransport, '_prep_wrapped_messages') as prep: - client = NotificationsApiServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.NotificationsApiServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = NotificationsApiServiceClient.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 = NotificationsApiServiceClient( - 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 = NotificationsApiServiceAsyncClient( - 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 = NotificationsApiServiceClient( - 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 = NotificationsApiServiceClient( - 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", [ - (NotificationsApiServiceClient, transports.NotificationsApiServiceGrpcTransport), - (NotificationsApiServiceAsyncClient, transports.NotificationsApiServiceGrpcAsyncIOTransport), -]) -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-promotions/v1beta/.coveragerc b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/.coveragerc deleted file mode 100644 index dafc77479871..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/shopping/merchant_promotions/__init__.py - google/shopping/merchant_promotions/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-promotions/v1beta/.flake8 b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/MANIFEST.in b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/MANIFEST.in deleted file mode 100644 index 4000aef85aac..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/shopping/merchant_promotions *.py -recursive-include google/shopping/merchant_promotions_v1beta *.py diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/README.rst b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/README.rst deleted file mode 100644 index cb2860617dd9..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Shopping Merchant Promotions 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 Promotions 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 diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/_static/custom.css b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/_static/custom.css +++ /dev/null @@ -1,3 +0,0 @@ -dl.field-list > dt { - min-width: 100px -} diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/conf.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/conf.py deleted file mode 100644 index 903cf3292f1b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-promotions 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("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# 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.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -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-promotions" -copyright = u"2023, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# 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 = 'en' - -# 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"] - -# 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 Python", - "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-promotions-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-promotions.tex", - u"google-shopping-merchant-promotions 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-promotions", - u"Google Shopping Merchant Promotions 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-promotions", - u"google-shopping-merchant-promotions Documentation", - author, - "google-shopping-merchant-promotions", - "GAPIC library for Google Shopping Merchant Promotions API", - "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": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", 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-promotions/v1beta/docs/index.rst b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/index.rst deleted file mode 100644 index bd406fae2308..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - merchant_promotions_v1beta/services_ - merchant_promotions_v1beta/types_ diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/merchant_promotions_v1beta/promotions_service.rst b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/merchant_promotions_v1beta/promotions_service.rst deleted file mode 100644 index 229477aebf39..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/merchant_promotions_v1beta/promotions_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -PromotionsService ------------------------------------ - -.. automodule:: google.shopping.merchant_promotions_v1beta.services.promotions_service - :members: - :inherited-members: - -.. automodule:: google.shopping.merchant_promotions_v1beta.services.promotions_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/merchant_promotions_v1beta/services_.rst b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/merchant_promotions_v1beta/services_.rst deleted file mode 100644 index befbacf009f8..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/merchant_promotions_v1beta/services_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Shopping Merchant Promotions v1beta API -=========================================================== -.. toctree:: - :maxdepth: 2 - - promotions_service diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/merchant_promotions_v1beta/types_.rst b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/merchant_promotions_v1beta/types_.rst deleted file mode 100644 index a95c03a1e319..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/docs/merchant_promotions_v1beta/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Shopping Merchant Promotions v1beta API -======================================================== - -.. automodule:: google.shopping.merchant_promotions_v1beta.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions/__init__.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions/__init__.py deleted file mode 100644 index 443803dbb301..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions/__init__.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_promotions import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.shopping.merchant_promotions_v1beta.services.promotions_service.client import PromotionsServiceClient -from google.shopping.merchant_promotions_v1beta.services.promotions_service.async_client import PromotionsServiceAsyncClient - -from google.shopping.merchant_promotions_v1beta.types.promotions import GetPromotionRequest -from google.shopping.merchant_promotions_v1beta.types.promotions import InsertPromotionRequest -from google.shopping.merchant_promotions_v1beta.types.promotions import ListPromotionsRequest -from google.shopping.merchant_promotions_v1beta.types.promotions import ListPromotionsResponse -from google.shopping.merchant_promotions_v1beta.types.promotions import Promotion -from google.shopping.merchant_promotions_v1beta.types.promotions_common import Attributes -from google.shopping.merchant_promotions_v1beta.types.promotions_common import PromotionStatus -from google.shopping.merchant_promotions_v1beta.types.promotions_common import CouponValueType -from google.shopping.merchant_promotions_v1beta.types.promotions_common import OfferType -from google.shopping.merchant_promotions_v1beta.types.promotions_common import ProductApplicability -from google.shopping.merchant_promotions_v1beta.types.promotions_common import RedemptionChannel -from google.shopping.merchant_promotions_v1beta.types.promotions_common import StoreApplicability - -__all__ = ('PromotionsServiceClient', - 'PromotionsServiceAsyncClient', - 'GetPromotionRequest', - 'InsertPromotionRequest', - 'ListPromotionsRequest', - 'ListPromotionsResponse', - 'Promotion', - 'Attributes', - 'PromotionStatus', - 'CouponValueType', - 'OfferType', - 'ProductApplicability', - 'RedemptionChannel', - 'StoreApplicability', -) diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions/gapic_version.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-promotions/v1beta/google/shopping/merchant_promotions/py.typed b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions/py.typed deleted file mode 100644 index 53f2425ea9b3..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-shopping-merchant-promotions package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/__init__.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/__init__.py deleted file mode 100644 index d93e5699df4b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/__init__.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_promotions_v1beta import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.promotions_service import PromotionsServiceClient -from .services.promotions_service import PromotionsServiceAsyncClient - -from .types.promotions import GetPromotionRequest -from .types.promotions import InsertPromotionRequest -from .types.promotions import ListPromotionsRequest -from .types.promotions import ListPromotionsResponse -from .types.promotions import Promotion -from .types.promotions_common import Attributes -from .types.promotions_common import PromotionStatus -from .types.promotions_common import CouponValueType -from .types.promotions_common import OfferType -from .types.promotions_common import ProductApplicability -from .types.promotions_common import RedemptionChannel -from .types.promotions_common import StoreApplicability - -__all__ = ( - 'PromotionsServiceAsyncClient', -'Attributes', -'CouponValueType', -'GetPromotionRequest', -'InsertPromotionRequest', -'ListPromotionsRequest', -'ListPromotionsResponse', -'OfferType', -'ProductApplicability', -'Promotion', -'PromotionStatus', -'PromotionsServiceClient', -'RedemptionChannel', -'StoreApplicability', -) diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/gapic_metadata.json b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/gapic_metadata.json deleted file mode 100644 index 0f9f123e2e18..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/gapic_metadata.json +++ /dev/null @@ -1,73 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.shopping.merchant_promotions_v1beta", - "protoPackage": "google.shopping.merchant.promotions.v1beta", - "schema": "1.0", - "services": { - "PromotionsService": { - "clients": { - "grpc": { - "libraryClient": "PromotionsServiceClient", - "rpcs": { - "GetPromotion": { - "methods": [ - "get_promotion" - ] - }, - "InsertPromotion": { - "methods": [ - "insert_promotion" - ] - }, - "ListPromotions": { - "methods": [ - "list_promotions" - ] - } - } - }, - "grpc-async": { - "libraryClient": "PromotionsServiceAsyncClient", - "rpcs": { - "GetPromotion": { - "methods": [ - "get_promotion" - ] - }, - "InsertPromotion": { - "methods": [ - "insert_promotion" - ] - }, - "ListPromotions": { - "methods": [ - "list_promotions" - ] - } - } - }, - "rest": { - "libraryClient": "PromotionsServiceClient", - "rpcs": { - "GetPromotion": { - "methods": [ - "get_promotion" - ] - }, - "InsertPromotion": { - "methods": [ - "insert_promotion" - ] - }, - "ListPromotions": { - "methods": [ - "list_promotions" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/gapic_version.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-promotions/v1beta/google/shopping/merchant_promotions_v1beta/py.typed b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/py.typed deleted file mode 100644 index 53f2425ea9b3..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-shopping-merchant-promotions package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/__init__.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/__init__.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/__init__.py deleted file mode 100644 index 3cebeff587b6..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 PromotionsServiceClient -from .async_client import PromotionsServiceAsyncClient - -__all__ = ( - 'PromotionsServiceClient', - 'PromotionsServiceAsyncClient', -) diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/async_client.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/async_client.py deleted file mode 100644 index 11d96f941820..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/async_client.py +++ /dev/null @@ -1,612 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_promotions_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 - - -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_promotions_v1beta.services.promotions_service import pagers -from google.shopping.merchant_promotions_v1beta.types import promotions -from google.shopping.merchant_promotions_v1beta.types import promotions_common -from google.shopping.type.types import types -from .transports.base import PromotionsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import PromotionsServiceGrpcAsyncIOTransport -from .client import PromotionsServiceClient - -try: - from google.api_core import client_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 PromotionsServiceAsyncClient: - """Service to manage promotions for products.""" - - _client: PromotionsServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = PromotionsServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = PromotionsServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = PromotionsServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = PromotionsServiceClient._DEFAULT_UNIVERSE - - promotion_path = staticmethod(PromotionsServiceClient.promotion_path) - parse_promotion_path = staticmethod(PromotionsServiceClient.parse_promotion_path) - common_billing_account_path = staticmethod(PromotionsServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(PromotionsServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(PromotionsServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(PromotionsServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(PromotionsServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(PromotionsServiceClient.parse_common_organization_path) - common_project_path = staticmethod(PromotionsServiceClient.common_project_path) - parse_common_project_path = staticmethod(PromotionsServiceClient.parse_common_project_path) - common_location_path = staticmethod(PromotionsServiceClient.common_location_path) - parse_common_location_path = staticmethod(PromotionsServiceClient.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: - PromotionsServiceAsyncClient: The constructed client. - """ - return PromotionsServiceClient.from_service_account_info.__func__(PromotionsServiceAsyncClient, 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: - PromotionsServiceAsyncClient: The constructed client. - """ - return PromotionsServiceClient.from_service_account_file.__func__(PromotionsServiceAsyncClient, 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 PromotionsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> PromotionsServiceTransport: - """Returns the transport used by the client instance. - - Returns: - PromotionsServiceTransport: 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 = PromotionsServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, PromotionsServiceTransport, Callable[..., PromotionsServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the promotions 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,PromotionsServiceTransport,Callable[..., PromotionsServiceTransport]]]): - 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 PromotionsServiceTransport 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 = PromotionsServiceClient( - 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.promotions_v1beta.PromotionsServiceAsyncClient`.", - extra = { - "serviceName": "google.shopping.merchant.promotions.v1beta.PromotionsService", - "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.promotions.v1beta.PromotionsService", - "credentialsType": None, - } - ) - - async def insert_promotion(self, - request: Optional[Union[promotions.InsertPromotionRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> promotions.Promotion: - r"""Inserts a promotion for your Merchant Center account. - If the promotion already exists, then it updates the - promotion instead. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_promotions_v1beta - - async def sample_insert_promotion(): - # Create a client - client = merchant_promotions_v1beta.PromotionsServiceAsyncClient() - - # Initialize request argument(s) - promotion = merchant_promotions_v1beta.Promotion() - promotion.promotion_id = "promotion_id_value" - promotion.content_language = "content_language_value" - promotion.target_country = "target_country_value" - promotion.redemption_channel = ['ONLINE'] - - request = merchant_promotions_v1beta.InsertPromotionRequest( - parent="parent_value", - promotion=promotion, - data_source="data_source_value", - ) - - # Make the request - response = await client.insert_promotion(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_promotions_v1beta.types.InsertPromotionRequest, dict]]): - The request object. Request message for the ``InsertPromotion`` 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_promotions_v1beta.types.Promotion: - Represents a promotion. See the following articles for - more details. - - Required promotion input attributes to pass data - validation checks are primarily defined below: - - \* [Promotions data - specification](\ https://support.google.com/merchants/answer/2906014) - \* [Local promotions data - specification](\ https://support.google.com/merchants/answer/10146130) - - After inserting, updating a promotion input, it may - take several minutes before the final promotion can - be retrieved. - - """ - # 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, promotions.InsertPromotionRequest): - request = promotions.InsertPromotionRequest(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_promotion] - - # Certain 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 get_promotion(self, - request: Optional[Union[promotions.GetPromotionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> promotions.Promotion: - r"""Retrieves the promotion from your Merchant Center - account. - After inserting or updating a promotion input, it may - take several minutes before the updated promotion can be - retrieved. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_promotions_v1beta - - async def sample_get_promotion(): - # Create a client - client = merchant_promotions_v1beta.PromotionsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_promotions_v1beta.GetPromotionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_promotion(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_promotions_v1beta.types.GetPromotionRequest, dict]]): - The request object. Request message for the ``GetPromotion`` method. - name (:class:`str`): - Required. The name of the promotion to retrieve. Format: - ``accounts/{account}/promotions/{promotions}`` - - 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_promotions_v1beta.types.Promotion: - Represents a promotion. See the following articles for - more details. - - Required promotion input attributes to pass data - validation checks are primarily defined below: - - \* [Promotions data - specification](\ https://support.google.com/merchants/answer/2906014) - \* [Local promotions data - specification](\ https://support.google.com/merchants/answer/10146130) - - After inserting, updating a promotion input, it may - take several minutes before the final promotion can - be retrieved. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, promotions.GetPromotionRequest): - request = promotions.GetPromotionRequest(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_promotion] - - # Certain 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_promotions(self, - request: Optional[Union[promotions.ListPromotionsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListPromotionsAsyncPager: - r"""Lists the promotions in your Merchant Center account. The - response might contain fewer items than specified by - ``pageSize``. Rely on ``pageToken`` to determine if there are - more items to be requested. - - After inserting or updating a promotion, it may take several - minutes before the updated processed promotion can be retrieved. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_promotions_v1beta - - async def sample_list_promotions(): - # Create a client - client = merchant_promotions_v1beta.PromotionsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_promotions_v1beta.ListPromotionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_promotions(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_promotions_v1beta.types.ListPromotionsRequest, dict]]): - The request object. Request message for the ``ListPromotions`` method. - parent (:class:`str`): - Required. The account to list processed promotions 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_promotions_v1beta.services.promotions_service.pagers.ListPromotionsAsyncPager: - Response message for the ListPromotions 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, promotions.ListPromotionsRequest): - request = promotions.ListPromotionsRequest(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_promotions] - - # Certain 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.ListPromotionsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self) -> "PromotionsServiceAsyncClient": - 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__) - - -__all__ = ( - "PromotionsServiceAsyncClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/client.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/client.py deleted file mode 100644 index 85a4938180cd..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/client.py +++ /dev/null @@ -1,946 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -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_promotions_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 - -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_promotions_v1beta.services.promotions_service import pagers -from google.shopping.merchant_promotions_v1beta.types import promotions -from google.shopping.merchant_promotions_v1beta.types import promotions_common -from google.shopping.type.types import types -from .transports.base import PromotionsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import PromotionsServiceGrpcTransport -from .transports.grpc_asyncio import PromotionsServiceGrpcAsyncIOTransport -from .transports.rest import PromotionsServiceRestTransport - - -class PromotionsServiceClientMeta(type): - """Metaclass for the PromotionsService 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[PromotionsServiceTransport]] - _transport_registry["grpc"] = PromotionsServiceGrpcTransport - _transport_registry["grpc_asyncio"] = PromotionsServiceGrpcAsyncIOTransport - _transport_registry["rest"] = PromotionsServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[PromotionsServiceTransport]: - """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 PromotionsServiceClient(metaclass=PromotionsServiceClientMeta): - """Service to manage promotions for products.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = "merchantapi.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "merchantapi.{UNIVERSE_DOMAIN}" - _DEFAULT_UNIVERSE = "googleapis.com" - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - PromotionsServiceClient: 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: - PromotionsServiceClient: 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) -> PromotionsServiceTransport: - """Returns the transport used by the client instance. - - Returns: - PromotionsServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def promotion_path(account: str,promotion: str,) -> str: - """Returns a fully-qualified promotion string.""" - return "accounts/{account}/promotions/{promotion}".format(account=account, promotion=promotion, ) - - @staticmethod - def parse_promotion_path(path: str) -> Dict[str,str]: - """Parses a promotion path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/promotions/(?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 = PromotionsServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = PromotionsServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = PromotionsServiceClient._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 = PromotionsServiceClient._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 - - @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, PromotionsServiceTransport, Callable[..., PromotionsServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the promotions 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,PromotionsServiceTransport,Callable[..., PromotionsServiceTransport]]]): - 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 PromotionsServiceTransport 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 = PromotionsServiceClient._read_environment_variables() - self._client_cert_source = PromotionsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = PromotionsServiceClient._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, PromotionsServiceTransport) - if transport_provided: - # transport is a PromotionsServiceTransport 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(PromotionsServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - PromotionsServiceClient._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[PromotionsServiceTransport], Callable[..., PromotionsServiceTransport]] = ( - PromotionsServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., PromotionsServiceTransport], 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.promotions_v1beta.PromotionsServiceClient`.", - extra = { - "serviceName": "google.shopping.merchant.promotions.v1beta.PromotionsService", - "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.promotions.v1beta.PromotionsService", - "credentialsType": None, - } - ) - - def insert_promotion(self, - request: Optional[Union[promotions.InsertPromotionRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> promotions.Promotion: - r"""Inserts a promotion for your Merchant Center account. - If the promotion already exists, then it updates the - promotion instead. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_promotions_v1beta - - def sample_insert_promotion(): - # Create a client - client = merchant_promotions_v1beta.PromotionsServiceClient() - - # Initialize request argument(s) - promotion = merchant_promotions_v1beta.Promotion() - promotion.promotion_id = "promotion_id_value" - promotion.content_language = "content_language_value" - promotion.target_country = "target_country_value" - promotion.redemption_channel = ['ONLINE'] - - request = merchant_promotions_v1beta.InsertPromotionRequest( - parent="parent_value", - promotion=promotion, - data_source="data_source_value", - ) - - # Make the request - response = client.insert_promotion(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_promotions_v1beta.types.InsertPromotionRequest, dict]): - The request object. Request message for the ``InsertPromotion`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.shopping.merchant_promotions_v1beta.types.Promotion: - Represents a promotion. See the following articles for - more details. - - Required promotion input attributes to pass data - validation checks are primarily defined below: - - \* [Promotions data - specification](\ https://support.google.com/merchants/answer/2906014) - \* [Local promotions data - specification](\ https://support.google.com/merchants/answer/10146130) - - After inserting, updating a promotion input, it may - take several minutes before the final promotion can - be retrieved. - - """ - # 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, promotions.InsertPromotionRequest): - request = promotions.InsertPromotionRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.insert_promotion] - - # Certain 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 get_promotion(self, - request: Optional[Union[promotions.GetPromotionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> promotions.Promotion: - r"""Retrieves the promotion from your Merchant Center - account. - After inserting or updating a promotion input, it may - take several minutes before the updated promotion can be - retrieved. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_promotions_v1beta - - def sample_get_promotion(): - # Create a client - client = merchant_promotions_v1beta.PromotionsServiceClient() - - # Initialize request argument(s) - request = merchant_promotions_v1beta.GetPromotionRequest( - name="name_value", - ) - - # Make the request - response = client.get_promotion(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_promotions_v1beta.types.GetPromotionRequest, dict]): - The request object. Request message for the ``GetPromotion`` method. - name (str): - Required. The name of the promotion to retrieve. Format: - ``accounts/{account}/promotions/{promotions}`` - - 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_promotions_v1beta.types.Promotion: - Represents a promotion. See the following articles for - more details. - - Required promotion input attributes to pass data - validation checks are primarily defined below: - - \* [Promotions data - specification](\ https://support.google.com/merchants/answer/2906014) - \* [Local promotions data - specification](\ https://support.google.com/merchants/answer/10146130) - - After inserting, updating a promotion input, it may - take several minutes before the final promotion can - be retrieved. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, promotions.GetPromotionRequest): - request = promotions.GetPromotionRequest(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_promotion] - - # Certain 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_promotions(self, - request: Optional[Union[promotions.ListPromotionsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListPromotionsPager: - r"""Lists the promotions in your Merchant Center account. The - response might contain fewer items than specified by - ``pageSize``. Rely on ``pageToken`` to determine if there are - more items to be requested. - - After inserting or updating a promotion, it may take several - minutes before the updated processed promotion can be retrieved. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_promotions_v1beta - - def sample_list_promotions(): - # Create a client - client = merchant_promotions_v1beta.PromotionsServiceClient() - - # Initialize request argument(s) - request = merchant_promotions_v1beta.ListPromotionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_promotions(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.shopping.merchant_promotions_v1beta.types.ListPromotionsRequest, dict]): - The request object. Request message for the ``ListPromotions`` method. - parent (str): - Required. The account to list processed promotions 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_promotions_v1beta.services.promotions_service.pagers.ListPromotionsPager: - Response message for the ListPromotions 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, promotions.ListPromotionsRequest): - request = promotions.ListPromotionsRequest(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_promotions] - - # Certain 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.ListPromotionsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "PromotionsServiceClient": - 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__) - - -__all__ = ( - "PromotionsServiceClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/pagers.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/pagers.py deleted file mode 100644 index 5ca325dd375e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/pagers.py +++ /dev/null @@ -1,166 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_promotions_v1beta.types import promotions - - -class ListPromotionsPager: - """A pager for iterating through ``list_promotions`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_promotions_v1beta.types.ListPromotionsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``promotions`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListPromotions`` requests and continue to iterate - through the ``promotions`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_promotions_v1beta.types.ListPromotionsResponse` - 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[..., promotions.ListPromotionsResponse], - request: promotions.ListPromotionsRequest, - response: promotions.ListPromotionsResponse, - *, - 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_promotions_v1beta.types.ListPromotionsRequest): - The initial request object. - response (google.shopping.merchant_promotions_v1beta.types.ListPromotionsResponse): - 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 = promotions.ListPromotionsRequest(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[promotions.ListPromotionsResponse]: - 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[promotions.Promotion]: - for page in self.pages: - yield from page.promotions - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListPromotionsAsyncPager: - """A pager for iterating through ``list_promotions`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_promotions_v1beta.types.ListPromotionsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``promotions`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListPromotions`` requests and continue to iterate - through the ``promotions`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_promotions_v1beta.types.ListPromotionsResponse` - 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[promotions.ListPromotionsResponse]], - request: promotions.ListPromotionsRequest, - response: promotions.ListPromotionsResponse, - *, - 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_promotions_v1beta.types.ListPromotionsRequest): - The initial request object. - response (google.shopping.merchant_promotions_v1beta.types.ListPromotionsResponse): - 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 = promotions.ListPromotionsRequest(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[promotions.ListPromotionsResponse]: - 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[promotions.Promotion]: - async def async_generator(): - async for page in self.pages: - for response in page.promotions: - 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-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/README.rst deleted file mode 100644 index 8e430c8e2e3a..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`PromotionsServiceTransport` is the ABC for all transports. -- public child `PromotionsServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `PromotionsServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BasePromotionsServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `PromotionsServiceRestTransport` 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-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/__init__.py deleted file mode 100644 index 6f04436b2cd7..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 PromotionsServiceTransport -from .grpc import PromotionsServiceGrpcTransport -from .grpc_asyncio import PromotionsServiceGrpcAsyncIOTransport -from .rest import PromotionsServiceRestTransport -from .rest import PromotionsServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[PromotionsServiceTransport]] -_transport_registry['grpc'] = PromotionsServiceGrpcTransport -_transport_registry['grpc_asyncio'] = PromotionsServiceGrpcAsyncIOTransport -_transport_registry['rest'] = PromotionsServiceRestTransport - -__all__ = ( - 'PromotionsServiceTransport', - 'PromotionsServiceGrpcTransport', - 'PromotionsServiceGrpcAsyncIOTransport', - 'PromotionsServiceRestTransport', - 'PromotionsServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/base.py deleted file mode 100644 index 7890c6625a55..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/base.py +++ /dev/null @@ -1,182 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_promotions_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 - -from google.shopping.merchant_promotions_v1beta.types import promotions - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class PromotionsServiceTransport(abc.ABC): - """Abstract transport class for PromotionsService.""" - - 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.insert_promotion: gapic_v1.method.wrap_method( - self.insert_promotion, - default_timeout=None, - client_info=client_info, - ), - self.get_promotion: gapic_v1.method.wrap_method( - self.get_promotion, - default_timeout=None, - client_info=client_info, - ), - self.list_promotions: gapic_v1.method.wrap_method( - self.list_promotions, - 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 insert_promotion(self) -> Callable[ - [promotions.InsertPromotionRequest], - Union[ - promotions.Promotion, - Awaitable[promotions.Promotion] - ]]: - raise NotImplementedError() - - @property - def get_promotion(self) -> Callable[ - [promotions.GetPromotionRequest], - Union[ - promotions.Promotion, - Awaitable[promotions.Promotion] - ]]: - raise NotImplementedError() - - @property - def list_promotions(self) -> Callable[ - [promotions.ListPromotionsRequest], - Union[ - promotions.ListPromotionsResponse, - Awaitable[promotions.ListPromotionsResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'PromotionsServiceTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/grpc.py deleted file mode 100644 index 202e50e8a426..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/grpc.py +++ /dev/null @@ -1,411 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_promotions_v1beta.types import promotions -from .base import PromotionsServiceTransport, 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.promotions.v1beta.PromotionsService", - "rpcName": 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.promotions.v1beta.PromotionsService", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class PromotionsServiceGrpcTransport(PromotionsServiceTransport): - """gRPC backend transport for PromotionsService. - - Service to manage promotions for products. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'merchantapi.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'merchantapi.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if a ``channel`` instance is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if a ``channel`` instance is provided. - channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, grpc.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) - - # Wrap messages. This must be done after self._logged_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'merchantapi.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def insert_promotion(self) -> Callable[ - [promotions.InsertPromotionRequest], - promotions.Promotion]: - r"""Return a callable for the insert promotion method over gRPC. - - Inserts a promotion for your Merchant Center account. - If the promotion already exists, then it updates the - promotion instead. - - Returns: - Callable[[~.InsertPromotionRequest], - ~.Promotion]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_promotion' not in self._stubs: - self._stubs['insert_promotion'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.promotions.v1beta.PromotionsService/InsertPromotion', - request_serializer=promotions.InsertPromotionRequest.serialize, - response_deserializer=promotions.Promotion.deserialize, - ) - return self._stubs['insert_promotion'] - - @property - def get_promotion(self) -> Callable[ - [promotions.GetPromotionRequest], - promotions.Promotion]: - r"""Return a callable for the get promotion method over gRPC. - - Retrieves the promotion from your Merchant Center - account. - After inserting or updating a promotion input, it may - take several minutes before the updated promotion can be - retrieved. - - Returns: - Callable[[~.GetPromotionRequest], - ~.Promotion]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_promotion' not in self._stubs: - self._stubs['get_promotion'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.promotions.v1beta.PromotionsService/GetPromotion', - request_serializer=promotions.GetPromotionRequest.serialize, - response_deserializer=promotions.Promotion.deserialize, - ) - return self._stubs['get_promotion'] - - @property - def list_promotions(self) -> Callable[ - [promotions.ListPromotionsRequest], - promotions.ListPromotionsResponse]: - r"""Return a callable for the list promotions method over gRPC. - - Lists the promotions in your Merchant Center account. The - response might contain fewer items than specified by - ``pageSize``. Rely on ``pageToken`` to determine if there are - more items to be requested. - - After inserting or updating a promotion, it may take several - minutes before the updated processed promotion can be retrieved. - - Returns: - Callable[[~.ListPromotionsRequest], - ~.ListPromotionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_promotions' not in self._stubs: - self._stubs['list_promotions'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.promotions.v1beta.PromotionsService/ListPromotions', - request_serializer=promotions.ListPromotionsRequest.serialize, - response_deserializer=promotions.ListPromotionsResponse.deserialize, - ) - return self._stubs['list_promotions'] - - def close(self): - self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'PromotionsServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/grpc_asyncio.py deleted file mode 100644 index 8d41e6f30075..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,441 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_promotions_v1beta.types import promotions -from .base import PromotionsServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import PromotionsServiceGrpcTransport - -try: - from google.api_core import client_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.promotions.v1beta.PromotionsService", - "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.promotions.v1beta.PromotionsService", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class PromotionsServiceGrpcAsyncIOTransport(PromotionsServiceTransport): - """gRPC AsyncIO backend transport for PromotionsService. - - Service to manage promotions for products. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'merchantapi.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'merchantapi.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'merchantapi.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if a ``channel`` instance is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, aio.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - self._interceptor = _LoggingClientAIOInterceptor() - self._grpc_channel._unary_unary_interceptors.append(self._interceptor) - self._logged_channel = self._grpc_channel - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - # Wrap messages. This must be done after self._logged_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def insert_promotion(self) -> Callable[ - [promotions.InsertPromotionRequest], - Awaitable[promotions.Promotion]]: - r"""Return a callable for the insert promotion method over gRPC. - - Inserts a promotion for your Merchant Center account. - If the promotion already exists, then it updates the - promotion instead. - - Returns: - Callable[[~.InsertPromotionRequest], - Awaitable[~.Promotion]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_promotion' not in self._stubs: - self._stubs['insert_promotion'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.promotions.v1beta.PromotionsService/InsertPromotion', - request_serializer=promotions.InsertPromotionRequest.serialize, - response_deserializer=promotions.Promotion.deserialize, - ) - return self._stubs['insert_promotion'] - - @property - def get_promotion(self) -> Callable[ - [promotions.GetPromotionRequest], - Awaitable[promotions.Promotion]]: - r"""Return a callable for the get promotion method over gRPC. - - Retrieves the promotion from your Merchant Center - account. - After inserting or updating a promotion input, it may - take several minutes before the updated promotion can be - retrieved. - - Returns: - Callable[[~.GetPromotionRequest], - Awaitable[~.Promotion]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_promotion' not in self._stubs: - self._stubs['get_promotion'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.promotions.v1beta.PromotionsService/GetPromotion', - request_serializer=promotions.GetPromotionRequest.serialize, - response_deserializer=promotions.Promotion.deserialize, - ) - return self._stubs['get_promotion'] - - @property - def list_promotions(self) -> Callable[ - [promotions.ListPromotionsRequest], - Awaitable[promotions.ListPromotionsResponse]]: - r"""Return a callable for the list promotions method over gRPC. - - Lists the promotions in your Merchant Center account. The - response might contain fewer items than specified by - ``pageSize``. Rely on ``pageToken`` to determine if there are - more items to be requested. - - After inserting or updating a promotion, it may take several - minutes before the updated processed promotion can be retrieved. - - Returns: - Callable[[~.ListPromotionsRequest], - Awaitable[~.ListPromotionsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_promotions' not in self._stubs: - self._stubs['list_promotions'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.promotions.v1beta.PromotionsService/ListPromotions', - request_serializer=promotions.ListPromotionsRequest.serialize, - response_deserializer=promotions.ListPromotionsResponse.deserialize, - ) - return self._stubs['list_promotions'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.insert_promotion: self._wrap_method( - self.insert_promotion, - default_timeout=None, - client_info=client_info, - ), - self.get_promotion: self._wrap_method( - self.get_promotion, - default_timeout=None, - client_info=client_info, - ), - self.list_promotions: self._wrap_method( - self.list_promotions, - 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__ = ( - 'PromotionsServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/rest.py deleted file mode 100644 index fe0219eb6838..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/rest.py +++ /dev/null @@ -1,657 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -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_promotions_v1beta.types import promotions - - -from .rest_base import _BasePromotionsServiceRestTransport -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}", -) - - -class PromotionsServiceRestInterceptor: - """Interceptor for PromotionsService. - - 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 PromotionsServiceRestTransport. - - .. code-block:: python - class MyCustomPromotionsServiceInterceptor(PromotionsServiceRestInterceptor): - def pre_get_promotion(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_promotion(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_insert_promotion(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_insert_promotion(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_promotions(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_promotions(self, response): - logging.log(f"Received response: {response}") - return response - - transport = PromotionsServiceRestTransport(interceptor=MyCustomPromotionsServiceInterceptor()) - client = PromotionsServiceClient(transport=transport) - - - """ - def pre_get_promotion(self, request: promotions.GetPromotionRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[promotions.GetPromotionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_promotion - - Override in a subclass to manipulate the request or metadata - before they are sent to the PromotionsService server. - """ - return request, metadata - - def post_get_promotion(self, response: promotions.Promotion) -> promotions.Promotion: - """Post-rpc interceptor for get_promotion - - Override in a subclass to manipulate the response - after it is returned by the PromotionsService server but before - it is returned to user code. - """ - return response - - def pre_insert_promotion(self, request: promotions.InsertPromotionRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[promotions.InsertPromotionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for insert_promotion - - Override in a subclass to manipulate the request or metadata - before they are sent to the PromotionsService server. - """ - return request, metadata - - def post_insert_promotion(self, response: promotions.Promotion) -> promotions.Promotion: - """Post-rpc interceptor for insert_promotion - - Override in a subclass to manipulate the response - after it is returned by the PromotionsService server but before - it is returned to user code. - """ - return response - - def pre_list_promotions(self, request: promotions.ListPromotionsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[promotions.ListPromotionsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_promotions - - Override in a subclass to manipulate the request or metadata - before they are sent to the PromotionsService server. - """ - return request, metadata - - def post_list_promotions(self, response: promotions.ListPromotionsResponse) -> promotions.ListPromotionsResponse: - """Post-rpc interceptor for list_promotions - - Override in a subclass to manipulate the response - after it is returned by the PromotionsService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class PromotionsServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: PromotionsServiceRestInterceptor - - -class PromotionsServiceRestTransport(_BasePromotionsServiceRestTransport): - """REST backend synchronous transport for PromotionsService. - - Service to manage promotions for products. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - """ - - def __init__(self, *, - host: str = 'merchantapi.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[PromotionsServiceRestInterceptor] = 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 PromotionsServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _GetPromotion(_BasePromotionsServiceRestTransport._BaseGetPromotion, PromotionsServiceRestStub): - def __hash__(self): - return hash("PromotionsServiceRestTransport.GetPromotion") - - @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: promotions.GetPromotionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> promotions.Promotion: - r"""Call the get promotion method over HTTP. - - Args: - request (~.promotions.GetPromotionRequest): - The request object. Request message for the ``GetPromotion`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.promotions.Promotion: - Represents a promotion. See the following articles for - more details. - - Required promotion input attributes to pass data - validation checks are primarily defined below: - - - `Promotions data - specification `__ - - `Local promotions data - specification `__ - - After inserting, updating a promotion input, it may take - several minutes before the final promotion can be - retrieved. - - """ - - http_options = _BasePromotionsServiceRestTransport._BaseGetPromotion._get_http_options() - - request, metadata = self._interceptor.pre_get_promotion(request, metadata) - transcoded_request = _BasePromotionsServiceRestTransport._BaseGetPromotion._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BasePromotionsServiceRestTransport._BaseGetPromotion._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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.promotions_v1beta.PromotionsServiceClient.GetPromotion", - extra = { - "serviceName": "google.shopping.merchant.promotions.v1beta.PromotionsService", - "rpcName": "GetPromotion", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = PromotionsServiceRestTransport._GetPromotion._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 = promotions.Promotion() - pb_resp = promotions.Promotion.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_promotion(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = promotions.Promotion.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.promotions_v1beta.PromotionsServiceClient.get_promotion", - extra = { - "serviceName": "google.shopping.merchant.promotions.v1beta.PromotionsService", - "rpcName": "GetPromotion", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _InsertPromotion(_BasePromotionsServiceRestTransport._BaseInsertPromotion, PromotionsServiceRestStub): - def __hash__(self): - return hash("PromotionsServiceRestTransport.InsertPromotion") - - @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: promotions.InsertPromotionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> promotions.Promotion: - r"""Call the insert promotion method over HTTP. - - Args: - request (~.promotions.InsertPromotionRequest): - The request object. Request message for the ``InsertPromotion`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.promotions.Promotion: - Represents a promotion. See the following articles for - more details. - - Required promotion input attributes to pass data - validation checks are primarily defined below: - - - `Promotions data - specification `__ - - `Local promotions data - specification `__ - - After inserting, updating a promotion input, it may take - several minutes before the final promotion can be - retrieved. - - """ - - http_options = _BasePromotionsServiceRestTransport._BaseInsertPromotion._get_http_options() - - request, metadata = self._interceptor.pre_insert_promotion(request, metadata) - transcoded_request = _BasePromotionsServiceRestTransport._BaseInsertPromotion._get_transcoded_request(http_options, request) - - body = _BasePromotionsServiceRestTransport._BaseInsertPromotion._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BasePromotionsServiceRestTransport._BaseInsertPromotion._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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.promotions_v1beta.PromotionsServiceClient.InsertPromotion", - extra = { - "serviceName": "google.shopping.merchant.promotions.v1beta.PromotionsService", - "rpcName": "InsertPromotion", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = PromotionsServiceRestTransport._InsertPromotion._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 = promotions.Promotion() - pb_resp = promotions.Promotion.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_insert_promotion(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = promotions.Promotion.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.promotions_v1beta.PromotionsServiceClient.insert_promotion", - extra = { - "serviceName": "google.shopping.merchant.promotions.v1beta.PromotionsService", - "rpcName": "InsertPromotion", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListPromotions(_BasePromotionsServiceRestTransport._BaseListPromotions, PromotionsServiceRestStub): - def __hash__(self): - return hash("PromotionsServiceRestTransport.ListPromotions") - - @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: promotions.ListPromotionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> promotions.ListPromotionsResponse: - r"""Call the list promotions method over HTTP. - - Args: - request (~.promotions.ListPromotionsRequest): - The request object. Request message for the ``ListPromotions`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.promotions.ListPromotionsResponse: - Response message for the ``ListPromotions`` method. - """ - - http_options = _BasePromotionsServiceRestTransport._BaseListPromotions._get_http_options() - - request, metadata = self._interceptor.pre_list_promotions(request, metadata) - transcoded_request = _BasePromotionsServiceRestTransport._BaseListPromotions._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BasePromotionsServiceRestTransport._BaseListPromotions._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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.promotions_v1beta.PromotionsServiceClient.ListPromotions", - extra = { - "serviceName": "google.shopping.merchant.promotions.v1beta.PromotionsService", - "rpcName": "ListPromotions", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = PromotionsServiceRestTransport._ListPromotions._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 = promotions.ListPromotionsResponse() - pb_resp = promotions.ListPromotionsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_promotions(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = promotions.ListPromotionsResponse.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.promotions_v1beta.PromotionsServiceClient.list_promotions", - extra = { - "serviceName": "google.shopping.merchant.promotions.v1beta.PromotionsService", - "rpcName": "ListPromotions", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def get_promotion(self) -> Callable[ - [promotions.GetPromotionRequest], - promotions.Promotion]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetPromotion(self._session, self._host, self._interceptor) # type: ignore - - @property - def insert_promotion(self) -> Callable[ - [promotions.InsertPromotionRequest], - promotions.Promotion]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._InsertPromotion(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_promotions(self) -> Callable[ - [promotions.ListPromotionsRequest], - promotions.ListPromotionsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListPromotions(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'PromotionsServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/rest_base.py deleted file mode 100644 index aab3dec4695e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/rest_base.py +++ /dev/null @@ -1,212 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 PromotionsServiceTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.shopping.merchant_promotions_v1beta.types import promotions - - -class _BasePromotionsServiceRestTransport(PromotionsServiceTransport): - """Base REST backend transport for PromotionsService. - - 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 _BaseGetPromotion: - 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': '/promotions/v1beta/{name=accounts/*/promotions/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = promotions.GetPromotionRequest.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(_BasePromotionsServiceRestTransport._BaseGetPromotion._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseInsertPromotion: - 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': '/promotions/v1beta/{parent=accounts/*}/promotions:insert', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = promotions.InsertPromotionRequest.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(_BasePromotionsServiceRestTransport._BaseInsertPromotion._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListPromotions: - 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': '/promotions/v1beta/{parent=accounts/*}/promotions', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = promotions.ListPromotionsRequest.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(_BasePromotionsServiceRestTransport._BaseListPromotions._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BasePromotionsServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/types/__init__.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/types/__init__.py deleted file mode 100644 index aa349ec9d51f..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/types/__init__.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .promotions import ( - GetPromotionRequest, - InsertPromotionRequest, - ListPromotionsRequest, - ListPromotionsResponse, - Promotion, -) -from .promotions_common import ( - Attributes, - PromotionStatus, - CouponValueType, - OfferType, - ProductApplicability, - RedemptionChannel, - StoreApplicability, -) - -__all__ = ( - 'GetPromotionRequest', - 'InsertPromotionRequest', - 'ListPromotionsRequest', - 'ListPromotionsResponse', - 'Promotion', - 'Attributes', - 'PromotionStatus', - 'CouponValueType', - 'OfferType', - 'ProductApplicability', - 'RedemptionChannel', - 'StoreApplicability', -) diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/types/promotions.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/types/promotions.py deleted file mode 100644 index d3d9283e4324..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/types/promotions.py +++ /dev/null @@ -1,277 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_promotions_v1beta.types import promotions_common -from google.shopping.type.types import types - - -__protobuf__ = proto.module( - package='google.shopping.merchant.promotions.v1beta', - manifest={ - 'Promotion', - 'InsertPromotionRequest', - 'GetPromotionRequest', - 'ListPromotionsRequest', - 'ListPromotionsResponse', - }, -) - - -class Promotion(proto.Message): - r"""Represents a promotion. See the following articles for more details. - - Required promotion input attributes to pass data validation checks - are primarily defined below: - - - `Promotions data - specification `__ - - `Local promotions data - specification `__ - - After inserting, updating a promotion input, it may take several - minutes before the final promotion can be retrieved. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - Identifier. The name of the promotion. Format: - ``accounts/{account}/promotions/{promotion}`` - promotion_id (str): - Required. The user provided promotion ID to uniquely - identify the promotion. Follow `minimum - requirements `__ - to prevent promotion disapprovals. - content_language (str): - Required. The two-letter `ISO - 639-1 `__ language - code for the promotion. - - Promotions is only for `selected - languages `__. - target_country (str): - Required. The target country used as part of the unique - identifier. Represented as a `CLDR territory - code `__. - - Promotions are only available in selected countries, `Free - Listings and Shopping - ads `__ - `Local Inventory - ads `__ - redemption_channel (MutableSequence[google.shopping.merchant_promotions_v1beta.types.RedemptionChannel]): - Required. `Redemption - channel `__ - for the promotion. At least one channel is required. - data_source (str): - Output only. The primary data source of the - promotion. - attributes (google.shopping.merchant_promotions_v1beta.types.Attributes): - Optional. A list of promotion attributes. - custom_attributes (MutableSequence[google.shopping.type.types.CustomAttribute]): - Optional. A list of custom (merchant-provided) attributes. - It can also be used for submitting any attribute of the data - specification in its generic form (for example, - ``{ "name": "size type", "value": "regular" }``). This is - useful for submitting attributes not explicitly exposed by - the API. - promotion_status (google.shopping.merchant_promotions_v1beta.types.PromotionStatus): - Output only. The `status of a - promotion `__, - data validation issues, that is, information about a - promotion computed asynchronously. - version_number (int): - Optional. Represents the existing version (freshness) of the - promotion, which can be used to preserve the right order - when multiple updates are done at the same time. - - If set, the insertion is prevented when version number is - lower than the current version number of the existing - promotion. Re-insertion (for example, promotion refresh - after 30 days) can be performed with the current - ``version_number``. - - If the operation is prevented, the aborted exception will be - thrown. - - This field is a member of `oneof`_ ``_version_number``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - promotion_id: str = proto.Field( - proto.STRING, - number=2, - ) - content_language: str = proto.Field( - proto.STRING, - number=3, - ) - target_country: str = proto.Field( - proto.STRING, - number=4, - ) - redemption_channel: MutableSequence[promotions_common.RedemptionChannel] = proto.RepeatedField( - proto.ENUM, - number=5, - enum=promotions_common.RedemptionChannel, - ) - data_source: str = proto.Field( - proto.STRING, - number=6, - ) - attributes: promotions_common.Attributes = proto.Field( - proto.MESSAGE, - number=7, - message=promotions_common.Attributes, - ) - custom_attributes: MutableSequence[types.CustomAttribute] = proto.RepeatedField( - proto.MESSAGE, - number=8, - message=types.CustomAttribute, - ) - promotion_status: promotions_common.PromotionStatus = proto.Field( - proto.MESSAGE, - number=9, - message=promotions_common.PromotionStatus, - ) - version_number: int = proto.Field( - proto.INT64, - number=10, - optional=True, - ) - - -class InsertPromotionRequest(proto.Message): - r"""Request message for the ``InsertPromotion`` method. - - Attributes: - parent (str): - Required. The account where the promotion - will be inserted. Format: accounts/{account} - promotion (google.shopping.merchant_promotions_v1beta.types.Promotion): - Required. The promotion to insert. - data_source (str): - Required. The data source of the - `promotion `__ - Format: ``accounts/{account}/dataSources/{datasource}``. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - promotion: 'Promotion' = proto.Field( - proto.MESSAGE, - number=2, - message='Promotion', - ) - data_source: str = proto.Field( - proto.STRING, - number=3, - ) - - -class GetPromotionRequest(proto.Message): - r"""Request message for the ``GetPromotion`` method. - - Attributes: - name (str): - Required. The name of the promotion to retrieve. Format: - ``accounts/{account}/promotions/{promotions}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListPromotionsRequest(proto.Message): - r"""Request message for the ``ListPromotions`` method. - - Attributes: - parent (str): - Required. The account to list processed promotions for. - Format: ``accounts/{account}`` - page_size (int): - Output only. The maximum number of promotions - to return. The service may return fewer than - this value. The maximum value is 1000; values - above 1000 will be coerced to 1000. If - unspecified, the maximum number of promotions - will be returned. - page_token (str): - Output only. A page token, received from a previous - ``ListPromotions`` call. Provide this to retrieve the - subsequent page. - - When paginating, all other parameters provided to - ``ListPromotions`` 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 ListPromotionsResponse(proto.Message): - r"""Response message for the ``ListPromotions`` method. - - Attributes: - promotions (MutableSequence[google.shopping.merchant_promotions_v1beta.types.Promotion]): - The processed promotions 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 - - promotions: MutableSequence['Promotion'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Promotion', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/types/promotions_common.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/types/promotions_common.py deleted file mode 100644 index 290e4bcf4ee5..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/google/shopping/merchant_promotions_v1beta/types/promotions_common.py +++ /dev/null @@ -1,671 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 timestamp_pb2 # type: ignore -from google.shopping.type.types import types -from google.type import interval_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.shopping.merchant.promotions.v1beta', - manifest={ - 'ProductApplicability', - 'StoreApplicability', - 'OfferType', - 'RedemptionChannel', - 'CouponValueType', - 'Attributes', - 'PromotionStatus', - }, -) - - -class ProductApplicability(proto.Enum): - r"""Which product or list of products the promotion applies to. - - Values: - PRODUCT_APPLICABILITY_UNSPECIFIED (0): - Which products the promotion applies to is - unknown. - ALL_PRODUCTS (1): - Applicable to all products. - SPECIFIC_PRODUCTS (2): - Applicable to only a single product or list - of products. - """ - PRODUCT_APPLICABILITY_UNSPECIFIED = 0 - ALL_PRODUCTS = 1 - SPECIFIC_PRODUCTS = 2 - - -class StoreApplicability(proto.Enum): - r"""Store codes or list of store codes the promotion applies to. - Only for Local inventory ads promotions. - - Values: - STORE_APPLICABILITY_UNSPECIFIED (0): - Which store codes the promotion applies to is - unknown. - ALL_STORES (1): - Promotion applies to all stores. - SPECIFIC_STORES (2): - Promotion applies to only the specified - stores. - """ - STORE_APPLICABILITY_UNSPECIFIED = 0 - ALL_STORES = 1 - SPECIFIC_STORES = 2 - - -class OfferType(proto.Enum): - r"""Offer type of a promotion. - - Values: - OFFER_TYPE_UNSPECIFIED (0): - Unknown offer type. - NO_CODE (1): - Offer type without a code. - GENERIC_CODE (2): - Offer type with a code. Generic redemption code for the - promotion is required when ``offerType`` = ``GENERIC_CODE``. - """ - OFFER_TYPE_UNSPECIFIED = 0 - NO_CODE = 1 - GENERIC_CODE = 2 - - -class RedemptionChannel(proto.Enum): - r"""Channel of a promotion. - - Values: - REDEMPTION_CHANNEL_UNSPECIFIED (0): - Indicates that the channel is unspecified. - IN_STORE (1): - Indicates that the channel is in store. This is same as - ``local`` channel used for ``products``. - ONLINE (2): - Indicates that the channel is online. - """ - REDEMPTION_CHANNEL_UNSPECIFIED = 0 - IN_STORE = 1 - ONLINE = 2 - - -class CouponValueType(proto.Enum): - r"""`Coupon value - type `__ - of a promotion. - - Values: - COUPON_VALUE_TYPE_UNSPECIFIED (0): - Indicates that the coupon value type is - unspecified. - MONEY_OFF (1): - Money off coupon value type. - PERCENT_OFF (2): - Percent off coupon value type. - BUY_M_GET_N_MONEY_OFF (3): - Buy M quantity, get N money off coupon value type. - ``minimum_purchase_quantity`` and - ``get_this_quantity_discounted`` must be present. - ``money_off_amount`` must also be present. - BUY_M_GET_N_PERCENT_OFF (4): - Buy M quantity, get N percent off coupon value type. - ``minimum_purchase_quantity`` and - ``get_this_quantity_discounted`` must be present. - ``percent_off_percentage`` must also be present. - BUY_M_GET_MONEY_OFF (5): - Buy M quantity, get money off. ``minimum_purchase_quantity`` - and ``money_off_amount`` must be present. - BUY_M_GET_PERCENT_OFF (6): - Buy M quantity, get money off. ``minimum_purchase_quantity`` - and ``percent_off_percentage`` must be present. - FREE_GIFT (7): - Free gift with description only. - FREE_GIFT_WITH_VALUE (8): - Free gift with monetary value. - FREE_GIFT_WITH_ITEM_ID (9): - Free gift with item ID. - FREE_SHIPPING_STANDARD (10): - Standard free shipping coupon value type. - FREE_SHIPPING_OVERNIGHT (11): - Overnight free shipping coupon value type. - FREE_SHIPPING_TWO_DAY (12): - Two day free shipping coupon value type. - """ - COUPON_VALUE_TYPE_UNSPECIFIED = 0 - MONEY_OFF = 1 - PERCENT_OFF = 2 - BUY_M_GET_N_MONEY_OFF = 3 - BUY_M_GET_N_PERCENT_OFF = 4 - BUY_M_GET_MONEY_OFF = 5 - BUY_M_GET_PERCENT_OFF = 6 - FREE_GIFT = 7 - FREE_GIFT_WITH_VALUE = 8 - FREE_GIFT_WITH_ITEM_ID = 9 - FREE_SHIPPING_STANDARD = 10 - FREE_SHIPPING_OVERNIGHT = 11 - FREE_SHIPPING_TWO_DAY = 12 - - -class Attributes(proto.Message): - r"""Attributes. - - Attributes: - product_applicability (google.shopping.merchant_promotions_v1beta.types.ProductApplicability): - Required. Applicability of the promotion to either all - products or `only specific - products `__. - offer_type (google.shopping.merchant_promotions_v1beta.types.OfferType): - Required. - `Type `__ - of the promotion. Use this attribute to indicate whether or - not customers need a coupon code to redeem your promotion. - generic_redemption_code (str): - Optional. Generic redemption code for the promotion. To be - used with the ``offerType`` field and must meet the `minimum - requirements `__. - long_title (str): - Required. `Long - title `__ - for the promotion. - coupon_value_type (google.shopping.merchant_promotions_v1beta.types.CouponValueType): - Required. The [coupon value type] - (https://support.google.com/merchants/answer/13861986?ref_topic=13773355&sjid=17642868584668136159-NC) - attribute to signal the type of promotion that you are - running. Depending on type of the selected coupon value - `some attributes are - required `__. - promotion_destinations (MutableSequence[google.shopping.type.types.Destination.DestinationEnum]): - Required. The list of destinations where the promotion - applies to. If you don't specify a destination by including - a supported value in your data source, your promotion will - display in Shopping ads and free listings by default. - - You may have previously submitted the following values as - destinations for your products: Shopping Actions, Surfaces - across Google, Local surfaces across Google. To represent - these values use ``FREE_LISTINGS``, ``FREE_LOCAL_LISTINGS``, - ``LOCAL_INVENTORY_ADS``. For more details see `Promotion - destination `__ - item_id_inclusion (MutableSequence[str]): - Optional. Product filter by `item - ID `__ - for the promotion. The product filter attributes only - applies when the products eligible for promotion product - applicability ``product_applicability`` attribute is set to - `specific_products `__. - brand_inclusion (MutableSequence[str]): - Optional. Product filter by brand for the promotion. The - product filter attributes only applies when the products - eligible for promotion product applicability - ``product_applicability`` attribute is set to - `specific_products `__. - item_group_id_inclusion (MutableSequence[str]): - Optional. Product filter by item group ID for the promotion. - The product filter attributes only applies when the products - eligible for promotion product applicability - [product_applicability] attribute is set to - `specific_products `__. - product_type_inclusion (MutableSequence[str]): - Optional. Product filter by product type for the promotion. - The product filter attributes only applies when the products - eligible for promotion product applicability - ``product_applicability`` attribute is set to - `specific_products `__. - item_id_exclusion (MutableSequence[str]): - Optional. Product filter by `item ID - exclusion `__ - for the promotion. The product filter attributes only - applies when the products eligible for promotion product - applicability ``product_applicability`` attribute is set to - `specific_products `__. - brand_exclusion (MutableSequence[str]): - Optional. Product filter by `brand - exclusion `__ - for the promotion. The product filter attributes only - applies when the products eligible for promotion product - applicability ``product_applicability`` attribute is set to - `specific_products `__. - item_group_id_exclusion (MutableSequence[str]): - Optional. Product filter by `item group - ID `__. - The product filter attributes only applies when the products - eligible for promotion product applicability - ``product_applicability`` attribute is set to - `specific_products `__. - exclusion for the promotion. - product_type_exclusion (MutableSequence[str]): - Optional. Product filter by `product type - exclusion `__ - for the promotion. The product filter attributes only - applies when the products eligible for promotion product - applicability ``product_applicability`` attribute is set to - `specific_products `__. - minimum_purchase_amount (google.shopping.type.types.Price): - Optional. `Minimum purchase - amount `__ - for the promotion. - minimum_purchase_quantity (int): - Optional. `Minimum purchase - quantity `__ - for the promotion. - limit_quantity (int): - Optional. `Maximum purchase - quantity `__ - for the promotion. - limit_value (google.shopping.type.types.Price): - Optional. `Maximum product - price `__ - for promotion. - percent_off (int): - Optional. The `percentage - discount `__ - offered in the promotion. - money_off_amount (google.shopping.type.types.Price): - Optional. The `money off - amount `__ - offered in the promotion. - get_this_quantity_discounted (int): - Optional. The number of items discounted in the promotion. - The attribute is set when ``couponValueType`` is equal to - ``buy_m_get_n_money_off`` or ``buy_m_get_n_percent_off``. - free_gift_value (google.shopping.type.types.Price): - Optional. `Free gift - value `__ - for the promotion. - free_gift_description (str): - Optional. `Free gift - description `__ - for the promotion. - free_gift_item_id (str): - Optional. `Free gift item - ID `__ - for the promotion. - promotion_effective_time_period (google.type.interval_pb2.Interval): - Required. ``TimePeriod`` representation of the promotion's - effective dates. This attribute specifies that the promotion - can be tested on your online store during this time period. - promotion_display_time_period (google.type.interval_pb2.Interval): - Optional. ``TimePeriod`` representation of the promotion's - display dates. This attribute specifies the date and time - frame when the promotion will be live on Google.com and - Shopping ads. If the display time period for promotion - ``promotion_display_time_period`` attribute is not - specified, the promotion effective time period - ``promotion_effective_time_period`` determines the date and - time frame when the promotion will be live on Google.com and - Shopping ads. - store_applicability (google.shopping.merchant_promotions_v1beta.types.StoreApplicability): - Optional. Whether the promotion applies to `all stores, or - only specified - stores `__. - Local Inventory ads promotions throw an error if no store - applicability is included. An ``INVALID_ARGUMENT`` error is - thrown if ``store_applicability`` is set to ``ALL_STORES`` - and ``store_codes_inclusion`` or ``score_code_exclusion`` is - set to a value. - store_codes_inclusion (MutableSequence[str]): - Optional. `Store codes to - include `__ - for the promotion. The store filter attributes only applies - when the ``store_applicability`` attribute is set to - `specific_stores `__. - - Store code (the store ID from your Business Profile) of the - physical store the product is sold in. See the `Local - product inventory data - specification `__ - for more information. - store_codes_exclusion (MutableSequence[str]): - Optional. `Store codes to - exclude `__ - for the promotion. The store filter attributes only applies - when the ``store_applicability`` attribute is set to - `specific_stores `__. - promotion_url (str): - Optional. URL to the page on the merchant's site where the - promotion shows. Local Inventory ads promotions throw an - error if no ``promotion_url`` is included. URL is used to - confirm that the promotion is valid and can be redeemed. - """ - - product_applicability: 'ProductApplicability' = proto.Field( - proto.ENUM, - number=1, - enum='ProductApplicability', - ) - offer_type: 'OfferType' = proto.Field( - proto.ENUM, - number=2, - enum='OfferType', - ) - generic_redemption_code: str = proto.Field( - proto.STRING, - number=3, - ) - long_title: str = proto.Field( - proto.STRING, - number=4, - ) - coupon_value_type: 'CouponValueType' = proto.Field( - proto.ENUM, - number=5, - enum='CouponValueType', - ) - promotion_destinations: MutableSequence[types.Destination.DestinationEnum] = proto.RepeatedField( - proto.ENUM, - number=6, - enum=types.Destination.DestinationEnum, - ) - item_id_inclusion: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=7, - ) - brand_inclusion: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=8, - ) - item_group_id_inclusion: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=9, - ) - product_type_inclusion: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=10, - ) - item_id_exclusion: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=11, - ) - brand_exclusion: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=12, - ) - item_group_id_exclusion: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=13, - ) - product_type_exclusion: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=14, - ) - minimum_purchase_amount: types.Price = proto.Field( - proto.MESSAGE, - number=15, - message=types.Price, - ) - minimum_purchase_quantity: int = proto.Field( - proto.INT64, - number=16, - ) - limit_quantity: int = proto.Field( - proto.INT64, - number=17, - ) - limit_value: types.Price = proto.Field( - proto.MESSAGE, - number=18, - message=types.Price, - ) - percent_off: int = proto.Field( - proto.INT64, - number=19, - ) - money_off_amount: types.Price = proto.Field( - proto.MESSAGE, - number=20, - message=types.Price, - ) - get_this_quantity_discounted: int = proto.Field( - proto.INT64, - number=21, - ) - free_gift_value: types.Price = proto.Field( - proto.MESSAGE, - number=22, - message=types.Price, - ) - free_gift_description: str = proto.Field( - proto.STRING, - number=23, - ) - free_gift_item_id: str = proto.Field( - proto.STRING, - number=24, - ) - promotion_effective_time_period: interval_pb2.Interval = proto.Field( - proto.MESSAGE, - number=25, - message=interval_pb2.Interval, - ) - promotion_display_time_period: interval_pb2.Interval = proto.Field( - proto.MESSAGE, - number=26, - message=interval_pb2.Interval, - ) - store_applicability: 'StoreApplicability' = proto.Field( - proto.ENUM, - number=28, - enum='StoreApplicability', - ) - store_codes_inclusion: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=29, - ) - store_codes_exclusion: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=30, - ) - promotion_url: str = proto.Field( - proto.STRING, - number=31, - ) - - -class PromotionStatus(proto.Message): - r"""The status of the promotion. - - Attributes: - destination_statuses (MutableSequence[google.shopping.merchant_promotions_v1beta.types.PromotionStatus.DestinationStatus]): - Output only. The intended destinations for - the promotion. - item_level_issues (MutableSequence[google.shopping.merchant_promotions_v1beta.types.PromotionStatus.ItemLevelIssue]): - Output only. A list of issues associated with - the promotion. - creation_date (google.protobuf.timestamp_pb2.Timestamp): - Output only. Date on which the promotion has been created in - `ISO 8601 `__ format: - Date, time, and offset, for example - ``2020-01-02T09:00:00+01:00`` or ``2020-01-02T09:00:00Z`` - last_update_date (google.protobuf.timestamp_pb2.Timestamp): - Output only. Date on which the promotion status has been - last updated in `ISO - 8601 `__ format: - Date, time, and offset, for example - ``2020-01-02T09:00:00+01:00`` or ``2020-01-02T09:00:00Z`` - """ - - class DestinationStatus(proto.Message): - r"""The status for the specified destination. - - Attributes: - reporting_context (google.shopping.type.types.ReportingContext.ReportingContextEnum): - Output only. The name of the promotion - destination. - status (google.shopping.merchant_promotions_v1beta.types.PromotionStatus.DestinationStatus.State): - Output only. The status for the specified - destination. - """ - class State(proto.Enum): - r"""The current state of the promotion. - - Values: - STATE_UNSPECIFIED (0): - Unknown promotion state. - IN_REVIEW (1): - The promotion is under review. - REJECTED (2): - The promotion is disapproved. - LIVE (3): - The promotion is approved and active. - STOPPED (4): - The promotion is stopped by merchant. - EXPIRED (5): - The promotion is no longer active. - PENDING (6): - The promotion is not stopped, and all reviews - are approved, but the active date is in the - future. - """ - STATE_UNSPECIFIED = 0 - IN_REVIEW = 1 - REJECTED = 2 - LIVE = 3 - STOPPED = 4 - EXPIRED = 5 - PENDING = 6 - - reporting_context: types.ReportingContext.ReportingContextEnum = proto.Field( - proto.ENUM, - number=1, - enum=types.ReportingContext.ReportingContextEnum, - ) - status: 'PromotionStatus.DestinationStatus.State' = proto.Field( - proto.ENUM, - number=2, - enum='PromotionStatus.DestinationStatus.State', - ) - - class ItemLevelIssue(proto.Message): - r"""The issue associated with the promotion. - - Attributes: - code (str): - Output only. The error code of the issue. - severity (google.shopping.merchant_promotions_v1beta.types.PromotionStatus.ItemLevelIssue.Severity): - Output only. How this issue affects serving - of the promotion. - resolution (str): - Output only. Whether the issue can be - resolved by the merchant. - attribute (str): - Output only. The attribute's name, if the - issue is caused by a single attribute. - reporting_context (google.shopping.type.types.ReportingContext.ReportingContextEnum): - Output only. The destination the issue - applies to. - description (str): - Output only. A short issue description in - English. - detail (str): - Output only. A detailed issue description in - English. - documentation (str): - Output only. The URL of a web page to help - with resolving this issue. - applicable_countries (MutableSequence[str]): - Output only. List of country codes (ISO - 3166-1 alpha-2) where issue applies to the - offer. - """ - class Severity(proto.Enum): - r"""The severity of the issue. - - Values: - SEVERITY_UNSPECIFIED (0): - Not specified. - NOT_IMPACTED (1): - This issue represents a warning and does not - have a direct affect on the promotion. - DEMOTED (2): - The promotion is demoted and most likely have - limited performance in search results - DISAPPROVED (3): - Issue disapproves the promotion. - """ - SEVERITY_UNSPECIFIED = 0 - NOT_IMPACTED = 1 - DEMOTED = 2 - DISAPPROVED = 3 - - code: str = proto.Field( - proto.STRING, - number=1, - ) - severity: 'PromotionStatus.ItemLevelIssue.Severity' = proto.Field( - proto.ENUM, - number=2, - enum='PromotionStatus.ItemLevelIssue.Severity', - ) - resolution: str = proto.Field( - proto.STRING, - number=3, - ) - attribute: str = proto.Field( - proto.STRING, - number=4, - ) - reporting_context: types.ReportingContext.ReportingContextEnum = proto.Field( - proto.ENUM, - number=5, - enum=types.ReportingContext.ReportingContextEnum, - ) - description: str = proto.Field( - proto.STRING, - number=6, - ) - detail: str = proto.Field( - proto.STRING, - number=7, - ) - documentation: str = proto.Field( - proto.STRING, - number=8, - ) - applicable_countries: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=9, - ) - - destination_statuses: MutableSequence[DestinationStatus] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=DestinationStatus, - ) - item_level_issues: MutableSequence[ItemLevelIssue] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=ItemLevelIssue, - ) - creation_date: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - last_update_date: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/mypy.ini b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/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-promotions/v1beta/noxfile.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/noxfile.py deleted file mode 100644 index 3cd901f36b88..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/noxfile.py +++ /dev/null @@ -1,280 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", - "3.12", - "3.13", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = 'google-shopping-merchant-promotions' - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.13" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "prerelease_deps", -] - -@nox.session(python=ALL_PYTHON) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def unit(session, protobuf_implementation): - """Run the unit test suite.""" - - 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+") - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") - - # 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") - - session.run( - 'py.test', - '--quiet', - '--cov=google/shopping/merchant_promotions_v1beta/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - -@nox.session(python=ALL_PYTHON[-1]) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def prerelease_deps(session, protobuf_implementation): - """Run the unit test suite against pre-release versions of dependencies.""" - - 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 test environment dependencies - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - - # Install the package without dependencies - session.install('-e', '.', '--no-deps') - - # We test the minimum dependency versions using the minimum Python - # version so the lowest python runtime that we test has a corresponding constraints - # file, located at `testing/constraints--.txt`, which contains all of the - # 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 - ) - ] - - session.install(*constraints_deps) - - prerel_deps = [ - "googleapis-common-protos", - "google-api-core", - "google-auth", - # Exclude grpcio!=1.67.0rc1 which does not support python 3.13 - "grpcio!=1.67.0rc1", - "grpcio-status", - "protobuf", - "proto-plus", - ] - - for dep in prerel_deps: - session.install("--pre", "--no-deps", "--upgrade", dep) - - # Remaining dependencies - other_deps = [ - "requests", - ] - session.install(*other_deps) - - # Print out prerelease package versions - - session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") - session.run("python", "-c", "import google.auth; print(google.auth.__version__)") - session.run("python", "-c", "import grpc; print(grpc.__version__)") - session.run( - "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" - ) - session.run( - "python", "-c", "import proto; print(proto.__version__)" - ) - - session.run( - 'py.test', - '--quiet', - '--cov=google/shopping/merchant_promotions_v1beta/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - - -@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=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 docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==7.0.1", "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=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", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_get_promotion_async.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_get_promotion_async.py deleted file mode 100644 index 66bd0db4ca0d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_get_promotion_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetPromotion -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-promotions - - -# [START merchantapi_v1beta_generated_PromotionsService_GetPromotion_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_promotions_v1beta - - -async def sample_get_promotion(): - # Create a client - client = merchant_promotions_v1beta.PromotionsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_promotions_v1beta.GetPromotionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_promotion(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_PromotionsService_GetPromotion_async] diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_get_promotion_sync.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_get_promotion_sync.py deleted file mode 100644 index 6b8e9dade3e9..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_get_promotion_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetPromotion -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-promotions - - -# [START merchantapi_v1beta_generated_PromotionsService_GetPromotion_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_promotions_v1beta - - -def sample_get_promotion(): - # Create a client - client = merchant_promotions_v1beta.PromotionsServiceClient() - - # Initialize request argument(s) - request = merchant_promotions_v1beta.GetPromotionRequest( - name="name_value", - ) - - # Make the request - response = client.get_promotion(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_PromotionsService_GetPromotion_sync] diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_insert_promotion_async.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_insert_promotion_async.py deleted file mode 100644 index d9245ecabde7..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_insert_promotion_async.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for InsertPromotion -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-promotions - - -# [START merchantapi_v1beta_generated_PromotionsService_InsertPromotion_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_promotions_v1beta - - -async def sample_insert_promotion(): - # Create a client - client = merchant_promotions_v1beta.PromotionsServiceAsyncClient() - - # Initialize request argument(s) - promotion = merchant_promotions_v1beta.Promotion() - promotion.promotion_id = "promotion_id_value" - promotion.content_language = "content_language_value" - promotion.target_country = "target_country_value" - promotion.redemption_channel = ['ONLINE'] - - request = merchant_promotions_v1beta.InsertPromotionRequest( - parent="parent_value", - promotion=promotion, - data_source="data_source_value", - ) - - # Make the request - response = await client.insert_promotion(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_PromotionsService_InsertPromotion_async] diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_insert_promotion_sync.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_insert_promotion_sync.py deleted file mode 100644 index 2fd44913b58c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_insert_promotion_sync.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for InsertPromotion -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-promotions - - -# [START merchantapi_v1beta_generated_PromotionsService_InsertPromotion_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_promotions_v1beta - - -def sample_insert_promotion(): - # Create a client - client = merchant_promotions_v1beta.PromotionsServiceClient() - - # Initialize request argument(s) - promotion = merchant_promotions_v1beta.Promotion() - promotion.promotion_id = "promotion_id_value" - promotion.content_language = "content_language_value" - promotion.target_country = "target_country_value" - promotion.redemption_channel = ['ONLINE'] - - request = merchant_promotions_v1beta.InsertPromotionRequest( - parent="parent_value", - promotion=promotion, - data_source="data_source_value", - ) - - # Make the request - response = client.insert_promotion(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_PromotionsService_InsertPromotion_sync] diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_list_promotions_async.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_list_promotions_async.py deleted file mode 100644 index ae88a1355d74..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_list_promotions_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListPromotions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-promotions - - -# [START merchantapi_v1beta_generated_PromotionsService_ListPromotions_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_promotions_v1beta - - -async def sample_list_promotions(): - # Create a client - client = merchant_promotions_v1beta.PromotionsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_promotions_v1beta.ListPromotionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_promotions(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_PromotionsService_ListPromotions_async] diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_list_promotions_sync.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_list_promotions_sync.py deleted file mode 100644 index d2d3f2a247df..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/merchantapi_v1beta_generated_promotions_service_list_promotions_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListPromotions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-promotions - - -# [START merchantapi_v1beta_generated_PromotionsService_ListPromotions_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_promotions_v1beta - - -def sample_list_promotions(): - # Create a client - client = merchant_promotions_v1beta.PromotionsServiceClient() - - # Initialize request argument(s) - request = merchant_promotions_v1beta.ListPromotionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_promotions(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_PromotionsService_ListPromotions_sync] diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.promotions.v1beta.json b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.promotions.v1beta.json deleted file mode 100644 index 35c4091b4ca2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.promotions.v1beta.json +++ /dev/null @@ -1,490 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.shopping.merchant.promotions.v1beta", - "version": "v1beta" - } - ], - "language": "PYTHON", - "name": "google-shopping-merchant-promotions", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_promotions_v1beta.PromotionsServiceAsyncClient", - "shortName": "PromotionsServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_promotions_v1beta.PromotionsServiceAsyncClient.get_promotion", - "method": { - "fullName": "google.shopping.merchant.promotions.v1beta.PromotionsService.GetPromotion", - "service": { - "fullName": "google.shopping.merchant.promotions.v1beta.PromotionsService", - "shortName": "PromotionsService" - }, - "shortName": "GetPromotion" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_promotions_v1beta.types.GetPromotionRequest" - }, - { - "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_promotions_v1beta.types.Promotion", - "shortName": "get_promotion" - }, - "description": "Sample for GetPromotion", - "file": "merchantapi_v1beta_generated_promotions_service_get_promotion_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_PromotionsService_GetPromotion_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_promotions_service_get_promotion_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_promotions_v1beta.PromotionsServiceClient", - "shortName": "PromotionsServiceClient" - }, - "fullName": "google.shopping.merchant_promotions_v1beta.PromotionsServiceClient.get_promotion", - "method": { - "fullName": "google.shopping.merchant.promotions.v1beta.PromotionsService.GetPromotion", - "service": { - "fullName": "google.shopping.merchant.promotions.v1beta.PromotionsService", - "shortName": "PromotionsService" - }, - "shortName": "GetPromotion" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_promotions_v1beta.types.GetPromotionRequest" - }, - { - "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_promotions_v1beta.types.Promotion", - "shortName": "get_promotion" - }, - "description": "Sample for GetPromotion", - "file": "merchantapi_v1beta_generated_promotions_service_get_promotion_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_PromotionsService_GetPromotion_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_promotions_service_get_promotion_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_promotions_v1beta.PromotionsServiceAsyncClient", - "shortName": "PromotionsServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_promotions_v1beta.PromotionsServiceAsyncClient.insert_promotion", - "method": { - "fullName": "google.shopping.merchant.promotions.v1beta.PromotionsService.InsertPromotion", - "service": { - "fullName": "google.shopping.merchant.promotions.v1beta.PromotionsService", - "shortName": "PromotionsService" - }, - "shortName": "InsertPromotion" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_promotions_v1beta.types.InsertPromotionRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.shopping.merchant_promotions_v1beta.types.Promotion", - "shortName": "insert_promotion" - }, - "description": "Sample for InsertPromotion", - "file": "merchantapi_v1beta_generated_promotions_service_insert_promotion_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_PromotionsService_InsertPromotion_async", - "segments": [ - { - "end": 59, - "start": 27, - "type": "FULL" - }, - { - "end": 59, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 53, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 56, - "start": 54, - "type": "REQUEST_EXECUTION" - }, - { - "end": 60, - "start": 57, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_promotions_service_insert_promotion_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_promotions_v1beta.PromotionsServiceClient", - "shortName": "PromotionsServiceClient" - }, - "fullName": "google.shopping.merchant_promotions_v1beta.PromotionsServiceClient.insert_promotion", - "method": { - "fullName": "google.shopping.merchant.promotions.v1beta.PromotionsService.InsertPromotion", - "service": { - "fullName": "google.shopping.merchant.promotions.v1beta.PromotionsService", - "shortName": "PromotionsService" - }, - "shortName": "InsertPromotion" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_promotions_v1beta.types.InsertPromotionRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.shopping.merchant_promotions_v1beta.types.Promotion", - "shortName": "insert_promotion" - }, - "description": "Sample for InsertPromotion", - "file": "merchantapi_v1beta_generated_promotions_service_insert_promotion_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_PromotionsService_InsertPromotion_sync", - "segments": [ - { - "end": 59, - "start": 27, - "type": "FULL" - }, - { - "end": 59, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 53, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 56, - "start": 54, - "type": "REQUEST_EXECUTION" - }, - { - "end": 60, - "start": 57, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_promotions_service_insert_promotion_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_promotions_v1beta.PromotionsServiceAsyncClient", - "shortName": "PromotionsServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_promotions_v1beta.PromotionsServiceAsyncClient.list_promotions", - "method": { - "fullName": "google.shopping.merchant.promotions.v1beta.PromotionsService.ListPromotions", - "service": { - "fullName": "google.shopping.merchant.promotions.v1beta.PromotionsService", - "shortName": "PromotionsService" - }, - "shortName": "ListPromotions" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_promotions_v1beta.types.ListPromotionsRequest" - }, - { - "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_promotions_v1beta.services.promotions_service.pagers.ListPromotionsAsyncPager", - "shortName": "list_promotions" - }, - "description": "Sample for ListPromotions", - "file": "merchantapi_v1beta_generated_promotions_service_list_promotions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_PromotionsService_ListPromotions_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_promotions_service_list_promotions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_promotions_v1beta.PromotionsServiceClient", - "shortName": "PromotionsServiceClient" - }, - "fullName": "google.shopping.merchant_promotions_v1beta.PromotionsServiceClient.list_promotions", - "method": { - "fullName": "google.shopping.merchant.promotions.v1beta.PromotionsService.ListPromotions", - "service": { - "fullName": "google.shopping.merchant.promotions.v1beta.PromotionsService", - "shortName": "PromotionsService" - }, - "shortName": "ListPromotions" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_promotions_v1beta.types.ListPromotionsRequest" - }, - { - "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_promotions_v1beta.services.promotions_service.pagers.ListPromotionsPager", - "shortName": "list_promotions" - }, - "description": "Sample for ListPromotions", - "file": "merchantapi_v1beta_generated_promotions_service_list_promotions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_PromotionsService_ListPromotions_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_promotions_service_list_promotions_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/scripts/fixup_merchant_promotions_v1beta_keywords.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/scripts/fixup_merchant_promotions_v1beta_keywords.py deleted file mode 100644 index 398615e0afb5..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/scripts/fixup_merchant_promotions_v1beta_keywords.py +++ /dev/null @@ -1,178 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_promotionsCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'get_promotion': ('name', ), - 'insert_promotion': ('parent', 'promotion', 'data_source', ), - 'list_promotions': ('parent', 'page_size', 'page_token', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=merchant_promotionsCallTransformer(), -): - """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_promotions 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-promotions/v1beta/setup.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/setup.py deleted file mode 100644 index a4ef40e7ce4a..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/setup.py +++ /dev/null @@ -1,99 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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-promotions' - - -description = "Google Shopping Merchant Promotions API client library" - -version = None - -with open(os.path.join(package_root, 'google/shopping/merchant_promotions/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.0dev,!=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.0dev,!=2.24.0,!=2.25.0", - "proto-plus >= 1.22.3, <2.0.0dev", - "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'", - "protobuf>=3.20.2,<6.0.0dev,!=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.0dev", -] -extras = { -} -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-promotions" - -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-promotions/v1beta/testing/constraints-3.10.txt b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/testing/constraints-3.10.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/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-promotions/v1beta/testing/constraints-3.11.txt b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/testing/constraints-3.11.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/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-promotions/v1beta/testing/constraints-3.12.txt b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/testing/constraints-3.12.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/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-promotions/v1beta/testing/constraints-3.13.txt b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/testing/constraints-3.13.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/testing/constraints-3.13.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-promotions/v1beta/testing/constraints-3.7.txt b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/testing/constraints-3.7.txt deleted file mode 100644 index 130a0c0f80ab..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/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.0dev", -# 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-promotions/v1beta/testing/constraints-3.8.txt b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/testing/constraints-3.8.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/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-promotions/v1beta/testing/constraints-3.9.txt b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/testing/constraints-3.9.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/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-promotions/v1beta/tests/__init__.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-promotions/v1beta/tests/unit/__init__.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-promotions/v1beta/tests/unit/gapic/__init__.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-promotions/v1beta/tests/unit/gapic/merchant_promotions_v1beta/__init__.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/tests/unit/gapic/merchant_promotions_v1beta/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/tests/unit/gapic/merchant_promotions_v1beta/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-promotions/v1beta/tests/unit/gapic/merchant_promotions_v1beta/test_promotions_service.py b/owl-bot-staging/google-shopping-merchant-promotions/v1beta/tests/unit/gapic/merchant_promotions_v1beta/test_promotions_service.py deleted file mode 100644 index c6dbc6da0ec9..000000000000 --- a/owl-bot-staging/google-shopping-merchant-promotions/v1beta/tests/unit/gapic/merchant_promotions_v1beta/test_promotions_service.py +++ /dev/null @@ -1,3614 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable, AsyncIterable -from google.protobuf import json_format -import json -import math -import pytest -from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -try: - from google.auth.aio import credentials as ga_credentials_async - HAS_GOOGLE_AUTH_AIO = True -except ImportError: # pragma: NO COVER - HAS_GOOGLE_AUTH_AIO = False - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.oauth2 import service_account -from google.protobuf import timestamp_pb2 # type: ignore -from google.shopping.merchant_promotions_v1beta.services.promotions_service import PromotionsServiceAsyncClient -from google.shopping.merchant_promotions_v1beta.services.promotions_service import PromotionsServiceClient -from google.shopping.merchant_promotions_v1beta.services.promotions_service import pagers -from google.shopping.merchant_promotions_v1beta.services.promotions_service import transports -from google.shopping.merchant_promotions_v1beta.types import promotions -from google.shopping.merchant_promotions_v1beta.types import promotions_common -from google.shopping.type.types import types -from google.type import interval_pb2 # type: ignore -import google.auth - - -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 PromotionsServiceClient._get_default_mtls_endpoint(None) is None - assert PromotionsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert PromotionsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert PromotionsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert PromotionsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert PromotionsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert PromotionsServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert PromotionsServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert PromotionsServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - PromotionsServiceClient._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 PromotionsServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert PromotionsServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert PromotionsServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - PromotionsServiceClient._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 PromotionsServiceClient._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 PromotionsServiceClient._get_client_cert_source(None, False) is None - assert PromotionsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert PromotionsServiceClient._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 PromotionsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert PromotionsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(PromotionsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PromotionsServiceClient)) -@mock.patch.object(PromotionsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PromotionsServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = PromotionsServiceClient._DEFAULT_UNIVERSE - default_endpoint = PromotionsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = PromotionsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert PromotionsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert PromotionsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == PromotionsServiceClient.DEFAULT_MTLS_ENDPOINT - assert PromotionsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert PromotionsServiceClient._get_api_endpoint(None, None, default_universe, "always") == PromotionsServiceClient.DEFAULT_MTLS_ENDPOINT - assert PromotionsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == PromotionsServiceClient.DEFAULT_MTLS_ENDPOINT - assert PromotionsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert PromotionsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - PromotionsServiceClient._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 PromotionsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert PromotionsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert PromotionsServiceClient._get_universe_domain(None, None) == PromotionsServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - PromotionsServiceClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - - -@pytest.mark.parametrize("client_class,transport_name", [ - (PromotionsServiceClient, "grpc"), - (PromotionsServiceAsyncClient, "grpc_asyncio"), - (PromotionsServiceClient, "rest"), -]) -def test_promotions_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.PromotionsServiceGrpcTransport, "grpc"), - (transports.PromotionsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.PromotionsServiceRestTransport, "rest"), -]) -def test_promotions_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", [ - (PromotionsServiceClient, "grpc"), - (PromotionsServiceAsyncClient, "grpc_asyncio"), - (PromotionsServiceClient, "rest"), -]) -def test_promotions_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_promotions_service_client_get_transport_class(): - transport = PromotionsServiceClient.get_transport_class() - available_transports = [ - transports.PromotionsServiceGrpcTransport, - transports.PromotionsServiceRestTransport, - ] - assert transport in available_transports - - transport = PromotionsServiceClient.get_transport_class("grpc") - assert transport == transports.PromotionsServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (PromotionsServiceClient, transports.PromotionsServiceGrpcTransport, "grpc"), - (PromotionsServiceAsyncClient, transports.PromotionsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (PromotionsServiceClient, transports.PromotionsServiceRestTransport, "rest"), -]) -@mock.patch.object(PromotionsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PromotionsServiceClient)) -@mock.patch.object(PromotionsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PromotionsServiceAsyncClient)) -def test_promotions_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(PromotionsServiceClient, '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(PromotionsServiceClient, '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", [ - (PromotionsServiceClient, transports.PromotionsServiceGrpcTransport, "grpc", "true"), - (PromotionsServiceAsyncClient, transports.PromotionsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (PromotionsServiceClient, transports.PromotionsServiceGrpcTransport, "grpc", "false"), - (PromotionsServiceAsyncClient, transports.PromotionsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (PromotionsServiceClient, transports.PromotionsServiceRestTransport, "rest", "true"), - (PromotionsServiceClient, transports.PromotionsServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(PromotionsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PromotionsServiceClient)) -@mock.patch.object(PromotionsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PromotionsServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_promotions_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", [ - PromotionsServiceClient, PromotionsServiceAsyncClient -]) -@mock.patch.object(PromotionsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PromotionsServiceClient)) -@mock.patch.object(PromotionsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PromotionsServiceAsyncClient)) -def test_promotions_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", [ - PromotionsServiceClient, PromotionsServiceAsyncClient -]) -@mock.patch.object(PromotionsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PromotionsServiceClient)) -@mock.patch.object(PromotionsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PromotionsServiceAsyncClient)) -def test_promotions_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = PromotionsServiceClient._DEFAULT_UNIVERSE - default_endpoint = PromotionsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = PromotionsServiceClient._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", [ - (PromotionsServiceClient, transports.PromotionsServiceGrpcTransport, "grpc"), - (PromotionsServiceAsyncClient, transports.PromotionsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (PromotionsServiceClient, transports.PromotionsServiceRestTransport, "rest"), -]) -def test_promotions_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", [ - (PromotionsServiceClient, transports.PromotionsServiceGrpcTransport, "grpc", grpc_helpers), - (PromotionsServiceAsyncClient, transports.PromotionsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (PromotionsServiceClient, transports.PromotionsServiceRestTransport, "rest", None), -]) -def test_promotions_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_promotions_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_promotions_v1beta.services.promotions_service.transports.PromotionsServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = PromotionsServiceClient( - 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", [ - (PromotionsServiceClient, transports.PromotionsServiceGrpcTransport, "grpc", grpc_helpers), - (PromotionsServiceAsyncClient, transports.PromotionsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_promotions_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", [ - promotions.InsertPromotionRequest, - dict, -]) -def test_insert_promotion(request_type, transport: str = 'grpc'): - client = PromotionsServiceClient( - 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_promotion), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = promotions.Promotion( - name='name_value', - promotion_id='promotion_id_value', - content_language='content_language_value', - target_country='target_country_value', - redemption_channel=[promotions_common.RedemptionChannel.IN_STORE], - data_source='data_source_value', - version_number=1518, - ) - response = client.insert_promotion(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = promotions.InsertPromotionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, promotions.Promotion) - assert response.name == 'name_value' - assert response.promotion_id == 'promotion_id_value' - assert response.content_language == 'content_language_value' - assert response.target_country == 'target_country_value' - assert response.redemption_channel == [promotions_common.RedemptionChannel.IN_STORE] - assert response.data_source == 'data_source_value' - assert response.version_number == 1518 - - -def test_insert_promotion_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 = PromotionsServiceClient( - 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 = promotions.InsertPromotionRequest( - parent='parent_value', - data_source='data_source_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.insert_promotion), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.insert_promotion(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == promotions.InsertPromotionRequest( - parent='parent_value', - data_source='data_source_value', - ) - -def test_insert_promotion_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = PromotionsServiceClient( - 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_promotion in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_promotion] = mock_rpc - request = {} - client.insert_promotion(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.insert_promotion(request) - - # Establish that a new wrapper 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_promotion_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = PromotionsServiceAsyncClient( - 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_promotion in client._client._transport._wrapped_methods - - # 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_promotion] = mock_rpc - - request = {} - await client.insert_promotion(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.insert_promotion(request) - - # Establish that a new wrapper 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_promotion_async(transport: str = 'grpc_asyncio', request_type=promotions.InsertPromotionRequest): - client = PromotionsServiceAsyncClient( - 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_promotion), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(promotions.Promotion( - name='name_value', - promotion_id='promotion_id_value', - content_language='content_language_value', - target_country='target_country_value', - redemption_channel=[promotions_common.RedemptionChannel.IN_STORE], - data_source='data_source_value', - version_number=1518, - )) - response = await client.insert_promotion(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = promotions.InsertPromotionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, promotions.Promotion) - assert response.name == 'name_value' - assert response.promotion_id == 'promotion_id_value' - assert response.content_language == 'content_language_value' - assert response.target_country == 'target_country_value' - assert response.redemption_channel == [promotions_common.RedemptionChannel.IN_STORE] - assert response.data_source == 'data_source_value' - assert response.version_number == 1518 - - -@pytest.mark.asyncio -async def test_insert_promotion_async_from_dict(): - await test_insert_promotion_async(request_type=dict) - -def test_insert_promotion_field_headers(): - client = PromotionsServiceClient( - 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 = promotions.InsertPromotionRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.insert_promotion), - '__call__') as call: - call.return_value = promotions.Promotion() - client.insert_promotion(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_promotion_field_headers_async(): - client = PromotionsServiceAsyncClient( - 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 = promotions.InsertPromotionRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.insert_promotion), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(promotions.Promotion()) - await client.insert_promotion(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - promotions.GetPromotionRequest, - dict, -]) -def test_get_promotion(request_type, transport: str = 'grpc'): - client = PromotionsServiceClient( - 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_promotion), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = promotions.Promotion( - name='name_value', - promotion_id='promotion_id_value', - content_language='content_language_value', - target_country='target_country_value', - redemption_channel=[promotions_common.RedemptionChannel.IN_STORE], - data_source='data_source_value', - version_number=1518, - ) - response = client.get_promotion(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = promotions.GetPromotionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, promotions.Promotion) - assert response.name == 'name_value' - assert response.promotion_id == 'promotion_id_value' - assert response.content_language == 'content_language_value' - assert response.target_country == 'target_country_value' - assert response.redemption_channel == [promotions_common.RedemptionChannel.IN_STORE] - assert response.data_source == 'data_source_value' - assert response.version_number == 1518 - - -def test_get_promotion_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 = PromotionsServiceClient( - 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 = promotions.GetPromotionRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_promotion), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_promotion(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == promotions.GetPromotionRequest( - name='name_value', - ) - -def test_get_promotion_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = PromotionsServiceClient( - 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_promotion in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_promotion] = mock_rpc - request = {} - client.get_promotion(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_promotion(request) - - # Establish that a new wrapper 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_promotion_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = PromotionsServiceAsyncClient( - 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_promotion in client._client._transport._wrapped_methods - - # 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_promotion] = mock_rpc - - request = {} - await client.get_promotion(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_promotion(request) - - # Establish that a new wrapper 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_promotion_async(transport: str = 'grpc_asyncio', request_type=promotions.GetPromotionRequest): - client = PromotionsServiceAsyncClient( - 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_promotion), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(promotions.Promotion( - name='name_value', - promotion_id='promotion_id_value', - content_language='content_language_value', - target_country='target_country_value', - redemption_channel=[promotions_common.RedemptionChannel.IN_STORE], - data_source='data_source_value', - version_number=1518, - )) - response = await client.get_promotion(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = promotions.GetPromotionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, promotions.Promotion) - assert response.name == 'name_value' - assert response.promotion_id == 'promotion_id_value' - assert response.content_language == 'content_language_value' - assert response.target_country == 'target_country_value' - assert response.redemption_channel == [promotions_common.RedemptionChannel.IN_STORE] - assert response.data_source == 'data_source_value' - assert response.version_number == 1518 - - -@pytest.mark.asyncio -async def test_get_promotion_async_from_dict(): - await test_get_promotion_async(request_type=dict) - -def test_get_promotion_field_headers(): - client = PromotionsServiceClient( - 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 = promotions.GetPromotionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_promotion), - '__call__') as call: - call.return_value = promotions.Promotion() - client.get_promotion(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_promotion_field_headers_async(): - client = PromotionsServiceAsyncClient( - 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 = promotions.GetPromotionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_promotion), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(promotions.Promotion()) - await client.get_promotion(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_promotion_flattened(): - client = PromotionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_promotion), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = promotions.Promotion() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_promotion( - 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_promotion_flattened_error(): - client = PromotionsServiceClient( - 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_promotion( - promotions.GetPromotionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_promotion_flattened_async(): - client = PromotionsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_promotion), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = promotions.Promotion() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(promotions.Promotion()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_promotion( - 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_promotion_flattened_error_async(): - client = PromotionsServiceAsyncClient( - 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_promotion( - promotions.GetPromotionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - promotions.ListPromotionsRequest, - dict, -]) -def test_list_promotions(request_type, transport: str = 'grpc'): - client = PromotionsServiceClient( - 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_promotions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = promotions.ListPromotionsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_promotions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = promotions.ListPromotionsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListPromotionsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_promotions_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 = PromotionsServiceClient( - 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 = promotions.ListPromotionsRequest( - 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_promotions), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_promotions(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == promotions.ListPromotionsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_promotions_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = PromotionsServiceClient( - 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_promotions in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_promotions] = mock_rpc - request = {} - client.list_promotions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_promotions(request) - - # Establish that a new wrapper 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_promotions_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = PromotionsServiceAsyncClient( - 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_promotions in client._client._transport._wrapped_methods - - # 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_promotions] = mock_rpc - - request = {} - await client.list_promotions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_promotions(request) - - # Establish that a new wrapper 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_promotions_async(transport: str = 'grpc_asyncio', request_type=promotions.ListPromotionsRequest): - client = PromotionsServiceAsyncClient( - 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_promotions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(promotions.ListPromotionsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_promotions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = promotions.ListPromotionsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListPromotionsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_promotions_async_from_dict(): - await test_list_promotions_async(request_type=dict) - -def test_list_promotions_field_headers(): - client = PromotionsServiceClient( - 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 = promotions.ListPromotionsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_promotions), - '__call__') as call: - call.return_value = promotions.ListPromotionsResponse() - client.list_promotions(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_promotions_field_headers_async(): - client = PromotionsServiceAsyncClient( - 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 = promotions.ListPromotionsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_promotions), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(promotions.ListPromotionsResponse()) - await client.list_promotions(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_promotions_flattened(): - client = PromotionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_promotions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = promotions.ListPromotionsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_promotions( - 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_promotions_flattened_error(): - client = PromotionsServiceClient( - 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_promotions( - promotions.ListPromotionsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_promotions_flattened_async(): - client = PromotionsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_promotions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = promotions.ListPromotionsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(promotions.ListPromotionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_promotions( - 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_promotions_flattened_error_async(): - client = PromotionsServiceAsyncClient( - 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_promotions( - promotions.ListPromotionsRequest(), - parent='parent_value', - ) - - -def test_list_promotions_pager(transport_name: str = "grpc"): - client = PromotionsServiceClient( - 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_promotions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - promotions.ListPromotionsResponse( - promotions=[ - promotions.Promotion(), - promotions.Promotion(), - promotions.Promotion(), - ], - next_page_token='abc', - ), - promotions.ListPromotionsResponse( - promotions=[], - next_page_token='def', - ), - promotions.ListPromotionsResponse( - promotions=[ - promotions.Promotion(), - ], - next_page_token='ghi', - ), - promotions.ListPromotionsResponse( - promotions=[ - promotions.Promotion(), - promotions.Promotion(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_promotions(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, promotions.Promotion) - for i in results) -def test_list_promotions_pages(transport_name: str = "grpc"): - client = PromotionsServiceClient( - 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_promotions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - promotions.ListPromotionsResponse( - promotions=[ - promotions.Promotion(), - promotions.Promotion(), - promotions.Promotion(), - ], - next_page_token='abc', - ), - promotions.ListPromotionsResponse( - promotions=[], - next_page_token='def', - ), - promotions.ListPromotionsResponse( - promotions=[ - promotions.Promotion(), - ], - next_page_token='ghi', - ), - promotions.ListPromotionsResponse( - promotions=[ - promotions.Promotion(), - promotions.Promotion(), - ], - ), - RuntimeError, - ) - pages = list(client.list_promotions(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_promotions_async_pager(): - client = PromotionsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_promotions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - promotions.ListPromotionsResponse( - promotions=[ - promotions.Promotion(), - promotions.Promotion(), - promotions.Promotion(), - ], - next_page_token='abc', - ), - promotions.ListPromotionsResponse( - promotions=[], - next_page_token='def', - ), - promotions.ListPromotionsResponse( - promotions=[ - promotions.Promotion(), - ], - next_page_token='ghi', - ), - promotions.ListPromotionsResponse( - promotions=[ - promotions.Promotion(), - promotions.Promotion(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_promotions(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, promotions.Promotion) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_promotions_async_pages(): - client = PromotionsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_promotions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - promotions.ListPromotionsResponse( - promotions=[ - promotions.Promotion(), - promotions.Promotion(), - promotions.Promotion(), - ], - next_page_token='abc', - ), - promotions.ListPromotionsResponse( - promotions=[], - next_page_token='def', - ), - promotions.ListPromotionsResponse( - promotions=[ - promotions.Promotion(), - ], - next_page_token='ghi', - ), - promotions.ListPromotionsResponse( - promotions=[ - promotions.Promotion(), - promotions.Promotion(), - ], - ), - 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_promotions(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_insert_promotion_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 = PromotionsServiceClient( - 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_promotion in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_promotion] = mock_rpc - - request = {} - client.insert_promotion(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.insert_promotion(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_promotion_rest_required_fields(request_type=promotions.InsertPromotionRequest): - transport_class = transports.PromotionsServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["data_source"] = "" - request = 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_promotion._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["dataSource"] = 'data_source_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).insert_promotion._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 "dataSource" in jsonified_request - assert jsonified_request["dataSource"] == 'data_source_value' - - client = PromotionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = promotions.Promotion() - # 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 = promotions.Promotion.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_promotion(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_insert_promotion_rest_unset_required_fields(): - transport = transports.PromotionsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.insert_promotion._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "promotion", "dataSource", ))) - - -def test_get_promotion_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 = PromotionsServiceClient( - 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_promotion in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_promotion] = mock_rpc - - request = {} - client.get_promotion(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_promotion(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_promotion_rest_required_fields(request_type=promotions.GetPromotionRequest): - transport_class = transports.PromotionsServiceRestTransport - - 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_promotion._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_promotion._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 = PromotionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = promotions.Promotion() - # 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 = promotions.Promotion.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_promotion(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_promotion_rest_unset_required_fields(): - transport = transports.PromotionsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_promotion._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_promotion_rest_flattened(): - client = PromotionsServiceClient( - 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 = promotions.Promotion() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/promotions/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 = promotions.Promotion.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_promotion(**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/promotions/v1beta/{name=accounts/*/promotions/*}" % client.transport._host, args[1]) - - -def test_get_promotion_rest_flattened_error(transport: str = 'rest'): - client = PromotionsServiceClient( - 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_promotion( - promotions.GetPromotionRequest(), - name='name_value', - ) - - -def test_list_promotions_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 = PromotionsServiceClient( - 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_promotions in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_promotions] = mock_rpc - - request = {} - client.list_promotions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_promotions(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_promotions_rest_required_fields(request_type=promotions.ListPromotionsRequest): - transport_class = transports.PromotionsServiceRestTransport - - 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_promotions._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_promotions._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 = PromotionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = promotions.ListPromotionsResponse() - # 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 = promotions.ListPromotionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_promotions(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_promotions_rest_unset_required_fields(): - transport = transports.PromotionsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_promotions._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_promotions_rest_flattened(): - client = PromotionsServiceClient( - 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 = promotions.ListPromotionsResponse() - - # 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 = promotions.ListPromotionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_promotions(**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/promotions/v1beta/{parent=accounts/*}/promotions" % client.transport._host, args[1]) - - -def test_list_promotions_rest_flattened_error(transport: str = 'rest'): - client = PromotionsServiceClient( - 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_promotions( - promotions.ListPromotionsRequest(), - parent='parent_value', - ) - - -def test_list_promotions_rest_pager(transport: str = 'rest'): - client = PromotionsServiceClient( - 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 = ( - promotions.ListPromotionsResponse( - promotions=[ - promotions.Promotion(), - promotions.Promotion(), - promotions.Promotion(), - ], - next_page_token='abc', - ), - promotions.ListPromotionsResponse( - promotions=[], - next_page_token='def', - ), - promotions.ListPromotionsResponse( - promotions=[ - promotions.Promotion(), - ], - next_page_token='ghi', - ), - promotions.ListPromotionsResponse( - promotions=[ - promotions.Promotion(), - promotions.Promotion(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(promotions.ListPromotionsResponse.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_promotions(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, promotions.Promotion) - for i in results) - - pages = list(client.list_promotions(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.PromotionsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PromotionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.PromotionsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PromotionsServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.PromotionsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = PromotionsServiceClient( - 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 = PromotionsServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.PromotionsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PromotionsServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.PromotionsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = PromotionsServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.PromotionsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.PromotionsServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.PromotionsServiceGrpcTransport, - transports.PromotionsServiceGrpcAsyncIOTransport, - transports.PromotionsServiceRestTransport, -]) -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 = PromotionsServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = PromotionsServiceClient( - 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_insert_promotion_empty_call_grpc(): - client = PromotionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.insert_promotion), - '__call__') as call: - call.return_value = promotions.Promotion() - client.insert_promotion(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = promotions.InsertPromotionRequest() - - assert args[0] == request_msg - - -# This 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_promotion_empty_call_grpc(): - client = PromotionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_promotion), - '__call__') as call: - call.return_value = promotions.Promotion() - client.get_promotion(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = promotions.GetPromotionRequest() - - assert args[0] == request_msg - - -# This 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_promotions_empty_call_grpc(): - client = PromotionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_promotions), - '__call__') as call: - call.return_value = promotions.ListPromotionsResponse() - client.list_promotions(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = promotions.ListPromotionsRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = PromotionsServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = PromotionsServiceAsyncClient( - 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_insert_promotion_empty_call_grpc_asyncio(): - client = PromotionsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.insert_promotion), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(promotions.Promotion( - name='name_value', - promotion_id='promotion_id_value', - content_language='content_language_value', - target_country='target_country_value', - redemption_channel=[promotions_common.RedemptionChannel.IN_STORE], - data_source='data_source_value', - version_number=1518, - )) - await client.insert_promotion(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = promotions.InsertPromotionRequest() - - assert args[0] == request_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_promotion_empty_call_grpc_asyncio(): - client = PromotionsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_promotion), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(promotions.Promotion( - name='name_value', - promotion_id='promotion_id_value', - content_language='content_language_value', - target_country='target_country_value', - redemption_channel=[promotions_common.RedemptionChannel.IN_STORE], - data_source='data_source_value', - version_number=1518, - )) - await client.get_promotion(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = promotions.GetPromotionRequest() - - assert args[0] == request_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_promotions_empty_call_grpc_asyncio(): - client = PromotionsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_promotions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(promotions.ListPromotionsResponse( - next_page_token='next_page_token_value', - )) - await client.list_promotions(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = promotions.ListPromotionsRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = PromotionsServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_insert_promotion_rest_bad_request(request_type=promotions.InsertPromotionRequest): - client = PromotionsServiceClient( - 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_promotion(request) - - -@pytest.mark.parametrize("request_type", [ - promotions.InsertPromotionRequest, - dict, -]) -def test_insert_promotion_rest_call_success(request_type): - client = PromotionsServiceClient( - 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 = promotions.Promotion( - name='name_value', - promotion_id='promotion_id_value', - content_language='content_language_value', - target_country='target_country_value', - redemption_channel=[promotions_common.RedemptionChannel.IN_STORE], - data_source='data_source_value', - version_number=1518, - ) - - # 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 = promotions.Promotion.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_promotion(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, promotions.Promotion) - assert response.name == 'name_value' - assert response.promotion_id == 'promotion_id_value' - assert response.content_language == 'content_language_value' - assert response.target_country == 'target_country_value' - assert response.redemption_channel == [promotions_common.RedemptionChannel.IN_STORE] - assert response.data_source == 'data_source_value' - assert response.version_number == 1518 - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_insert_promotion_rest_interceptors(null_interceptor): - transport = transports.PromotionsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.PromotionsServiceRestInterceptor(), - ) - client = PromotionsServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.PromotionsServiceRestInterceptor, "post_insert_promotion") as post, \ - mock.patch.object(transports.PromotionsServiceRestInterceptor, "pre_insert_promotion") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = promotions.InsertPromotionRequest.pb(promotions.InsertPromotionRequest()) - 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 = promotions.Promotion.to_json(promotions.Promotion()) - req.return_value.content = return_value - - request = promotions.InsertPromotionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = promotions.Promotion() - - client.insert_promotion(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_promotion_rest_bad_request(request_type=promotions.GetPromotionRequest): - client = PromotionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/promotions/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_promotion(request) - - -@pytest.mark.parametrize("request_type", [ - promotions.GetPromotionRequest, - dict, -]) -def test_get_promotion_rest_call_success(request_type): - client = PromotionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/promotions/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 = promotions.Promotion( - name='name_value', - promotion_id='promotion_id_value', - content_language='content_language_value', - target_country='target_country_value', - redemption_channel=[promotions_common.RedemptionChannel.IN_STORE], - data_source='data_source_value', - version_number=1518, - ) - - # 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 = promotions.Promotion.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_promotion(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, promotions.Promotion) - assert response.name == 'name_value' - assert response.promotion_id == 'promotion_id_value' - assert response.content_language == 'content_language_value' - assert response.target_country == 'target_country_value' - assert response.redemption_channel == [promotions_common.RedemptionChannel.IN_STORE] - assert response.data_source == 'data_source_value' - assert response.version_number == 1518 - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_promotion_rest_interceptors(null_interceptor): - transport = transports.PromotionsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.PromotionsServiceRestInterceptor(), - ) - client = PromotionsServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.PromotionsServiceRestInterceptor, "post_get_promotion") as post, \ - mock.patch.object(transports.PromotionsServiceRestInterceptor, "pre_get_promotion") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = promotions.GetPromotionRequest.pb(promotions.GetPromotionRequest()) - 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 = promotions.Promotion.to_json(promotions.Promotion()) - req.return_value.content = return_value - - request = promotions.GetPromotionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = promotions.Promotion() - - client.get_promotion(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_promotions_rest_bad_request(request_type=promotions.ListPromotionsRequest): - client = PromotionsServiceClient( - 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_promotions(request) - - -@pytest.mark.parametrize("request_type", [ - promotions.ListPromotionsRequest, - dict, -]) -def test_list_promotions_rest_call_success(request_type): - client = PromotionsServiceClient( - 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 = promotions.ListPromotionsResponse( - 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 = promotions.ListPromotionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_promotions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListPromotionsPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_promotions_rest_interceptors(null_interceptor): - transport = transports.PromotionsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.PromotionsServiceRestInterceptor(), - ) - client = PromotionsServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.PromotionsServiceRestInterceptor, "post_list_promotions") as post, \ - mock.patch.object(transports.PromotionsServiceRestInterceptor, "pre_list_promotions") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = promotions.ListPromotionsRequest.pb(promotions.ListPromotionsRequest()) - 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 = promotions.ListPromotionsResponse.to_json(promotions.ListPromotionsResponse()) - req.return_value.content = return_value - - request = promotions.ListPromotionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = promotions.ListPromotionsResponse() - - client.list_promotions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - -def test_initialize_client_w_rest(): - client = PromotionsServiceClient( - 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_insert_promotion_empty_call_rest(): - client = PromotionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.insert_promotion), - '__call__') as call: - client.insert_promotion(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = promotions.InsertPromotionRequest() - - assert args[0] == request_msg - - -# This 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_promotion_empty_call_rest(): - client = PromotionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_promotion), - '__call__') as call: - client.get_promotion(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = promotions.GetPromotionRequest() - - assert args[0] == request_msg - - -# This 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_promotions_empty_call_rest(): - client = PromotionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_promotions), - '__call__') as call: - client.list_promotions(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = promotions.ListPromotionsRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = PromotionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.PromotionsServiceGrpcTransport, - ) - -def test_promotions_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.PromotionsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_promotions_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.shopping.merchant_promotions_v1beta.services.promotions_service.transports.PromotionsServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.PromotionsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'insert_promotion', - 'get_promotion', - 'list_promotions', - ) - 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_promotions_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_promotions_v1beta.services.promotions_service.transports.PromotionsServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PromotionsServiceTransport( - 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_promotions_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_promotions_v1beta.services.promotions_service.transports.PromotionsServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PromotionsServiceTransport() - adc.assert_called_once() - - -def test_promotions_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) - PromotionsServiceClient() - 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.PromotionsServiceGrpcTransport, - transports.PromotionsServiceGrpcAsyncIOTransport, - ], -) -def test_promotions_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.PromotionsServiceGrpcTransport, - transports.PromotionsServiceGrpcAsyncIOTransport, - transports.PromotionsServiceRestTransport, - ], -) -def test_promotions_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.PromotionsServiceGrpcTransport, grpc_helpers), - (transports.PromotionsServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_promotions_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.PromotionsServiceGrpcTransport, transports.PromotionsServiceGrpcAsyncIOTransport]) -def test_promotions_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_promotions_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.PromotionsServiceRestTransport ( - 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_promotions_service_host_no_port(transport_name): - client = PromotionsServiceClient( - 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_promotions_service_host_with_port(transport_name): - client = PromotionsServiceClient( - 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_promotions_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = PromotionsServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = PromotionsServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.insert_promotion._session - session2 = client2.transport.insert_promotion._session - assert session1 != session2 - session1 = client1.transport.get_promotion._session - session2 = client2.transport.get_promotion._session - assert session1 != session2 - session1 = client1.transport.list_promotions._session - session2 = client2.transport.list_promotions._session - assert session1 != session2 -def test_promotions_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.PromotionsServiceGrpcTransport( - 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_promotions_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.PromotionsServiceGrpcAsyncIOTransport( - 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.PromotionsServiceGrpcTransport, transports.PromotionsServiceGrpcAsyncIOTransport]) -def test_promotions_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.PromotionsServiceGrpcTransport, transports.PromotionsServiceGrpcAsyncIOTransport]) -def test_promotions_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_promotion_path(): - account = "squid" - promotion = "clam" - expected = "accounts/{account}/promotions/{promotion}".format(account=account, promotion=promotion, ) - actual = PromotionsServiceClient.promotion_path(account, promotion) - assert expected == actual - - -def test_parse_promotion_path(): - expected = { - "account": "whelk", - "promotion": "octopus", - } - path = PromotionsServiceClient.promotion_path(**expected) - - # Check that the path construction is reversible. - actual = PromotionsServiceClient.parse_promotion_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = PromotionsServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = PromotionsServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = PromotionsServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = PromotionsServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = PromotionsServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = PromotionsServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = PromotionsServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = PromotionsServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = PromotionsServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = PromotionsServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = PromotionsServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = PromotionsServiceClient.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 = PromotionsServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = PromotionsServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = PromotionsServiceClient.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.PromotionsServiceTransport, '_prep_wrapped_messages') as prep: - client = PromotionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.PromotionsServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = PromotionsServiceClient.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 = PromotionsServiceClient( - 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 = PromotionsServiceAsyncClient( - 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 = PromotionsServiceClient( - 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 = PromotionsServiceClient( - 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", [ - (PromotionsServiceClient, transports.PromotionsServiceGrpcTransport), - (PromotionsServiceAsyncClient, transports.PromotionsServiceGrpcAsyncIOTransport), -]) -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-quota/v1beta/.coveragerc b/owl-bot-staging/google-shopping-merchant-quota/v1beta/.coveragerc deleted file mode 100644 index 8114816bc3c5..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/shopping/merchant_quota/__init__.py - google/shopping/merchant_quota/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-quota/v1beta/.flake8 b/owl-bot-staging/google-shopping-merchant-quota/v1beta/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/MANIFEST.in b/owl-bot-staging/google-shopping-merchant-quota/v1beta/MANIFEST.in deleted file mode 100644 index e1f38916c325..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/shopping/merchant_quota *.py -recursive-include google/shopping/merchant_quota_v1beta *.py diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/README.rst b/owl-bot-staging/google-shopping-merchant-quota/v1beta/README.rst deleted file mode 100644 index ffa65e82132a..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Shopping Merchant Quota 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 Quota 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 diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/_static/custom.css b/owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/_static/custom.css +++ /dev/null @@ -1,3 +0,0 @@ -dl.field-list > dt { - min-width: 100px -} diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/conf.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/conf.py deleted file mode 100644 index a76827c00d4d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-quota 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("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# 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.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -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-quota" -copyright = u"2023, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# 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 = 'en' - -# 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"] - -# 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 Python", - "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-quota-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-quota.tex", - u"google-shopping-merchant-quota 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-quota", - u"Google Shopping Merchant Quota 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-quota", - u"google-shopping-merchant-quota Documentation", - author, - "google-shopping-merchant-quota", - "GAPIC library for Google Shopping Merchant Quota API", - "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": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", 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-quota/v1beta/docs/index.rst b/owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/index.rst deleted file mode 100644 index c688ba3396e1..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - merchant_quota_v1beta/services_ - merchant_quota_v1beta/types_ diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/merchant_quota_v1beta/quota_service.rst b/owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/merchant_quota_v1beta/quota_service.rst deleted file mode 100644 index 1743e25da211..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/merchant_quota_v1beta/quota_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -QuotaService ------------------------------- - -.. automodule:: google.shopping.merchant_quota_v1beta.services.quota_service - :members: - :inherited-members: - -.. automodule:: google.shopping.merchant_quota_v1beta.services.quota_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/merchant_quota_v1beta/services_.rst b/owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/merchant_quota_v1beta/services_.rst deleted file mode 100644 index 0928f3a6f1ce..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/merchant_quota_v1beta/services_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Shopping Merchant Quota v1beta API -====================================================== -.. toctree:: - :maxdepth: 2 - - quota_service diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/merchant_quota_v1beta/types_.rst b/owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/merchant_quota_v1beta/types_.rst deleted file mode 100644 index 622859fdaffb..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/docs/merchant_quota_v1beta/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Shopping Merchant Quota v1beta API -=================================================== - -.. automodule:: google.shopping.merchant_quota_v1beta.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota/__init__.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota/__init__.py deleted file mode 100644 index c3a300a10746..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota/__init__.py +++ /dev/null @@ -1,35 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_quota import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.shopping.merchant_quota_v1beta.services.quota_service.client import QuotaServiceClient -from google.shopping.merchant_quota_v1beta.services.quota_service.async_client import QuotaServiceAsyncClient - -from google.shopping.merchant_quota_v1beta.types.quota import ListQuotaGroupsRequest -from google.shopping.merchant_quota_v1beta.types.quota import ListQuotaGroupsResponse -from google.shopping.merchant_quota_v1beta.types.quota import MethodDetails -from google.shopping.merchant_quota_v1beta.types.quota import QuotaGroup - -__all__ = ('QuotaServiceClient', - 'QuotaServiceAsyncClient', - 'ListQuotaGroupsRequest', - 'ListQuotaGroupsResponse', - 'MethodDetails', - 'QuotaGroup', -) diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota/gapic_version.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-quota/v1beta/google/shopping/merchant_quota/py.typed b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota/py.typed deleted file mode 100644 index c73143bc3edf..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-shopping-merchant-quota package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/__init__.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/__init__.py deleted file mode 100644 index d5c60977b344..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/__init__.py +++ /dev/null @@ -1,36 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_quota_v1beta import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.quota_service import QuotaServiceClient -from .services.quota_service import QuotaServiceAsyncClient - -from .types.quota import ListQuotaGroupsRequest -from .types.quota import ListQuotaGroupsResponse -from .types.quota import MethodDetails -from .types.quota import QuotaGroup - -__all__ = ( - 'QuotaServiceAsyncClient', -'ListQuotaGroupsRequest', -'ListQuotaGroupsResponse', -'MethodDetails', -'QuotaGroup', -'QuotaServiceClient', -) diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/gapic_metadata.json b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/gapic_metadata.json deleted file mode 100644 index 8278f93d2b60..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/gapic_metadata.json +++ /dev/null @@ -1,43 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.shopping.merchant_quota_v1beta", - "protoPackage": "google.shopping.merchant.quota.v1beta", - "schema": "1.0", - "services": { - "QuotaService": { - "clients": { - "grpc": { - "libraryClient": "QuotaServiceClient", - "rpcs": { - "ListQuotaGroups": { - "methods": [ - "list_quota_groups" - ] - } - } - }, - "grpc-async": { - "libraryClient": "QuotaServiceAsyncClient", - "rpcs": { - "ListQuotaGroups": { - "methods": [ - "list_quota_groups" - ] - } - } - }, - "rest": { - "libraryClient": "QuotaServiceClient", - "rpcs": { - "ListQuotaGroups": { - "methods": [ - "list_quota_groups" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/gapic_version.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-quota/v1beta/google/shopping/merchant_quota_v1beta/py.typed b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/py.typed deleted file mode 100644 index c73143bc3edf..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-shopping-merchant-quota package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/__init__.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/__init__.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/__init__.py deleted file mode 100644 index 512b8ee436f7..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 QuotaServiceClient -from .async_client import QuotaServiceAsyncClient - -__all__ = ( - 'QuotaServiceClient', - 'QuotaServiceAsyncClient', -) diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/async_client.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/async_client.py deleted file mode 100644 index 8931f91189d1..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/async_client.py +++ /dev/null @@ -1,384 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_quota_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 - - -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_quota_v1beta.services.quota_service import pagers -from google.shopping.merchant_quota_v1beta.types import quota -from .transports.base import QuotaServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import QuotaServiceGrpcAsyncIOTransport -from .client import QuotaServiceClient - -try: - from google.api_core import client_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 QuotaServiceAsyncClient: - """Service to get method call quota information per Merchant API - method. - """ - - _client: QuotaServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = QuotaServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = QuotaServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = QuotaServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = QuotaServiceClient._DEFAULT_UNIVERSE - - quota_group_path = staticmethod(QuotaServiceClient.quota_group_path) - parse_quota_group_path = staticmethod(QuotaServiceClient.parse_quota_group_path) - common_billing_account_path = staticmethod(QuotaServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(QuotaServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(QuotaServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(QuotaServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(QuotaServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(QuotaServiceClient.parse_common_organization_path) - common_project_path = staticmethod(QuotaServiceClient.common_project_path) - parse_common_project_path = staticmethod(QuotaServiceClient.parse_common_project_path) - common_location_path = staticmethod(QuotaServiceClient.common_location_path) - parse_common_location_path = staticmethod(QuotaServiceClient.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: - QuotaServiceAsyncClient: The constructed client. - """ - return QuotaServiceClient.from_service_account_info.__func__(QuotaServiceAsyncClient, 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: - QuotaServiceAsyncClient: The constructed client. - """ - return QuotaServiceClient.from_service_account_file.__func__(QuotaServiceAsyncClient, 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 QuotaServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> QuotaServiceTransport: - """Returns the transport used by the client instance. - - Returns: - QuotaServiceTransport: 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 = QuotaServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, QuotaServiceTransport, Callable[..., QuotaServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the quota 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,QuotaServiceTransport,Callable[..., QuotaServiceTransport]]]): - 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 QuotaServiceTransport 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 = QuotaServiceClient( - 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.quota_v1beta.QuotaServiceAsyncClient`.", - extra = { - "serviceName": "google.shopping.merchant.quota.v1beta.QuotaService", - "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.quota.v1beta.QuotaService", - "credentialsType": None, - } - ) - - async def list_quota_groups(self, - request: Optional[Union[quota.ListQuotaGroupsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListQuotaGroupsAsyncPager: - r"""Lists the daily call quota and usage per group for - 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_quota_v1beta - - async def sample_list_quota_groups(): - # Create a client - client = merchant_quota_v1beta.QuotaServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_quota_v1beta.ListQuotaGroupsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_quota_groups(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_quota_v1beta.types.ListQuotaGroupsRequest, dict]]): - The request object. Request message for the - ListQuotaGroups method. - parent (:class:`str`): - Required. The merchant account who - owns the collection of method quotas - 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_quota_v1beta.services.quota_service.pagers.ListQuotaGroupsAsyncPager: - Response message for the - ListMethodGroups 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, quota.ListQuotaGroupsRequest): - request = quota.ListQuotaGroupsRequest(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_quota_groups] - - # Certain 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.ListQuotaGroupsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self) -> "QuotaServiceAsyncClient": - 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__) - - -__all__ = ( - "QuotaServiceAsyncClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/client.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/client.py deleted file mode 100644 index 9510a56dd108..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/client.py +++ /dev/null @@ -1,719 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -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_quota_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 - -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_quota_v1beta.services.quota_service import pagers -from google.shopping.merchant_quota_v1beta.types import quota -from .transports.base import QuotaServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import QuotaServiceGrpcTransport -from .transports.grpc_asyncio import QuotaServiceGrpcAsyncIOTransport -from .transports.rest import QuotaServiceRestTransport - - -class QuotaServiceClientMeta(type): - """Metaclass for the QuotaService 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[QuotaServiceTransport]] - _transport_registry["grpc"] = QuotaServiceGrpcTransport - _transport_registry["grpc_asyncio"] = QuotaServiceGrpcAsyncIOTransport - _transport_registry["rest"] = QuotaServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[QuotaServiceTransport]: - """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 QuotaServiceClient(metaclass=QuotaServiceClientMeta): - """Service to get method call quota 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: - QuotaServiceClient: 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: - QuotaServiceClient: 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) -> QuotaServiceTransport: - """Returns the transport used by the client instance. - - Returns: - QuotaServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def quota_group_path(account: str,group: str,) -> str: - """Returns a fully-qualified quota_group string.""" - return "accounts/{account}/groups/{group}".format(account=account, group=group, ) - - @staticmethod - def parse_quota_group_path(path: str) -> Dict[str,str]: - """Parses a quota_group path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/groups/(?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 = QuotaServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = QuotaServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = QuotaServiceClient._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 = QuotaServiceClient._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 - - @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, QuotaServiceTransport, Callable[..., QuotaServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the quota 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,QuotaServiceTransport,Callable[..., QuotaServiceTransport]]]): - 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 QuotaServiceTransport 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 = QuotaServiceClient._read_environment_variables() - self._client_cert_source = QuotaServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = QuotaServiceClient._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, QuotaServiceTransport) - if transport_provided: - # transport is a QuotaServiceTransport 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(QuotaServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - QuotaServiceClient._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[QuotaServiceTransport], Callable[..., QuotaServiceTransport]] = ( - QuotaServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., QuotaServiceTransport], 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.quota_v1beta.QuotaServiceClient`.", - extra = { - "serviceName": "google.shopping.merchant.quota.v1beta.QuotaService", - "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.quota.v1beta.QuotaService", - "credentialsType": None, - } - ) - - def list_quota_groups(self, - request: Optional[Union[quota.ListQuotaGroupsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListQuotaGroupsPager: - r"""Lists the daily call quota and usage per group for - 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_quota_v1beta - - def sample_list_quota_groups(): - # Create a client - client = merchant_quota_v1beta.QuotaServiceClient() - - # Initialize request argument(s) - request = merchant_quota_v1beta.ListQuotaGroupsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_quota_groups(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.shopping.merchant_quota_v1beta.types.ListQuotaGroupsRequest, dict]): - The request object. Request message for the - ListQuotaGroups method. - parent (str): - Required. The merchant account who - owns the collection of method quotas - 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_quota_v1beta.services.quota_service.pagers.ListQuotaGroupsPager: - Response message for the - ListMethodGroups 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, quota.ListQuotaGroupsRequest): - request = quota.ListQuotaGroupsRequest(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_quota_groups] - - # Certain 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.ListQuotaGroupsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "QuotaServiceClient": - 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__) - - -__all__ = ( - "QuotaServiceClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/pagers.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/pagers.py deleted file mode 100644 index afdb52c6f999..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/pagers.py +++ /dev/null @@ -1,166 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_quota_v1beta.types import quota - - -class ListQuotaGroupsPager: - """A pager for iterating through ``list_quota_groups`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_quota_v1beta.types.ListQuotaGroupsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``quota_groups`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListQuotaGroups`` requests and continue to iterate - through the ``quota_groups`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_quota_v1beta.types.ListQuotaGroupsResponse` - 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[..., quota.ListQuotaGroupsResponse], - request: quota.ListQuotaGroupsRequest, - response: quota.ListQuotaGroupsResponse, - *, - 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_quota_v1beta.types.ListQuotaGroupsRequest): - The initial request object. - response (google.shopping.merchant_quota_v1beta.types.ListQuotaGroupsResponse): - 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 = quota.ListQuotaGroupsRequest(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[quota.ListQuotaGroupsResponse]: - 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[quota.QuotaGroup]: - for page in self.pages: - yield from page.quota_groups - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListQuotaGroupsAsyncPager: - """A pager for iterating through ``list_quota_groups`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_quota_v1beta.types.ListQuotaGroupsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``quota_groups`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListQuotaGroups`` requests and continue to iterate - through the ``quota_groups`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_quota_v1beta.types.ListQuotaGroupsResponse` - 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[quota.ListQuotaGroupsResponse]], - request: quota.ListQuotaGroupsRequest, - response: quota.ListQuotaGroupsResponse, - *, - 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_quota_v1beta.types.ListQuotaGroupsRequest): - The initial request object. - response (google.shopping.merchant_quota_v1beta.types.ListQuotaGroupsResponse): - 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 = quota.ListQuotaGroupsRequest(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[quota.ListQuotaGroupsResponse]: - 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[quota.QuotaGroup]: - async def async_generator(): - async for page in self.pages: - for response in page.quota_groups: - 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-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/README.rst deleted file mode 100644 index 06b6eb4da828..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`QuotaServiceTransport` is the ABC for all transports. -- public child `QuotaServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `QuotaServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseQuotaServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `QuotaServiceRestTransport` 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-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/__init__.py deleted file mode 100644 index 1dddb73e2611..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 QuotaServiceTransport -from .grpc import QuotaServiceGrpcTransport -from .grpc_asyncio import QuotaServiceGrpcAsyncIOTransport -from .rest import QuotaServiceRestTransport -from .rest import QuotaServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[QuotaServiceTransport]] -_transport_registry['grpc'] = QuotaServiceGrpcTransport -_transport_registry['grpc_asyncio'] = QuotaServiceGrpcAsyncIOTransport -_transport_registry['rest'] = QuotaServiceRestTransport - -__all__ = ( - 'QuotaServiceTransport', - 'QuotaServiceGrpcTransport', - 'QuotaServiceGrpcAsyncIOTransport', - 'QuotaServiceRestTransport', - 'QuotaServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/base.py deleted file mode 100644 index b4e3103cc44f..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/base.py +++ /dev/null @@ -1,154 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_quota_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 - -from google.shopping.merchant_quota_v1beta.types import quota - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class QuotaServiceTransport(abc.ABC): - """Abstract transport class for QuotaService.""" - - 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_quota_groups: gapic_v1.method.wrap_method( - self.list_quota_groups, - 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_quota_groups(self) -> Callable[ - [quota.ListQuotaGroupsRequest], - Union[ - quota.ListQuotaGroupsResponse, - Awaitable[quota.ListQuotaGroupsResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'QuotaServiceTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/grpc.py deleted file mode 100644 index 9230328ddc64..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/grpc.py +++ /dev/null @@ -1,349 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_quota_v1beta.types import quota -from .base import QuotaServiceTransport, 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.quota.v1beta.QuotaService", - "rpcName": 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.quota.v1beta.QuotaService", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class QuotaServiceGrpcTransport(QuotaServiceTransport): - """gRPC backend transport for QuotaService. - - Service to get method call quota 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 list_quota_groups(self) -> Callable[ - [quota.ListQuotaGroupsRequest], - quota.ListQuotaGroupsResponse]: - r"""Return a callable for the list quota groups method over gRPC. - - Lists the daily call quota and usage per group for - your Merchant Center account. - - Returns: - Callable[[~.ListQuotaGroupsRequest], - ~.ListQuotaGroupsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_quota_groups' not in self._stubs: - self._stubs['list_quota_groups'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.quota.v1beta.QuotaService/ListQuotaGroups', - request_serializer=quota.ListQuotaGroupsRequest.serialize, - response_deserializer=quota.ListQuotaGroupsResponse.deserialize, - ) - return self._stubs['list_quota_groups'] - - def close(self): - self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'QuotaServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/grpc_asyncio.py deleted file mode 100644 index 91389d2fd3ca..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,369 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_quota_v1beta.types import quota -from .base import QuotaServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import QuotaServiceGrpcTransport - -try: - from google.api_core import client_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.quota.v1beta.QuotaService", - "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.quota.v1beta.QuotaService", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class QuotaServiceGrpcAsyncIOTransport(QuotaServiceTransport): - """gRPC AsyncIO backend transport for QuotaService. - - Service to get method call quota 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 list_quota_groups(self) -> Callable[ - [quota.ListQuotaGroupsRequest], - Awaitable[quota.ListQuotaGroupsResponse]]: - r"""Return a callable for the list quota groups method over gRPC. - - Lists the daily call quota and usage per group for - your Merchant Center account. - - Returns: - Callable[[~.ListQuotaGroupsRequest], - Awaitable[~.ListQuotaGroupsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_quota_groups' not in self._stubs: - self._stubs['list_quota_groups'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.quota.v1beta.QuotaService/ListQuotaGroups', - request_serializer=quota.ListQuotaGroupsRequest.serialize, - response_deserializer=quota.ListQuotaGroupsResponse.deserialize, - ) - return self._stubs['list_quota_groups'] - - 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_quota_groups: self._wrap_method( - self.list_quota_groups, - 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__ = ( - 'QuotaServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/rest.py deleted file mode 100644 index e6157bea06ce..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/rest.py +++ /dev/null @@ -1,330 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -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_quota_v1beta.types import quota - - -from .rest_base import _BaseQuotaServiceRestTransport -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}", -) - - -class QuotaServiceRestInterceptor: - """Interceptor for QuotaService. - - 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 QuotaServiceRestTransport. - - .. code-block:: python - class MyCustomQuotaServiceInterceptor(QuotaServiceRestInterceptor): - def pre_list_quota_groups(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_quota_groups(self, response): - logging.log(f"Received response: {response}") - return response - - transport = QuotaServiceRestTransport(interceptor=MyCustomQuotaServiceInterceptor()) - client = QuotaServiceClient(transport=transport) - - - """ - def pre_list_quota_groups(self, request: quota.ListQuotaGroupsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[quota.ListQuotaGroupsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_quota_groups - - Override in a subclass to manipulate the request or metadata - before they are sent to the QuotaService server. - """ - return request, metadata - - def post_list_quota_groups(self, response: quota.ListQuotaGroupsResponse) -> quota.ListQuotaGroupsResponse: - """Post-rpc interceptor for list_quota_groups - - Override in a subclass to manipulate the response - after it is returned by the QuotaService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class QuotaServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: QuotaServiceRestInterceptor - - -class QuotaServiceRestTransport(_BaseQuotaServiceRestTransport): - """REST backend synchronous transport for QuotaService. - - Service to get method call quota 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[QuotaServiceRestInterceptor] = 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 QuotaServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _ListQuotaGroups(_BaseQuotaServiceRestTransport._BaseListQuotaGroups, QuotaServiceRestStub): - def __hash__(self): - return hash("QuotaServiceRestTransport.ListQuotaGroups") - - @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: quota.ListQuotaGroupsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> quota.ListQuotaGroupsResponse: - r"""Call the list quota groups method over HTTP. - - Args: - request (~.quota.ListQuotaGroupsRequest): - The request object. Request message for the - ListQuotaGroups method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.quota.ListQuotaGroupsResponse: - Response message for the - ListMethodGroups method. - - """ - - http_options = _BaseQuotaServiceRestTransport._BaseListQuotaGroups._get_http_options() - - request, metadata = self._interceptor.pre_list_quota_groups(request, metadata) - transcoded_request = _BaseQuotaServiceRestTransport._BaseListQuotaGroups._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseQuotaServiceRestTransport._BaseListQuotaGroups._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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.quota_v1beta.QuotaServiceClient.ListQuotaGroups", - extra = { - "serviceName": "google.shopping.merchant.quota.v1beta.QuotaService", - "rpcName": "ListQuotaGroups", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = QuotaServiceRestTransport._ListQuotaGroups._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 = quota.ListQuotaGroupsResponse() - pb_resp = quota.ListQuotaGroupsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_quota_groups(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = quota.ListQuotaGroupsResponse.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.quota_v1beta.QuotaServiceClient.list_quota_groups", - extra = { - "serviceName": "google.shopping.merchant.quota.v1beta.QuotaService", - "rpcName": "ListQuotaGroups", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def list_quota_groups(self) -> Callable[ - [quota.ListQuotaGroupsRequest], - quota.ListQuotaGroupsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListQuotaGroups(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'QuotaServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/rest_base.py deleted file mode 100644 index c7b406f9d383..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/services/quota_service/transports/rest_base.py +++ /dev/null @@ -1,128 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 QuotaServiceTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.shopping.merchant_quota_v1beta.types import quota - - -class _BaseQuotaServiceRestTransport(QuotaServiceTransport): - """Base REST backend transport for QuotaService. - - 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 _BaseListQuotaGroups: - 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': '/quota/v1beta/{parent=accounts/*}/quotas', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = quota.ListQuotaGroupsRequest.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(_BaseQuotaServiceRestTransport._BaseListQuotaGroups._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseQuotaServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/types/__init__.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/types/__init__.py deleted file mode 100644 index e4e09c52c9f5..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/types/__init__.py +++ /dev/null @@ -1,28 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .quota import ( - ListQuotaGroupsRequest, - ListQuotaGroupsResponse, - MethodDetails, - QuotaGroup, -) - -__all__ = ( - 'ListQuotaGroupsRequest', - 'ListQuotaGroupsResponse', - 'MethodDetails', - 'QuotaGroup', -) diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/types/quota.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/types/quota.py deleted file mode 100644 index c1a3a79456e3..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/google/shopping/merchant_quota_v1beta/types/quota.py +++ /dev/null @@ -1,184 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.quota.v1beta', - manifest={ - 'QuotaGroup', - 'MethodDetails', - 'ListQuotaGroupsRequest', - 'ListQuotaGroupsResponse', - }, -) - - -class QuotaGroup(proto.Message): - r"""The group information for methods in the Merchant API. The - quota is shared between all methods in the group. Even if none - of the methods within the group have usage the information for - the group is returned. - - Attributes: - name (str): - Identifier. The resource name of the quota - group. Format: accounts/{account}/quotas/{group} - Note: There is no guarantee on the format of - {group} - quota_usage (int): - Output only. The current quota usage, meaning - the number of calls already made on a given day - to the methods in the group. The daily quota - limits reset at at 12:00 PM midday UTC. - quota_limit (int): - Output only. The maximum number of calls - allowed per day for the group. - quota_minute_limit (int): - Output only. The maximum number of calls - allowed per minute for the group. - method_details (MutableSequence[google.shopping.merchant_quota_v1beta.types.MethodDetails]): - Output only. List of all methods group quota - applies to. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - quota_usage: int = proto.Field( - proto.INT64, - number=2, - ) - quota_limit: int = proto.Field( - proto.INT64, - number=3, - ) - quota_minute_limit: int = proto.Field( - proto.INT64, - number=5, - ) - method_details: MutableSequence['MethodDetails'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='MethodDetails', - ) - - -class MethodDetails(proto.Message): - r"""The method details per method in the Merchant API. - - Attributes: - method (str): - Output only. The name of the method for example - ``products.list``. - version (str): - Output only. The API version that the method - belongs to. - subapi (str): - Output only. The sub-API that the method - belongs to. - path (str): - Output only. The path for the method such as - ``products/v1/productInputs.insert`` - """ - - method: str = proto.Field( - proto.STRING, - number=1, - ) - version: str = proto.Field( - proto.STRING, - number=2, - ) - subapi: str = proto.Field( - proto.STRING, - number=3, - ) - path: str = proto.Field( - proto.STRING, - number=4, - ) - - -class ListQuotaGroupsRequest(proto.Message): - r"""Request message for the ListQuotaGroups method. - - Attributes: - parent (str): - Required. The merchant account who owns the - collection of method quotas Format: - accounts/{account} - page_size (int): - Optional. The maximum number of quotas to - return in the response, used for paging. - Defaults to 500; values above 1000 will be - coerced to 1000. - page_token (str): - Optional. Token (if provided) to retrieve the - subsequent page. All other parameters must match - the original 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 ListQuotaGroupsResponse(proto.Message): - r"""Response message for the ListMethodGroups method. - - Attributes: - quota_groups (MutableSequence[google.shopping.merchant_quota_v1beta.types.QuotaGroup]): - The methods, current quota usage and limits per each group. - The quota is shared between all methods in the group. The - groups are sorted in descending order based on - [quotaUsage][google.shopping.merchant.quota.v1main.QuotaGroup.quota_usage]. - 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 - - quota_groups: MutableSequence['QuotaGroup'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='QuotaGroup', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/mypy.ini b/owl-bot-staging/google-shopping-merchant-quota/v1beta/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/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-quota/v1beta/noxfile.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/noxfile.py deleted file mode 100644 index ab60f2f71caf..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/noxfile.py +++ /dev/null @@ -1,280 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", - "3.12", - "3.13", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = 'google-shopping-merchant-quota' - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.13" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "prerelease_deps", -] - -@nox.session(python=ALL_PYTHON) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def unit(session, protobuf_implementation): - """Run the unit test suite.""" - - 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+") - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") - - # 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") - - session.run( - 'py.test', - '--quiet', - '--cov=google/shopping/merchant_quota_v1beta/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - -@nox.session(python=ALL_PYTHON[-1]) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def prerelease_deps(session, protobuf_implementation): - """Run the unit test suite against pre-release versions of dependencies.""" - - 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 test environment dependencies - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - - # Install the package without dependencies - session.install('-e', '.', '--no-deps') - - # We test the minimum dependency versions using the minimum Python - # version so the lowest python runtime that we test has a corresponding constraints - # file, located at `testing/constraints--.txt`, which contains all of the - # 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 - ) - ] - - session.install(*constraints_deps) - - prerel_deps = [ - "googleapis-common-protos", - "google-api-core", - "google-auth", - # Exclude grpcio!=1.67.0rc1 which does not support python 3.13 - "grpcio!=1.67.0rc1", - "grpcio-status", - "protobuf", - "proto-plus", - ] - - for dep in prerel_deps: - session.install("--pre", "--no-deps", "--upgrade", dep) - - # Remaining dependencies - other_deps = [ - "requests", - ] - session.install(*other_deps) - - # Print out prerelease package versions - - session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") - session.run("python", "-c", "import google.auth; print(google.auth.__version__)") - session.run("python", "-c", "import grpc; print(grpc.__version__)") - session.run( - "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" - ) - session.run( - "python", "-c", "import proto; print(proto.__version__)" - ) - - session.run( - 'py.test', - '--quiet', - '--cov=google/shopping/merchant_quota_v1beta/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - - -@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=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 docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==7.0.1", "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=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", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/samples/generated_samples/merchantapi_v1beta_generated_quota_service_list_quota_groups_async.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/samples/generated_samples/merchantapi_v1beta_generated_quota_service_list_quota_groups_async.py deleted file mode 100644 index 9df3fdc41d00..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/samples/generated_samples/merchantapi_v1beta_generated_quota_service_list_quota_groups_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListQuotaGroups -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-quota - - -# [START merchantapi_v1beta_generated_QuotaService_ListQuotaGroups_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_quota_v1beta - - -async def sample_list_quota_groups(): - # Create a client - client = merchant_quota_v1beta.QuotaServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_quota_v1beta.ListQuotaGroupsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_quota_groups(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_QuotaService_ListQuotaGroups_async] diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/samples/generated_samples/merchantapi_v1beta_generated_quota_service_list_quota_groups_sync.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/samples/generated_samples/merchantapi_v1beta_generated_quota_service_list_quota_groups_sync.py deleted file mode 100644 index 9cb0fe36a759..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/samples/generated_samples/merchantapi_v1beta_generated_quota_service_list_quota_groups_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListQuotaGroups -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-quota - - -# [START merchantapi_v1beta_generated_QuotaService_ListQuotaGroups_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_quota_v1beta - - -def sample_list_quota_groups(): - # Create a client - client = merchant_quota_v1beta.QuotaServiceClient() - - # Initialize request argument(s) - request = merchant_quota_v1beta.ListQuotaGroupsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_quota_groups(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_QuotaService_ListQuotaGroups_sync] diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.quota.v1beta.json b/owl-bot-staging/google-shopping-merchant-quota/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.quota.v1beta.json deleted file mode 100644 index 48037ddf7f53..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.quota.v1beta.json +++ /dev/null @@ -1,176 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.shopping.merchant.quota.v1beta", - "version": "v1beta" - } - ], - "language": "PYTHON", - "name": "google-shopping-merchant-quota", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_quota_v1beta.QuotaServiceAsyncClient", - "shortName": "QuotaServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_quota_v1beta.QuotaServiceAsyncClient.list_quota_groups", - "method": { - "fullName": "google.shopping.merchant.quota.v1beta.QuotaService.ListQuotaGroups", - "service": { - "fullName": "google.shopping.merchant.quota.v1beta.QuotaService", - "shortName": "QuotaService" - }, - "shortName": "ListQuotaGroups" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_quota_v1beta.types.ListQuotaGroupsRequest" - }, - { - "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_quota_v1beta.services.quota_service.pagers.ListQuotaGroupsAsyncPager", - "shortName": "list_quota_groups" - }, - "description": "Sample for ListQuotaGroups", - "file": "merchantapi_v1beta_generated_quota_service_list_quota_groups_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_QuotaService_ListQuotaGroups_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_quota_service_list_quota_groups_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_quota_v1beta.QuotaServiceClient", - "shortName": "QuotaServiceClient" - }, - "fullName": "google.shopping.merchant_quota_v1beta.QuotaServiceClient.list_quota_groups", - "method": { - "fullName": "google.shopping.merchant.quota.v1beta.QuotaService.ListQuotaGroups", - "service": { - "fullName": "google.shopping.merchant.quota.v1beta.QuotaService", - "shortName": "QuotaService" - }, - "shortName": "ListQuotaGroups" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_quota_v1beta.types.ListQuotaGroupsRequest" - }, - { - "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_quota_v1beta.services.quota_service.pagers.ListQuotaGroupsPager", - "shortName": "list_quota_groups" - }, - "description": "Sample for ListQuotaGroups", - "file": "merchantapi_v1beta_generated_quota_service_list_quota_groups_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_QuotaService_ListQuotaGroups_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_quota_service_list_quota_groups_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/scripts/fixup_merchant_quota_v1beta_keywords.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/scripts/fixup_merchant_quota_v1beta_keywords.py deleted file mode 100644 index 46854d66644a..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/scripts/fixup_merchant_quota_v1beta_keywords.py +++ /dev/null @@ -1,176 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_quotaCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'list_quota_groups': ('parent', 'page_size', 'page_token', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=merchant_quotaCallTransformer(), -): - """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_quota 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-quota/v1beta/setup.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/setup.py deleted file mode 100644 index 29c7175c3c3a..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/setup.py +++ /dev/null @@ -1,98 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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-quota' - - -description = "Google Shopping Merchant Quota API client library" - -version = None - -with open(os.path.join(package_root, 'google/shopping/merchant_quota/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.0dev,!=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.0dev,!=2.24.0,!=2.25.0", - "proto-plus >= 1.22.3, <2.0.0dev", - "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'", - "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", -] -extras = { -} -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-quota" - -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-quota/v1beta/testing/constraints-3.10.txt b/owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.10.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.10.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.11.txt b/owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.11.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.11.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.12.txt b/owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.12.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.12.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.13.txt b/owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.13.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.13.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.7.txt b/owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.7.txt deleted file mode 100644 index fc812592b0ee..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.7.txt +++ /dev/null @@ -1,10 +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.0dev", -# 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 diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.8.txt b/owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.8.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.8.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.9.txt b/owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.9.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/testing/constraints-3.9.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/google-shopping-merchant-quota/v1beta/tests/__init__.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-quota/v1beta/tests/unit/__init__.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-quota/v1beta/tests/unit/gapic/__init__.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-quota/v1beta/tests/unit/gapic/merchant_quota_v1beta/__init__.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/tests/unit/gapic/merchant_quota_v1beta/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/tests/unit/gapic/merchant_quota_v1beta/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-quota/v1beta/tests/unit/gapic/merchant_quota_v1beta/test_quota_service.py b/owl-bot-staging/google-shopping-merchant-quota/v1beta/tests/unit/gapic/merchant_quota_v1beta/test_quota_service.py deleted file mode 100644 index bdc981b12f6f..000000000000 --- a/owl-bot-staging/google-shopping-merchant-quota/v1beta/tests/unit/gapic/merchant_quota_v1beta/test_quota_service.py +++ /dev/null @@ -1,2347 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_quota_v1beta.services.quota_service import QuotaServiceAsyncClient -from google.shopping.merchant_quota_v1beta.services.quota_service import QuotaServiceClient -from google.shopping.merchant_quota_v1beta.services.quota_service import pagers -from google.shopping.merchant_quota_v1beta.services.quota_service import transports -from google.shopping.merchant_quota_v1beta.types import quota -import google.auth - - -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 QuotaServiceClient._get_default_mtls_endpoint(None) is None - assert QuotaServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert QuotaServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert QuotaServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert QuotaServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert QuotaServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert QuotaServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert QuotaServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert QuotaServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - QuotaServiceClient._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 QuotaServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert QuotaServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert QuotaServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - QuotaServiceClient._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 QuotaServiceClient._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 QuotaServiceClient._get_client_cert_source(None, False) is None - assert QuotaServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert QuotaServiceClient._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 QuotaServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert QuotaServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(QuotaServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(QuotaServiceClient)) -@mock.patch.object(QuotaServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(QuotaServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = QuotaServiceClient._DEFAULT_UNIVERSE - default_endpoint = QuotaServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = QuotaServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert QuotaServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert QuotaServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == QuotaServiceClient.DEFAULT_MTLS_ENDPOINT - assert QuotaServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert QuotaServiceClient._get_api_endpoint(None, None, default_universe, "always") == QuotaServiceClient.DEFAULT_MTLS_ENDPOINT - assert QuotaServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == QuotaServiceClient.DEFAULT_MTLS_ENDPOINT - assert QuotaServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert QuotaServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - QuotaServiceClient._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 QuotaServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert QuotaServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert QuotaServiceClient._get_universe_domain(None, None) == QuotaServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - QuotaServiceClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - - -@pytest.mark.parametrize("client_class,transport_name", [ - (QuotaServiceClient, "grpc"), - (QuotaServiceAsyncClient, "grpc_asyncio"), - (QuotaServiceClient, "rest"), -]) -def test_quota_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.QuotaServiceGrpcTransport, "grpc"), - (transports.QuotaServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.QuotaServiceRestTransport, "rest"), -]) -def test_quota_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", [ - (QuotaServiceClient, "grpc"), - (QuotaServiceAsyncClient, "grpc_asyncio"), - (QuotaServiceClient, "rest"), -]) -def test_quota_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_quota_service_client_get_transport_class(): - transport = QuotaServiceClient.get_transport_class() - available_transports = [ - transports.QuotaServiceGrpcTransport, - transports.QuotaServiceRestTransport, - ] - assert transport in available_transports - - transport = QuotaServiceClient.get_transport_class("grpc") - assert transport == transports.QuotaServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (QuotaServiceClient, transports.QuotaServiceGrpcTransport, "grpc"), - (QuotaServiceAsyncClient, transports.QuotaServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (QuotaServiceClient, transports.QuotaServiceRestTransport, "rest"), -]) -@mock.patch.object(QuotaServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(QuotaServiceClient)) -@mock.patch.object(QuotaServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(QuotaServiceAsyncClient)) -def test_quota_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(QuotaServiceClient, '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(QuotaServiceClient, '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", [ - (QuotaServiceClient, transports.QuotaServiceGrpcTransport, "grpc", "true"), - (QuotaServiceAsyncClient, transports.QuotaServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (QuotaServiceClient, transports.QuotaServiceGrpcTransport, "grpc", "false"), - (QuotaServiceAsyncClient, transports.QuotaServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (QuotaServiceClient, transports.QuotaServiceRestTransport, "rest", "true"), - (QuotaServiceClient, transports.QuotaServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(QuotaServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(QuotaServiceClient)) -@mock.patch.object(QuotaServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(QuotaServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_quota_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", [ - QuotaServiceClient, QuotaServiceAsyncClient -]) -@mock.patch.object(QuotaServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(QuotaServiceClient)) -@mock.patch.object(QuotaServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(QuotaServiceAsyncClient)) -def test_quota_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", [ - QuotaServiceClient, QuotaServiceAsyncClient -]) -@mock.patch.object(QuotaServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(QuotaServiceClient)) -@mock.patch.object(QuotaServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(QuotaServiceAsyncClient)) -def test_quota_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = QuotaServiceClient._DEFAULT_UNIVERSE - default_endpoint = QuotaServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = QuotaServiceClient._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", [ - (QuotaServiceClient, transports.QuotaServiceGrpcTransport, "grpc"), - (QuotaServiceAsyncClient, transports.QuotaServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (QuotaServiceClient, transports.QuotaServiceRestTransport, "rest"), -]) -def test_quota_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", [ - (QuotaServiceClient, transports.QuotaServiceGrpcTransport, "grpc", grpc_helpers), - (QuotaServiceAsyncClient, transports.QuotaServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (QuotaServiceClient, transports.QuotaServiceRestTransport, "rest", None), -]) -def test_quota_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_quota_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_quota_v1beta.services.quota_service.transports.QuotaServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = QuotaServiceClient( - 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", [ - (QuotaServiceClient, transports.QuotaServiceGrpcTransport, "grpc", grpc_helpers), - (QuotaServiceAsyncClient, transports.QuotaServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_quota_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", [ - quota.ListQuotaGroupsRequest, - dict, -]) -def test_list_quota_groups(request_type, transport: str = 'grpc'): - client = QuotaServiceClient( - 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_quota_groups), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = quota.ListQuotaGroupsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_quota_groups(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = quota.ListQuotaGroupsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListQuotaGroupsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_quota_groups_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 = QuotaServiceClient( - 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 = quota.ListQuotaGroupsRequest( - 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_quota_groups), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_quota_groups(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == quota.ListQuotaGroupsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_quota_groups_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = QuotaServiceClient( - 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_quota_groups in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_quota_groups] = mock_rpc - request = {} - client.list_quota_groups(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_quota_groups(request) - - # Establish that a new wrapper 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_quota_groups_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = QuotaServiceAsyncClient( - 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_quota_groups in client._client._transport._wrapped_methods - - # 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_quota_groups] = mock_rpc - - request = {} - await client.list_quota_groups(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_quota_groups(request) - - # Establish that a new wrapper 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_quota_groups_async(transport: str = 'grpc_asyncio', request_type=quota.ListQuotaGroupsRequest): - client = QuotaServiceAsyncClient( - 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_quota_groups), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(quota.ListQuotaGroupsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_quota_groups(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = quota.ListQuotaGroupsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListQuotaGroupsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_quota_groups_async_from_dict(): - await test_list_quota_groups_async(request_type=dict) - -def test_list_quota_groups_field_headers(): - client = QuotaServiceClient( - 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 = quota.ListQuotaGroupsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_quota_groups), - '__call__') as call: - call.return_value = quota.ListQuotaGroupsResponse() - client.list_quota_groups(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_quota_groups_field_headers_async(): - client = QuotaServiceAsyncClient( - 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 = quota.ListQuotaGroupsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_quota_groups), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(quota.ListQuotaGroupsResponse()) - await client.list_quota_groups(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_quota_groups_flattened(): - client = QuotaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_quota_groups), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = quota.ListQuotaGroupsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_quota_groups( - 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_quota_groups_flattened_error(): - client = QuotaServiceClient( - 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_quota_groups( - quota.ListQuotaGroupsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_quota_groups_flattened_async(): - client = QuotaServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_quota_groups), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = quota.ListQuotaGroupsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(quota.ListQuotaGroupsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_quota_groups( - 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_quota_groups_flattened_error_async(): - client = QuotaServiceAsyncClient( - 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_quota_groups( - quota.ListQuotaGroupsRequest(), - parent='parent_value', - ) - - -def test_list_quota_groups_pager(transport_name: str = "grpc"): - client = QuotaServiceClient( - 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_quota_groups), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - quota.ListQuotaGroupsResponse( - quota_groups=[ - quota.QuotaGroup(), - quota.QuotaGroup(), - quota.QuotaGroup(), - ], - next_page_token='abc', - ), - quota.ListQuotaGroupsResponse( - quota_groups=[], - next_page_token='def', - ), - quota.ListQuotaGroupsResponse( - quota_groups=[ - quota.QuotaGroup(), - ], - next_page_token='ghi', - ), - quota.ListQuotaGroupsResponse( - quota_groups=[ - quota.QuotaGroup(), - quota.QuotaGroup(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_quota_groups(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, quota.QuotaGroup) - for i in results) -def test_list_quota_groups_pages(transport_name: str = "grpc"): - client = QuotaServiceClient( - 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_quota_groups), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - quota.ListQuotaGroupsResponse( - quota_groups=[ - quota.QuotaGroup(), - quota.QuotaGroup(), - quota.QuotaGroup(), - ], - next_page_token='abc', - ), - quota.ListQuotaGroupsResponse( - quota_groups=[], - next_page_token='def', - ), - quota.ListQuotaGroupsResponse( - quota_groups=[ - quota.QuotaGroup(), - ], - next_page_token='ghi', - ), - quota.ListQuotaGroupsResponse( - quota_groups=[ - quota.QuotaGroup(), - quota.QuotaGroup(), - ], - ), - RuntimeError, - ) - pages = list(client.list_quota_groups(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_quota_groups_async_pager(): - client = QuotaServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_quota_groups), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - quota.ListQuotaGroupsResponse( - quota_groups=[ - quota.QuotaGroup(), - quota.QuotaGroup(), - quota.QuotaGroup(), - ], - next_page_token='abc', - ), - quota.ListQuotaGroupsResponse( - quota_groups=[], - next_page_token='def', - ), - quota.ListQuotaGroupsResponse( - quota_groups=[ - quota.QuotaGroup(), - ], - next_page_token='ghi', - ), - quota.ListQuotaGroupsResponse( - quota_groups=[ - quota.QuotaGroup(), - quota.QuotaGroup(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_quota_groups(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, quota.QuotaGroup) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_quota_groups_async_pages(): - client = QuotaServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_quota_groups), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - quota.ListQuotaGroupsResponse( - quota_groups=[ - quota.QuotaGroup(), - quota.QuotaGroup(), - quota.QuotaGroup(), - ], - next_page_token='abc', - ), - quota.ListQuotaGroupsResponse( - quota_groups=[], - next_page_token='def', - ), - quota.ListQuotaGroupsResponse( - quota_groups=[ - quota.QuotaGroup(), - ], - next_page_token='ghi', - ), - quota.ListQuotaGroupsResponse( - quota_groups=[ - quota.QuotaGroup(), - quota.QuotaGroup(), - ], - ), - 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_quota_groups(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_quota_groups_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 = QuotaServiceClient( - 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_quota_groups in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_quota_groups] = mock_rpc - - request = {} - client.list_quota_groups(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_quota_groups(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_quota_groups_rest_required_fields(request_type=quota.ListQuotaGroupsRequest): - transport_class = transports.QuotaServiceRestTransport - - 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_quota_groups._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_quota_groups._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 = QuotaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = quota.ListQuotaGroupsResponse() - # 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 = quota.ListQuotaGroupsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_quota_groups(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_quota_groups_rest_unset_required_fields(): - transport = transports.QuotaServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_quota_groups._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_quota_groups_rest_flattened(): - client = QuotaServiceClient( - 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 = quota.ListQuotaGroupsResponse() - - # 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 = quota.ListQuotaGroupsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_quota_groups(**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/quota/v1beta/{parent=accounts/*}/quotas" % client.transport._host, args[1]) - - -def test_list_quota_groups_rest_flattened_error(transport: str = 'rest'): - client = QuotaServiceClient( - 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_quota_groups( - quota.ListQuotaGroupsRequest(), - parent='parent_value', - ) - - -def test_list_quota_groups_rest_pager(transport: str = 'rest'): - client = QuotaServiceClient( - 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 = ( - quota.ListQuotaGroupsResponse( - quota_groups=[ - quota.QuotaGroup(), - quota.QuotaGroup(), - quota.QuotaGroup(), - ], - next_page_token='abc', - ), - quota.ListQuotaGroupsResponse( - quota_groups=[], - next_page_token='def', - ), - quota.ListQuotaGroupsResponse( - quota_groups=[ - quota.QuotaGroup(), - ], - next_page_token='ghi', - ), - quota.ListQuotaGroupsResponse( - quota_groups=[ - quota.QuotaGroup(), - quota.QuotaGroup(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(quota.ListQuotaGroupsResponse.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_quota_groups(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, quota.QuotaGroup) - for i in results) - - pages = list(client.list_quota_groups(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.QuotaServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = QuotaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.QuotaServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = QuotaServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.QuotaServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = QuotaServiceClient( - 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 = QuotaServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.QuotaServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = QuotaServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.QuotaServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = QuotaServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.QuotaServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.QuotaServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.QuotaServiceGrpcTransport, - transports.QuotaServiceGrpcAsyncIOTransport, - transports.QuotaServiceRestTransport, -]) -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 = QuotaServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = QuotaServiceClient( - 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_quota_groups_empty_call_grpc(): - client = QuotaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_quota_groups), - '__call__') as call: - call.return_value = quota.ListQuotaGroupsResponse() - client.list_quota_groups(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = quota.ListQuotaGroupsRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = QuotaServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = QuotaServiceAsyncClient( - 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_quota_groups_empty_call_grpc_asyncio(): - client = QuotaServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_quota_groups), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(quota.ListQuotaGroupsResponse( - next_page_token='next_page_token_value', - )) - await client.list_quota_groups(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = quota.ListQuotaGroupsRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = QuotaServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_list_quota_groups_rest_bad_request(request_type=quota.ListQuotaGroupsRequest): - client = QuotaServiceClient( - 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_quota_groups(request) - - -@pytest.mark.parametrize("request_type", [ - quota.ListQuotaGroupsRequest, - dict, -]) -def test_list_quota_groups_rest_call_success(request_type): - client = QuotaServiceClient( - 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 = quota.ListQuotaGroupsResponse( - 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 = quota.ListQuotaGroupsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_quota_groups(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListQuotaGroupsPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_quota_groups_rest_interceptors(null_interceptor): - transport = transports.QuotaServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.QuotaServiceRestInterceptor(), - ) - client = QuotaServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.QuotaServiceRestInterceptor, "post_list_quota_groups") as post, \ - mock.patch.object(transports.QuotaServiceRestInterceptor, "pre_list_quota_groups") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = quota.ListQuotaGroupsRequest.pb(quota.ListQuotaGroupsRequest()) - 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 = quota.ListQuotaGroupsResponse.to_json(quota.ListQuotaGroupsResponse()) - req.return_value.content = return_value - - request = quota.ListQuotaGroupsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = quota.ListQuotaGroupsResponse() - - client.list_quota_groups(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - -def test_initialize_client_w_rest(): - client = QuotaServiceClient( - 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_quota_groups_empty_call_rest(): - client = QuotaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_quota_groups), - '__call__') as call: - client.list_quota_groups(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = quota.ListQuotaGroupsRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = QuotaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.QuotaServiceGrpcTransport, - ) - -def test_quota_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.QuotaServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_quota_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.shopping.merchant_quota_v1beta.services.quota_service.transports.QuotaServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.QuotaServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_quota_groups', - ) - 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_quota_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_quota_v1beta.services.quota_service.transports.QuotaServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.QuotaServiceTransport( - 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_quota_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_quota_v1beta.services.quota_service.transports.QuotaServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.QuotaServiceTransport() - adc.assert_called_once() - - -def test_quota_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) - QuotaServiceClient() - 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.QuotaServiceGrpcTransport, - transports.QuotaServiceGrpcAsyncIOTransport, - ], -) -def test_quota_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.QuotaServiceGrpcTransport, - transports.QuotaServiceGrpcAsyncIOTransport, - transports.QuotaServiceRestTransport, - ], -) -def test_quota_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.QuotaServiceGrpcTransport, grpc_helpers), - (transports.QuotaServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_quota_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.QuotaServiceGrpcTransport, transports.QuotaServiceGrpcAsyncIOTransport]) -def test_quota_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_quota_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.QuotaServiceRestTransport ( - 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_quota_service_host_no_port(transport_name): - client = QuotaServiceClient( - 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_quota_service_host_with_port(transport_name): - client = QuotaServiceClient( - 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_quota_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = QuotaServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = QuotaServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_quota_groups._session - session2 = client2.transport.list_quota_groups._session - assert session1 != session2 -def test_quota_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.QuotaServiceGrpcTransport( - 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_quota_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.QuotaServiceGrpcAsyncIOTransport( - 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.QuotaServiceGrpcTransport, transports.QuotaServiceGrpcAsyncIOTransport]) -def test_quota_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.QuotaServiceGrpcTransport, transports.QuotaServiceGrpcAsyncIOTransport]) -def test_quota_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_quota_group_path(): - account = "squid" - group = "clam" - expected = "accounts/{account}/groups/{group}".format(account=account, group=group, ) - actual = QuotaServiceClient.quota_group_path(account, group) - assert expected == actual - - -def test_parse_quota_group_path(): - expected = { - "account": "whelk", - "group": "octopus", - } - path = QuotaServiceClient.quota_group_path(**expected) - - # Check that the path construction is reversible. - actual = QuotaServiceClient.parse_quota_group_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = QuotaServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = QuotaServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = QuotaServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = QuotaServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = QuotaServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = QuotaServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = QuotaServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = QuotaServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = QuotaServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = QuotaServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = QuotaServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = QuotaServiceClient.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 = QuotaServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = QuotaServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = QuotaServiceClient.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.QuotaServiceTransport, '_prep_wrapped_messages') as prep: - client = QuotaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.QuotaServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = QuotaServiceClient.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 = QuotaServiceClient( - 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 = QuotaServiceAsyncClient( - 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 = QuotaServiceClient( - 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 = QuotaServiceClient( - 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", [ - (QuotaServiceClient, transports.QuotaServiceGrpcTransport), - (QuotaServiceAsyncClient, transports.QuotaServiceGrpcAsyncIOTransport), -]) -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-reports/v1beta/.coveragerc b/owl-bot-staging/google-shopping-merchant-reports/v1beta/.coveragerc deleted file mode 100644 index ee0fc2257adb..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/v1beta/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/shopping/merchant_reports/__init__.py - google/shopping/merchant_reports/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-reports/v1beta/.flake8 b/owl-bot-staging/google-shopping-merchant-reports/v1beta/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/v1beta/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/MANIFEST.in b/owl-bot-staging/google-shopping-merchant-reports/v1beta/MANIFEST.in deleted file mode 100644 index baaee74264b4..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/v1beta/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/shopping/merchant_reports *.py -recursive-include google/shopping/merchant_reports_v1beta *.py diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/README.rst b/owl-bot-staging/google-shopping-merchant-reports/v1beta/README.rst deleted file mode 100644 index 33f7f87a7a6c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/v1beta/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Shopping Merchant Reports 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 Reports 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 diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/_static/custom.css b/owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/_static/custom.css +++ /dev/null @@ -1,3 +0,0 @@ -dl.field-list > dt { - min-width: 100px -} diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/conf.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/conf.py deleted file mode 100644 index e082f6d42016..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-reports 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("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# 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.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -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-reports" -copyright = u"2023, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# 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 = 'en' - -# 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"] - -# 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 Python", - "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-reports-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-reports.tex", - u"google-shopping-merchant-reports 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-reports", - u"Google Shopping Merchant Reports 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-reports", - u"google-shopping-merchant-reports Documentation", - author, - "google-shopping-merchant-reports", - "GAPIC library for Google Shopping Merchant Reports API", - "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": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", 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-reports/v1beta/docs/index.rst b/owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/index.rst deleted file mode 100644 index 56b119bc9a3d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - merchant_reports_v1beta/services_ - merchant_reports_v1beta/types_ diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/merchant_reports_v1beta/report_service.rst b/owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/merchant_reports_v1beta/report_service.rst deleted file mode 100644 index 38d2a647339e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/merchant_reports_v1beta/report_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -ReportService -------------------------------- - -.. automodule:: google.shopping.merchant_reports_v1beta.services.report_service - :members: - :inherited-members: - -.. automodule:: google.shopping.merchant_reports_v1beta.services.report_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/merchant_reports_v1beta/services_.rst b/owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/merchant_reports_v1beta/services_.rst deleted file mode 100644 index 55109976f640..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/merchant_reports_v1beta/services_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Shopping Merchant Reports v1beta API -======================================================== -.. toctree:: - :maxdepth: 2 - - report_service diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/merchant_reports_v1beta/types_.rst b/owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/merchant_reports_v1beta/types_.rst deleted file mode 100644 index 3f9d6a921dbd..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/v1beta/docs/merchant_reports_v1beta/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Shopping Merchant Reports v1beta API -===================================================== - -.. automodule:: google.shopping.merchant_reports_v1beta.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports/__init__.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports/__init__.py deleted file mode 100644 index 9a1854b53a00..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports/__init__.py +++ /dev/null @@ -1,63 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_reports import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.shopping.merchant_reports_v1beta.services.report_service.client import ReportServiceClient -from google.shopping.merchant_reports_v1beta.services.report_service.async_client import ReportServiceAsyncClient - -from google.shopping.merchant_reports_v1beta.types.reports import BestSellersBrandView -from google.shopping.merchant_reports_v1beta.types.reports import BestSellersProductClusterView -from google.shopping.merchant_reports_v1beta.types.reports import CompetitiveVisibilityBenchmarkView -from google.shopping.merchant_reports_v1beta.types.reports import CompetitiveVisibilityCompetitorView -from google.shopping.merchant_reports_v1beta.types.reports import CompetitiveVisibilityTopMerchantView -from google.shopping.merchant_reports_v1beta.types.reports import MarketingMethod -from google.shopping.merchant_reports_v1beta.types.reports import NonProductPerformanceView -from google.shopping.merchant_reports_v1beta.types.reports import PriceCompetitivenessProductView -from google.shopping.merchant_reports_v1beta.types.reports import PriceInsightsProductView -from google.shopping.merchant_reports_v1beta.types.reports import ProductPerformanceView -from google.shopping.merchant_reports_v1beta.types.reports import ProductView -from google.shopping.merchant_reports_v1beta.types.reports import RelativeDemand -from google.shopping.merchant_reports_v1beta.types.reports import RelativeDemandChangeType -from google.shopping.merchant_reports_v1beta.types.reports import ReportGranularity -from google.shopping.merchant_reports_v1beta.types.reports import ReportRow -from google.shopping.merchant_reports_v1beta.types.reports import SearchRequest -from google.shopping.merchant_reports_v1beta.types.reports import SearchResponse -from google.shopping.merchant_reports_v1beta.types.reports import TrafficSource - -__all__ = ('ReportServiceClient', - 'ReportServiceAsyncClient', - 'BestSellersBrandView', - 'BestSellersProductClusterView', - 'CompetitiveVisibilityBenchmarkView', - 'CompetitiveVisibilityCompetitorView', - 'CompetitiveVisibilityTopMerchantView', - 'MarketingMethod', - 'NonProductPerformanceView', - 'PriceCompetitivenessProductView', - 'PriceInsightsProductView', - 'ProductPerformanceView', - 'ProductView', - 'RelativeDemand', - 'RelativeDemandChangeType', - 'ReportGranularity', - 'ReportRow', - 'SearchRequest', - 'SearchResponse', - 'TrafficSource', -) diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports/gapic_version.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-reports/v1beta/google/shopping/merchant_reports/py.typed b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports/py.typed deleted file mode 100644 index 925c5df4dab6..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-shopping-merchant-reports package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/__init__.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/__init__.py deleted file mode 100644 index 3f709e1477bb..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/__init__.py +++ /dev/null @@ -1,64 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_reports_v1beta import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.report_service import ReportServiceClient -from .services.report_service import ReportServiceAsyncClient - -from .types.reports import BestSellersBrandView -from .types.reports import BestSellersProductClusterView -from .types.reports import CompetitiveVisibilityBenchmarkView -from .types.reports import CompetitiveVisibilityCompetitorView -from .types.reports import CompetitiveVisibilityTopMerchantView -from .types.reports import MarketingMethod -from .types.reports import NonProductPerformanceView -from .types.reports import PriceCompetitivenessProductView -from .types.reports import PriceInsightsProductView -from .types.reports import ProductPerformanceView -from .types.reports import ProductView -from .types.reports import RelativeDemand -from .types.reports import RelativeDemandChangeType -from .types.reports import ReportGranularity -from .types.reports import ReportRow -from .types.reports import SearchRequest -from .types.reports import SearchResponse -from .types.reports import TrafficSource - -__all__ = ( - 'ReportServiceAsyncClient', -'BestSellersBrandView', -'BestSellersProductClusterView', -'CompetitiveVisibilityBenchmarkView', -'CompetitiveVisibilityCompetitorView', -'CompetitiveVisibilityTopMerchantView', -'MarketingMethod', -'NonProductPerformanceView', -'PriceCompetitivenessProductView', -'PriceInsightsProductView', -'ProductPerformanceView', -'ProductView', -'RelativeDemand', -'RelativeDemandChangeType', -'ReportGranularity', -'ReportRow', -'ReportServiceClient', -'SearchRequest', -'SearchResponse', -'TrafficSource', -) diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/gapic_metadata.json b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/gapic_metadata.json deleted file mode 100644 index 77c560dce3aa..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/gapic_metadata.json +++ /dev/null @@ -1,43 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.shopping.merchant_reports_v1beta", - "protoPackage": "google.shopping.merchant.reports.v1beta", - "schema": "1.0", - "services": { - "ReportService": { - "clients": { - "grpc": { - "libraryClient": "ReportServiceClient", - "rpcs": { - "Search": { - "methods": [ - "search" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ReportServiceAsyncClient", - "rpcs": { - "Search": { - "methods": [ - "search" - ] - } - } - }, - "rest": { - "libraryClient": "ReportServiceClient", - "rpcs": { - "Search": { - "methods": [ - "search" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/gapic_version.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-reports/v1beta/google/shopping/merchant_reports_v1beta/py.typed b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/py.typed deleted file mode 100644 index 925c5df4dab6..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-shopping-merchant-reports package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/__init__.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/__init__.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/__init__.py deleted file mode 100644 index 90845062383d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 ReportServiceClient -from .async_client import ReportServiceAsyncClient - -__all__ = ( - 'ReportServiceClient', - 'ReportServiceAsyncClient', -) diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/async_client.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/async_client.py deleted file mode 100644 index d2879ac7215b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/async_client.py +++ /dev/null @@ -1,385 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_reports_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 - - -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_reports_v1beta.services.report_service import pagers -from google.shopping.merchant_reports_v1beta.types import reports -from .transports.base import ReportServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ReportServiceGrpcAsyncIOTransport -from .client import ReportServiceClient - -try: - from google.api_core import client_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 ReportServiceAsyncClient: - """Service for retrieving reports and insights about your - products, their performance, and their competitive environment - on Google. - """ - - _client: ReportServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = ReportServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ReportServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = ReportServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = ReportServiceClient._DEFAULT_UNIVERSE - - common_billing_account_path = staticmethod(ReportServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ReportServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ReportServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(ReportServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(ReportServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(ReportServiceClient.parse_common_organization_path) - common_project_path = staticmethod(ReportServiceClient.common_project_path) - parse_common_project_path = staticmethod(ReportServiceClient.parse_common_project_path) - common_location_path = staticmethod(ReportServiceClient.common_location_path) - parse_common_location_path = staticmethod(ReportServiceClient.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: - ReportServiceAsyncClient: The constructed client. - """ - return ReportServiceClient.from_service_account_info.__func__(ReportServiceAsyncClient, 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: - ReportServiceAsyncClient: The constructed client. - """ - return ReportServiceClient.from_service_account_file.__func__(ReportServiceAsyncClient, 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 ReportServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ReportServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ReportServiceTransport: 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 = ReportServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, ReportServiceTransport, Callable[..., ReportServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the report 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,ReportServiceTransport,Callable[..., ReportServiceTransport]]]): - 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 ReportServiceTransport 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 = ReportServiceClient( - 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.reports_v1beta.ReportServiceAsyncClient`.", - extra = { - "serviceName": "google.shopping.merchant.reports.v1beta.ReportService", - "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.reports.v1beta.ReportService", - "credentialsType": None, - } - ) - - async def search(self, - request: Optional[Union[reports.SearchRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.SearchAsyncPager: - r"""Retrieves a report defined by a search query. The response might - contain fewer rows than specified by ``page_size``. Rely on - ``next_page_token`` to determine if there are more rows to be - requested. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_reports_v1beta - - async def sample_search(): - # Create a client - client = merchant_reports_v1beta.ReportServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_reports_v1beta.SearchRequest( - parent="parent_value", - query="query_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_reports_v1beta.types.SearchRequest, dict]]): - The request object. Request message for the ``ReportService.Search`` method. - parent (:class:`str`): - Required. Id of the account making - the call. Must be a standalone account - or an MCA subaccount. 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_reports_v1beta.services.report_service.pagers.SearchAsyncPager: - Response message for the ReportService.Search 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, reports.SearchRequest): - request = reports.SearchRequest(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.search] - - # Certain 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.SearchAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self) -> "ReportServiceAsyncClient": - 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__) - - -__all__ = ( - "ReportServiceAsyncClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/client.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/client.py deleted file mode 100644 index dbef05c011c0..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/client.py +++ /dev/null @@ -1,711 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -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_reports_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 - -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_reports_v1beta.services.report_service import pagers -from google.shopping.merchant_reports_v1beta.types import reports -from .transports.base import ReportServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ReportServiceGrpcTransport -from .transports.grpc_asyncio import ReportServiceGrpcAsyncIOTransport -from .transports.rest import ReportServiceRestTransport - - -class ReportServiceClientMeta(type): - """Metaclass for the ReportService 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[ReportServiceTransport]] - _transport_registry["grpc"] = ReportServiceGrpcTransport - _transport_registry["grpc_asyncio"] = ReportServiceGrpcAsyncIOTransport - _transport_registry["rest"] = ReportServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[ReportServiceTransport]: - """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 ReportServiceClient(metaclass=ReportServiceClientMeta): - """Service for retrieving reports and insights about your - products, their performance, and their competitive environment - on Google. - """ - - @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: - ReportServiceClient: 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: - ReportServiceClient: 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) -> ReportServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ReportServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @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 = ReportServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = ReportServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = ReportServiceClient._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 = ReportServiceClient._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 - - @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, ReportServiceTransport, Callable[..., ReportServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the report 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,ReportServiceTransport,Callable[..., ReportServiceTransport]]]): - 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 ReportServiceTransport 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 = ReportServiceClient._read_environment_variables() - self._client_cert_source = ReportServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = ReportServiceClient._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, ReportServiceTransport) - if transport_provided: - # transport is a ReportServiceTransport 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(ReportServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - ReportServiceClient._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[ReportServiceTransport], Callable[..., ReportServiceTransport]] = ( - ReportServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., ReportServiceTransport], 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.reports_v1beta.ReportServiceClient`.", - extra = { - "serviceName": "google.shopping.merchant.reports.v1beta.ReportService", - "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.reports.v1beta.ReportService", - "credentialsType": None, - } - ) - - def search(self, - request: Optional[Union[reports.SearchRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.SearchPager: - r"""Retrieves a report defined by a search query. The response might - contain fewer rows than specified by ``page_size``. Rely on - ``next_page_token`` to determine if there are more rows to be - requested. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_reports_v1beta - - def sample_search(): - # Create a client - client = merchant_reports_v1beta.ReportServiceClient() - - # Initialize request argument(s) - request = merchant_reports_v1beta.SearchRequest( - parent="parent_value", - query="query_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.shopping.merchant_reports_v1beta.types.SearchRequest, dict]): - The request object. Request message for the ``ReportService.Search`` method. - parent (str): - Required. Id of the account making - the call. Must be a standalone account - or an MCA subaccount. 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_reports_v1beta.services.report_service.pagers.SearchPager: - Response message for the ReportService.Search 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, reports.SearchRequest): - request = reports.SearchRequest(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.search] - - # Certain 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.SearchPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "ReportServiceClient": - 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__) - - -__all__ = ( - "ReportServiceClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/pagers.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/pagers.py deleted file mode 100644 index 272b1d940d9b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/pagers.py +++ /dev/null @@ -1,166 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_reports_v1beta.types import reports - - -class SearchPager: - """A pager for iterating through ``search`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_reports_v1beta.types.SearchResponse` object, and - provides an ``__iter__`` method to iterate through its - ``results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``Search`` requests and continue to iterate - through the ``results`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_reports_v1beta.types.SearchResponse` - 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[..., reports.SearchResponse], - request: reports.SearchRequest, - response: reports.SearchResponse, - *, - 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_reports_v1beta.types.SearchRequest): - The initial request object. - response (google.shopping.merchant_reports_v1beta.types.SearchResponse): - 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 = reports.SearchRequest(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[reports.SearchResponse]: - 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[reports.ReportRow]: - for page in self.pages: - yield from page.results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class SearchAsyncPager: - """A pager for iterating through ``search`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_reports_v1beta.types.SearchResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``Search`` requests and continue to iterate - through the ``results`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_reports_v1beta.types.SearchResponse` - 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[reports.SearchResponse]], - request: reports.SearchRequest, - response: reports.SearchResponse, - *, - 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_reports_v1beta.types.SearchRequest): - The initial request object. - response (google.shopping.merchant_reports_v1beta.types.SearchResponse): - 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 = reports.SearchRequest(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[reports.SearchResponse]: - 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[reports.ReportRow]: - async def async_generator(): - async for page in self.pages: - for response in page.results: - 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-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/README.rst deleted file mode 100644 index 3ff494d6f149..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`ReportServiceTransport` is the ABC for all transports. -- public child `ReportServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `ReportServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseReportServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `ReportServiceRestTransport` 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-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/__init__.py deleted file mode 100644 index a2d3480db148..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 ReportServiceTransport -from .grpc import ReportServiceGrpcTransport -from .grpc_asyncio import ReportServiceGrpcAsyncIOTransport -from .rest import ReportServiceRestTransport -from .rest import ReportServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ReportServiceTransport]] -_transport_registry['grpc'] = ReportServiceGrpcTransport -_transport_registry['grpc_asyncio'] = ReportServiceGrpcAsyncIOTransport -_transport_registry['rest'] = ReportServiceRestTransport - -__all__ = ( - 'ReportServiceTransport', - 'ReportServiceGrpcTransport', - 'ReportServiceGrpcAsyncIOTransport', - 'ReportServiceRestTransport', - 'ReportServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/base.py deleted file mode 100644 index 93d8c8bff712..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/base.py +++ /dev/null @@ -1,154 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_reports_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 - -from google.shopping.merchant_reports_v1beta.types import reports - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class ReportServiceTransport(abc.ABC): - """Abstract transport class for ReportService.""" - - 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.search: gapic_v1.method.wrap_method( - self.search, - 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 search(self) -> Callable[ - [reports.SearchRequest], - Union[ - reports.SearchResponse, - Awaitable[reports.SearchResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ReportServiceTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/grpc.py deleted file mode 100644 index 0ce8c3266cbb..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/grpc.py +++ /dev/null @@ -1,352 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_reports_v1beta.types import reports -from .base import ReportServiceTransport, 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.reports.v1beta.ReportService", - "rpcName": 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.reports.v1beta.ReportService", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class ReportServiceGrpcTransport(ReportServiceTransport): - """gRPC backend transport for ReportService. - - Service for retrieving reports and insights about your - products, their performance, and their competitive environment - on Google. - - This 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 search(self) -> Callable[ - [reports.SearchRequest], - reports.SearchResponse]: - r"""Return a callable for the search method over gRPC. - - Retrieves a report defined by a search query. The response might - contain fewer rows than specified by ``page_size``. Rely on - ``next_page_token`` to determine if there are more rows to be - requested. - - Returns: - Callable[[~.SearchRequest], - ~.SearchResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search' not in self._stubs: - self._stubs['search'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.reports.v1beta.ReportService/Search', - request_serializer=reports.SearchRequest.serialize, - response_deserializer=reports.SearchResponse.deserialize, - ) - return self._stubs['search'] - - def close(self): - self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ReportServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/grpc_asyncio.py deleted file mode 100644 index 0820b13df3a3..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,372 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_reports_v1beta.types import reports -from .base import ReportServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import ReportServiceGrpcTransport - -try: - from google.api_core import client_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.reports.v1beta.ReportService", - "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.reports.v1beta.ReportService", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class ReportServiceGrpcAsyncIOTransport(ReportServiceTransport): - """gRPC AsyncIO backend transport for ReportService. - - Service for retrieving reports and insights about your - products, their performance, and their competitive environment - on Google. - - This 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 search(self) -> Callable[ - [reports.SearchRequest], - Awaitable[reports.SearchResponse]]: - r"""Return a callable for the search method over gRPC. - - Retrieves a report defined by a search query. The response might - contain fewer rows than specified by ``page_size``. Rely on - ``next_page_token`` to determine if there are more rows to be - requested. - - Returns: - Callable[[~.SearchRequest], - Awaitable[~.SearchResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search' not in self._stubs: - self._stubs['search'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.reports.v1beta.ReportService/Search', - request_serializer=reports.SearchRequest.serialize, - response_deserializer=reports.SearchResponse.deserialize, - ) - return self._stubs['search'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.search: self._wrap_method( - self.search, - 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__ = ( - 'ReportServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/rest.py deleted file mode 100644 index 870bb0a81407..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/rest.py +++ /dev/null @@ -1,333 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -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_reports_v1beta.types import reports - - -from .rest_base import _BaseReportServiceRestTransport -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}", -) - - -class ReportServiceRestInterceptor: - """Interceptor for ReportService. - - 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 ReportServiceRestTransport. - - .. code-block:: python - class MyCustomReportServiceInterceptor(ReportServiceRestInterceptor): - def pre_search(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_search(self, response): - logging.log(f"Received response: {response}") - return response - - transport = ReportServiceRestTransport(interceptor=MyCustomReportServiceInterceptor()) - client = ReportServiceClient(transport=transport) - - - """ - def pre_search(self, request: reports.SearchRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[reports.SearchRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for search - - Override in a subclass to manipulate the request or metadata - before they are sent to the ReportService server. - """ - return request, metadata - - def post_search(self, response: reports.SearchResponse) -> reports.SearchResponse: - """Post-rpc interceptor for search - - Override in a subclass to manipulate the response - after it is returned by the ReportService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class ReportServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: ReportServiceRestInterceptor - - -class ReportServiceRestTransport(_BaseReportServiceRestTransport): - """REST backend synchronous transport for ReportService. - - Service for retrieving reports and insights about your - products, their performance, and their competitive environment - on Google. - - This 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[ReportServiceRestInterceptor] = 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 ReportServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _Search(_BaseReportServiceRestTransport._BaseSearch, ReportServiceRestStub): - def __hash__(self): - return hash("ReportServiceRestTransport.Search") - - @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: reports.SearchRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> reports.SearchResponse: - r"""Call the search method over HTTP. - - Args: - request (~.reports.SearchRequest): - The request object. Request message for the ``ReportService.Search`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.reports.SearchResponse: - Response message for the ``ReportService.Search`` - method. - - """ - - http_options = _BaseReportServiceRestTransport._BaseSearch._get_http_options() - - request, metadata = self._interceptor.pre_search(request, metadata) - transcoded_request = _BaseReportServiceRestTransport._BaseSearch._get_transcoded_request(http_options, request) - - body = _BaseReportServiceRestTransport._BaseSearch._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseReportServiceRestTransport._BaseSearch._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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.reports_v1beta.ReportServiceClient.Search", - extra = { - "serviceName": "google.shopping.merchant.reports.v1beta.ReportService", - "rpcName": "Search", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ReportServiceRestTransport._Search._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 = reports.SearchResponse() - pb_resp = reports.SearchResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_search(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = reports.SearchResponse.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.reports_v1beta.ReportServiceClient.search", - extra = { - "serviceName": "google.shopping.merchant.reports.v1beta.ReportService", - "rpcName": "Search", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def search(self) -> Callable[ - [reports.SearchRequest], - reports.SearchResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._Search(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'ReportServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/rest_base.py deleted file mode 100644 index b7f01e752a42..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/services/report_service/transports/rest_base.py +++ /dev/null @@ -1,138 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 ReportServiceTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.shopping.merchant_reports_v1beta.types import reports - - -class _BaseReportServiceRestTransport(ReportServiceTransport): - """Base REST backend transport for ReportService. - - 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 _BaseSearch: - 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': '/reports/v1beta/{parent=accounts/*}/reports:search', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = reports.SearchRequest.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(_BaseReportServiceRestTransport._BaseSearch._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseReportServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/types/__init__.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/types/__init__.py deleted file mode 100644 index 5e965be69091..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/types/__init__.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .reports import ( - BestSellersBrandView, - BestSellersProductClusterView, - CompetitiveVisibilityBenchmarkView, - CompetitiveVisibilityCompetitorView, - CompetitiveVisibilityTopMerchantView, - MarketingMethod, - NonProductPerformanceView, - PriceCompetitivenessProductView, - PriceInsightsProductView, - ProductPerformanceView, - ProductView, - RelativeDemand, - RelativeDemandChangeType, - ReportGranularity, - ReportRow, - SearchRequest, - SearchResponse, - TrafficSource, -) - -__all__ = ( - 'BestSellersBrandView', - 'BestSellersProductClusterView', - 'CompetitiveVisibilityBenchmarkView', - 'CompetitiveVisibilityCompetitorView', - 'CompetitiveVisibilityTopMerchantView', - 'MarketingMethod', - 'NonProductPerformanceView', - 'PriceCompetitivenessProductView', - 'PriceInsightsProductView', - 'ProductPerformanceView', - 'ProductView', - 'RelativeDemand', - 'RelativeDemandChangeType', - 'ReportGranularity', - 'ReportRow', - 'SearchRequest', - 'SearchResponse', - 'TrafficSource', -) diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/types/reports.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/types/reports.py deleted file mode 100644 index 49712fcea3ab..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/v1beta/google/shopping/merchant_reports_v1beta/types/reports.py +++ /dev/null @@ -1,2521 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 timestamp_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.reports.v1beta', - manifest={ - 'SearchRequest', - 'SearchResponse', - 'ReportRow', - 'ProductPerformanceView', - 'ProductView', - 'PriceCompetitivenessProductView', - 'PriceInsightsProductView', - 'BestSellersProductClusterView', - 'BestSellersBrandView', - 'NonProductPerformanceView', - 'CompetitiveVisibilityCompetitorView', - 'CompetitiveVisibilityTopMerchantView', - 'CompetitiveVisibilityBenchmarkView', - 'MarketingMethod', - 'ReportGranularity', - 'RelativeDemand', - 'RelativeDemandChangeType', - 'TrafficSource', - }, -) - - -class SearchRequest(proto.Message): - r"""Request message for the ``ReportService.Search`` method. - - Attributes: - parent (str): - Required. Id of the account making the call. - Must be a standalone account or an MCA - subaccount. Format: accounts/{account} - query (str): - Required. Query that defines a report to be - retrieved. - For details on how to construct your query, see - the Query Language guide. For the full list of - available tables and fields, see the Available - fields. - page_size (int): - Optional. Number of ``ReportRows`` to retrieve in a single - page. Defaults to 1000. Values above 5000 are coerced to - 5000. - page_token (str): - Optional. Token of the page to retrieve. If not specified, - the first page of results is returned. In order to request - the next page of results, the value obtained from - ``next_page_token`` in the previous response should be used. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - query: str = proto.Field( - proto.STRING, - number=2, - ) - page_size: int = proto.Field( - proto.INT32, - number=3, - ) - page_token: str = proto.Field( - proto.STRING, - number=4, - ) - - -class SearchResponse(proto.Message): - r"""Response message for the ``ReportService.Search`` method. - - Attributes: - results (MutableSequence[google.shopping.merchant_reports_v1beta.types.ReportRow]): - Rows that matched the search query. - next_page_token (str): - Token which can be sent as ``page_token`` to retrieve the - next page. If omitted, there are no subsequent pages. - """ - - @property - def raw_page(self): - return self - - results: MutableSequence['ReportRow'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ReportRow', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ReportRow(proto.Message): - r"""Result row returned from the search query. - - Only the message corresponding to the queried table is populated - in the response. Within the populated message, only the fields - requested explicitly in the query are populated. - - Attributes: - product_performance_view (google.shopping.merchant_reports_v1beta.types.ProductPerformanceView): - Fields available for query in ``product_performance_view`` - table. - non_product_performance_view (google.shopping.merchant_reports_v1beta.types.NonProductPerformanceView): - Fields available for query in - ``non_product_performance_view`` table. - product_view (google.shopping.merchant_reports_v1beta.types.ProductView): - Fields available for query in ``product_view`` table. - price_competitiveness_product_view (google.shopping.merchant_reports_v1beta.types.PriceCompetitivenessProductView): - Fields available for query in - ``price_competitiveness_product_view`` table. - price_insights_product_view (google.shopping.merchant_reports_v1beta.types.PriceInsightsProductView): - Fields available for query in - ``price_insights_product_view`` table. - best_sellers_product_cluster_view (google.shopping.merchant_reports_v1beta.types.BestSellersProductClusterView): - Fields available for query in - ``best_sellers_product_cluster_view`` table. - best_sellers_brand_view (google.shopping.merchant_reports_v1beta.types.BestSellersBrandView): - Fields available for query in ``best_sellers_brand_view`` - table. - competitive_visibility_competitor_view (google.shopping.merchant_reports_v1beta.types.CompetitiveVisibilityCompetitorView): - Fields available for query in - ``competitive_visibility_competitor_view`` table. - competitive_visibility_top_merchant_view (google.shopping.merchant_reports_v1beta.types.CompetitiveVisibilityTopMerchantView): - Fields available for query in - ``competitive_visibility_top_merchant_view`` table. - competitive_visibility_benchmark_view (google.shopping.merchant_reports_v1beta.types.CompetitiveVisibilityBenchmarkView): - Fields available for query in - ``competitive_visibility_benchmark_view`` table. - """ - - product_performance_view: 'ProductPerformanceView' = proto.Field( - proto.MESSAGE, - number=1, - message='ProductPerformanceView', - ) - non_product_performance_view: 'NonProductPerformanceView' = proto.Field( - proto.MESSAGE, - number=7, - message='NonProductPerformanceView', - ) - product_view: 'ProductView' = proto.Field( - proto.MESSAGE, - number=2, - message='ProductView', - ) - price_competitiveness_product_view: 'PriceCompetitivenessProductView' = proto.Field( - proto.MESSAGE, - number=3, - message='PriceCompetitivenessProductView', - ) - price_insights_product_view: 'PriceInsightsProductView' = proto.Field( - proto.MESSAGE, - number=4, - message='PriceInsightsProductView', - ) - best_sellers_product_cluster_view: 'BestSellersProductClusterView' = proto.Field( - proto.MESSAGE, - number=5, - message='BestSellersProductClusterView', - ) - best_sellers_brand_view: 'BestSellersBrandView' = proto.Field( - proto.MESSAGE, - number=6, - message='BestSellersBrandView', - ) - competitive_visibility_competitor_view: 'CompetitiveVisibilityCompetitorView' = proto.Field( - proto.MESSAGE, - number=8, - message='CompetitiveVisibilityCompetitorView', - ) - competitive_visibility_top_merchant_view: 'CompetitiveVisibilityTopMerchantView' = proto.Field( - proto.MESSAGE, - number=9, - message='CompetitiveVisibilityTopMerchantView', - ) - competitive_visibility_benchmark_view: 'CompetitiveVisibilityBenchmarkView' = proto.Field( - proto.MESSAGE, - number=10, - message='CompetitiveVisibilityBenchmarkView', - ) - - -class ProductPerformanceView(proto.Message): - r"""Fields available for query in ``product_performance_view`` table. - - Product performance data for your account, including performance - metrics (for example, ``clicks``) and dimensions according to which - performance metrics are segmented (for example, ``offer_id``). - Values of product dimensions, such as ``offer_id``, reflect the - state of a product at the time of the impression. - - Segment fields cannot be selected in queries without also selecting - at least one metric field. - - Values are only set for fields requested explicitly in the request's - search query. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - marketing_method (google.shopping.merchant_reports_v1beta.types.MarketingMethod.MarketingMethodEnum): - Marketing method to which metrics apply. - Segment. - - This field is a member of `oneof`_ ``_marketing_method``. - date (google.type.date_pb2.Date): - Date in the merchant timezone to which metrics apply. - Segment. - - Condition on ``date`` is required in the ``WHERE`` clause. - week (google.type.date_pb2.Date): - First day of the week (Monday) of the metrics - date in the merchant timezone. Segment. - customer_country_code (str): - Code of the country where the customer is - located at the time of the event. Represented in - the ISO 3166 format. Segment. - - If the customer country cannot be determined, a - special 'ZZ' code is returned. - - This field is a member of `oneof`_ ``_customer_country_code``. - offer_id (str): - Merchant-provided id of the product. Segment. - - This field is a member of `oneof`_ ``_offer_id``. - title (str): - Title of the product. Segment. - - This field is a member of `oneof`_ ``_title``. - brand (str): - Brand of the product. Segment. - - This field is a member of `oneof`_ ``_brand``. - category_l1 (str): - `Product category (1st - level) `__ - in Google's product taxonomy. Segment. - - This field is a member of `oneof`_ ``_category_l1``. - category_l2 (str): - `Product category (2nd - level) `__ - in Google's product taxonomy. Segment. - - This field is a member of `oneof`_ ``_category_l2``. - category_l3 (str): - `Product category (3rd - level) `__ - in Google's product taxonomy. Segment. - - This field is a member of `oneof`_ ``_category_l3``. - category_l4 (str): - `Product category (4th - level) `__ - in Google's product taxonomy. Segment. - - This field is a member of `oneof`_ ``_category_l4``. - category_l5 (str): - `Product category (5th - level) `__ - in Google's product taxonomy. Segment. - - This field is a member of `oneof`_ ``_category_l5``. - product_type_l1 (str): - `Product type (1st - level) `__ - in merchant's own product taxonomy. Segment. - - This field is a member of `oneof`_ ``_product_type_l1``. - product_type_l2 (str): - `Product type (2nd - level) `__ - in merchant's own product taxonomy. Segment. - - This field is a member of `oneof`_ ``_product_type_l2``. - product_type_l3 (str): - `Product type (3rd - level) `__ - in merchant's own product taxonomy. Segment. - - This field is a member of `oneof`_ ``_product_type_l3``. - product_type_l4 (str): - `Product type (4th - level) `__ - in merchant's own product taxonomy. Segment. - - This field is a member of `oneof`_ ``_product_type_l4``. - product_type_l5 (str): - `Product type (5th - level) `__ - in merchant's own product taxonomy. Segment. - - This field is a member of `oneof`_ ``_product_type_l5``. - custom_label0 (str): - Custom label 0 for custom grouping of - products. Segment. - - This field is a member of `oneof`_ ``_custom_label0``. - custom_label1 (str): - Custom label 1 for custom grouping of - products. Segment. - - This field is a member of `oneof`_ ``_custom_label1``. - custom_label2 (str): - Custom label 2 for custom grouping of - products. Segment. - - This field is a member of `oneof`_ ``_custom_label2``. - custom_label3 (str): - Custom label 3 for custom grouping of - products. Segment. - - This field is a member of `oneof`_ ``_custom_label3``. - custom_label4 (str): - Custom label 4 for custom grouping of - products. Segment. - - This field is a member of `oneof`_ ``_custom_label4``. - clicks (int): - Number of clicks. Metric. - - This field is a member of `oneof`_ ``_clicks``. - impressions (int): - Number of times merchant's products are - shown. Metric. - - This field is a member of `oneof`_ ``_impressions``. - click_through_rate (float): - Click-through rate - the number of clicks - merchant's products receive (clicks) divided by - the number of times the products are shown - (impressions). Metric. - - This field is a member of `oneof`_ ``_click_through_rate``. - conversions (float): - Number of conversions attributed to the product, reported on - the conversion date. Depending on the attribution model, a - conversion might be distributed across multiple clicks, - where each click gets its own credit assigned. This metric - is a sum of all such credits. Metric. - - Available only for the ``FREE`` traffic source. - - This field is a member of `oneof`_ ``_conversions``. - conversion_value (google.shopping.type.types.Price): - Value of conversions attributed to the product, reported on - the conversion date. Metric. - - Available only for the ``FREE`` traffic source. - conversion_rate (float): - Number of conversions divided by the number of clicks, - reported on the impression date. Metric. - - Available only for the ``FREE`` traffic source. - - This field is a member of `oneof`_ ``_conversion_rate``. - """ - - marketing_method: 'MarketingMethod.MarketingMethodEnum' = proto.Field( - proto.ENUM, - number=1, - optional=True, - enum='MarketingMethod.MarketingMethodEnum', - ) - date: date_pb2.Date = proto.Field( - proto.MESSAGE, - number=2, - message=date_pb2.Date, - ) - week: date_pb2.Date = proto.Field( - proto.MESSAGE, - number=3, - message=date_pb2.Date, - ) - customer_country_code: str = proto.Field( - proto.STRING, - number=4, - optional=True, - ) - offer_id: str = proto.Field( - proto.STRING, - number=5, - optional=True, - ) - title: str = proto.Field( - proto.STRING, - number=6, - optional=True, - ) - brand: str = proto.Field( - proto.STRING, - number=7, - optional=True, - ) - category_l1: str = proto.Field( - proto.STRING, - number=8, - optional=True, - ) - category_l2: str = proto.Field( - proto.STRING, - number=9, - optional=True, - ) - category_l3: str = proto.Field( - proto.STRING, - number=10, - optional=True, - ) - category_l4: str = proto.Field( - proto.STRING, - number=11, - optional=True, - ) - category_l5: str = proto.Field( - proto.STRING, - number=12, - optional=True, - ) - product_type_l1: str = proto.Field( - proto.STRING, - number=13, - optional=True, - ) - product_type_l2: str = proto.Field( - proto.STRING, - number=14, - optional=True, - ) - product_type_l3: str = proto.Field( - proto.STRING, - number=15, - optional=True, - ) - product_type_l4: str = proto.Field( - proto.STRING, - number=16, - optional=True, - ) - product_type_l5: str = proto.Field( - proto.STRING, - number=17, - optional=True, - ) - custom_label0: str = proto.Field( - proto.STRING, - number=18, - optional=True, - ) - custom_label1: str = proto.Field( - proto.STRING, - number=19, - optional=True, - ) - custom_label2: str = proto.Field( - proto.STRING, - number=20, - optional=True, - ) - custom_label3: str = proto.Field( - proto.STRING, - number=21, - optional=True, - ) - custom_label4: str = proto.Field( - proto.STRING, - number=22, - optional=True, - ) - clicks: int = proto.Field( - proto.INT64, - number=23, - optional=True, - ) - impressions: int = proto.Field( - proto.INT64, - number=24, - optional=True, - ) - click_through_rate: float = proto.Field( - proto.DOUBLE, - number=25, - optional=True, - ) - conversions: float = proto.Field( - proto.DOUBLE, - number=26, - optional=True, - ) - conversion_value: types.Price = proto.Field( - proto.MESSAGE, - number=27, - message=types.Price, - ) - conversion_rate: float = proto.Field( - proto.DOUBLE, - number=28, - optional=True, - ) - - -class ProductView(proto.Message): - r"""Fields available for query in ``product_view`` table. - - Products in the current inventory. Products in this table are the - same as in Products sub-API but not all product attributes from - Products sub-API are available for query in this table. In contrast - to Products sub-API, this table allows to filter the returned list - of products by product attributes. To retrieve a single product by - ``id`` or list all products, Products sub-API should be used. - - Values are only set for fields requested explicitly in the request's - search query. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - id (str): - REST ID of the product, in the form of - ``channel~languageCode~feedLabel~offerId``. Merchant API - methods that operate on products take this as their ``name`` - parameter. - - Required in the ``SELECT`` clause. - - This field is a member of `oneof`_ ``_id``. - channel (google.shopping.type.types.Channel.ChannelEnum): - Channel of the product. Can be ``ONLINE`` or ``LOCAL``. - - This field is a member of `oneof`_ ``_channel``. - language_code (str): - Language code of the product in BCP 47 - format. - - This field is a member of `oneof`_ ``_language_code``. - feed_label (str): - Feed label of the product. - - This field is a member of `oneof`_ ``_feed_label``. - offer_id (str): - Merchant-provided id of the product. - - This field is a member of `oneof`_ ``_offer_id``. - title (str): - Title of the product. - - This field is a member of `oneof`_ ``_title``. - brand (str): - Brand of the product. - - This field is a member of `oneof`_ ``_brand``. - category_l1 (str): - Product category (1st level) in `Google's product - taxonomy `__. - - This field is a member of `oneof`_ ``_category_l1``. - category_l2 (str): - Product category (2nd level) in `Google's product - taxonomy `__. - - This field is a member of `oneof`_ ``_category_l2``. - category_l3 (str): - Product category (3rd level) in `Google's product - taxonomy `__. - - This field is a member of `oneof`_ ``_category_l3``. - category_l4 (str): - Product category (4th level) in `Google's product - taxonomy `__. - - This field is a member of `oneof`_ ``_category_l4``. - category_l5 (str): - Product category (5th level) in `Google's product - taxonomy `__. - - This field is a member of `oneof`_ ``_category_l5``. - product_type_l1 (str): - Product type (1st level) in merchant's own `product - taxonomy `__. - - This field is a member of `oneof`_ ``_product_type_l1``. - product_type_l2 (str): - Product type (2nd level) in merchant's own `product - taxonomy `__. - - This field is a member of `oneof`_ ``_product_type_l2``. - product_type_l3 (str): - Product type (3rd level) in merchant's own `product - taxonomy `__. - - This field is a member of `oneof`_ ``_product_type_l3``. - product_type_l4 (str): - Product type (4th level) in merchant's own `product - taxonomy `__. - - This field is a member of `oneof`_ ``_product_type_l4``. - product_type_l5 (str): - Product type (5th level) in merchant's own `product - taxonomy `__. - - This field is a member of `oneof`_ ``_product_type_l5``. - price (google.shopping.type.types.Price): - Product price. Absent if the information - about the price of the product is not available. - condition (str): - `Condition `__ - of the product. - - This field is a member of `oneof`_ ``_condition``. - availability (str): - `Availability `__ - of the product. - - This field is a member of `oneof`_ ``_availability``. - shipping_label (str): - Normalized `shipping - label `__ - specified in the data source. - - This field is a member of `oneof`_ ``_shipping_label``. - gtin (MutableSequence[str]): - List of Global Trade Item Numbers (GTINs) of - the product. - item_group_id (str): - Item group id provided by the merchant for - grouping variants together. - - This field is a member of `oneof`_ ``_item_group_id``. - thumbnail_link (str): - Link to the processed image of the product, - hosted on the Google infrastructure. - - This field is a member of `oneof`_ ``_thumbnail_link``. - creation_time (google.protobuf.timestamp_pb2.Timestamp): - The time the merchant created the product in - timestamp seconds. - expiration_date (google.type.date_pb2.Date): - Expiration date for the product, specified on - insertion. - aggregated_reporting_context_status (google.shopping.merchant_reports_v1beta.types.ProductView.AggregatedReportingContextStatus): - Aggregated status. - - This field is a member of `oneof`_ ``_aggregated_reporting_context_status``. - item_issues (MutableSequence[google.shopping.merchant_reports_v1beta.types.ProductView.ItemIssue]): - List of item issues for the product. - - **This field cannot be used for sorting the results.** - - **Only selected attributes of this field (for example, - ``item_issues.severity.aggregated_severity``) can be used - for filtering the results.** - click_potential (google.shopping.merchant_reports_v1beta.types.ProductView.ClickPotential): - Estimated performance potential compared to - highest performing products of the merchant. - click_potential_rank (int): - Rank of the product based on its click potential. A product - with ``click_potential_rank`` 1 has the highest click - potential among the merchant's products that fulfill the - search query conditions. - - This field is a member of `oneof`_ ``_click_potential_rank``. - """ - class AggregatedReportingContextStatus(proto.Enum): - r"""Status of the product aggregated for all reporting contexts. - - Here's an example of how the aggregated status is computed: - - Free listings \| Shopping ads \| Status - --------------|--------------|------------------------------ - Approved \| Approved \| ELIGIBLE Approved \| Pending \| ELIGIBLE - Approved \| Disapproved \| ELIGIBLE_LIMITED Pending \| Pending \| - PENDING Disapproved \| Disapproved \| NOT_ELIGIBLE_OR_DISAPPROVED - - Values: - AGGREGATED_REPORTING_CONTEXT_STATUS_UNSPECIFIED (0): - Not specified. - NOT_ELIGIBLE_OR_DISAPPROVED (1): - Product is not eligible or is disapproved for - all reporting contexts. - PENDING (2): - Product's status is pending in all reporting - contexts. - ELIGIBLE_LIMITED (3): - Product is eligible for some (but not all) - reporting contexts. - ELIGIBLE (4): - Product is eligible for all reporting - contexts. - """ - AGGREGATED_REPORTING_CONTEXT_STATUS_UNSPECIFIED = 0 - NOT_ELIGIBLE_OR_DISAPPROVED = 1 - PENDING = 2 - ELIGIBLE_LIMITED = 3 - ELIGIBLE = 4 - - class ClickPotential(proto.Enum): - r"""A product's `click - potential `__ - estimates its performance potential compared to highest performing - products of the merchant. Click potential of a product helps - merchants to prioritize which products to fix and helps them - understand how products are performing against their potential. - - Values: - CLICK_POTENTIAL_UNSPECIFIED (0): - Unknown predicted clicks impact. - LOW (1): - Potential to receive a low number of clicks - compared to the highest performing products of - the merchant. - MEDIUM (2): - Potential to receive a moderate number of - clicks compared to the highest performing - products of the merchant. - HIGH (3): - Potential to receive a similar number of - clicks as the highest performing products of the - merchant. - """ - CLICK_POTENTIAL_UNSPECIFIED = 0 - LOW = 1 - MEDIUM = 2 - HIGH = 3 - - class ItemIssue(proto.Message): - r"""Item issue associated with the product. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - type_ (google.shopping.merchant_reports_v1beta.types.ProductView.ItemIssue.ItemIssueType): - Item issue type. - severity (google.shopping.merchant_reports_v1beta.types.ProductView.ItemIssue.ItemIssueSeverity): - Item issue severity. - resolution (google.shopping.merchant_reports_v1beta.types.ProductView.ItemIssue.ItemIssueResolution): - Item issue resolution. - - This field is a member of `oneof`_ ``_resolution``. - """ - class ItemIssueResolution(proto.Enum): - r"""How to resolve the issue. - - Values: - ITEM_ISSUE_RESOLUTION_UNSPECIFIED (0): - Not specified. - MERCHANT_ACTION (1): - The merchant has to fix the issue. - PENDING_PROCESSING (2): - The issue will be resolved automatically (for - example, image crawl) or through a Google - review. No merchant action is required now. - Resolution might lead to another issue (for - example, if crawl fails). - """ - ITEM_ISSUE_RESOLUTION_UNSPECIFIED = 0 - MERCHANT_ACTION = 1 - PENDING_PROCESSING = 2 - - class ItemIssueType(proto.Message): - r"""Issue type. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - code (str): - Error code of the issue, equivalent to the ``code`` of - `Product - issues `__. - - This field is a member of `oneof`_ ``_code``. - canonical_attribute (str): - Canonical attribute name for - attribute-specific issues. - - This field is a member of `oneof`_ ``_canonical_attribute``. - """ - - code: str = proto.Field( - proto.STRING, - number=1, - optional=True, - ) - canonical_attribute: str = proto.Field( - proto.STRING, - number=2, - optional=True, - ) - - class ItemIssueSeverity(proto.Message): - r"""How the issue affects the serving of the product. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - severity_per_reporting_context (MutableSequence[google.shopping.merchant_reports_v1beta.types.ProductView.ItemIssue.ItemIssueSeverity.IssueSeverityPerReportingContext]): - Issue severity per reporting context. - aggregated_severity (google.shopping.merchant_reports_v1beta.types.ProductView.ItemIssue.ItemIssueSeverity.AggregatedIssueSeverity): - Aggregated severity of the issue for all reporting contexts - it affects. - - **This field can be used for filtering the results.** - - This field is a member of `oneof`_ ``_aggregated_severity``. - """ - class AggregatedIssueSeverity(proto.Enum): - r"""Issue severity aggregated for all reporting contexts. - - Values: - AGGREGATED_ISSUE_SEVERITY_UNSPECIFIED (0): - Not specified. - DISAPPROVED (1): - Issue disapproves the product in at least one - reporting context. - DEMOTED (2): - Issue demotes the product in all reporting - contexts it affects. - PENDING (3): - Issue resolution is ``PENDING_PROCESSING``. - """ - AGGREGATED_ISSUE_SEVERITY_UNSPECIFIED = 0 - DISAPPROVED = 1 - DEMOTED = 2 - PENDING = 3 - - class IssueSeverityPerReportingContext(proto.Message): - r"""Issue severity per reporting context. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - reporting_context (google.shopping.type.types.ReportingContext.ReportingContextEnum): - Reporting context the issue applies to. - - This field is a member of `oneof`_ ``_reporting_context``. - disapproved_countries (MutableSequence[str]): - List of disapproved countries in the - reporting context, represented in ISO 3166 - format. - demoted_countries (MutableSequence[str]): - List of demoted countries in the reporting - context, represented in ISO 3166 format. - """ - - reporting_context: types.ReportingContext.ReportingContextEnum = proto.Field( - proto.ENUM, - number=1, - optional=True, - enum=types.ReportingContext.ReportingContextEnum, - ) - disapproved_countries: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - demoted_countries: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - severity_per_reporting_context: MutableSequence['ProductView.ItemIssue.ItemIssueSeverity.IssueSeverityPerReportingContext'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ProductView.ItemIssue.ItemIssueSeverity.IssueSeverityPerReportingContext', - ) - aggregated_severity: 'ProductView.ItemIssue.ItemIssueSeverity.AggregatedIssueSeverity' = proto.Field( - proto.ENUM, - number=2, - optional=True, - enum='ProductView.ItemIssue.ItemIssueSeverity.AggregatedIssueSeverity', - ) - - type_: 'ProductView.ItemIssue.ItemIssueType' = proto.Field( - proto.MESSAGE, - number=1, - message='ProductView.ItemIssue.ItemIssueType', - ) - severity: 'ProductView.ItemIssue.ItemIssueSeverity' = proto.Field( - proto.MESSAGE, - number=2, - message='ProductView.ItemIssue.ItemIssueSeverity', - ) - resolution: 'ProductView.ItemIssue.ItemIssueResolution' = proto.Field( - proto.ENUM, - number=3, - optional=True, - enum='ProductView.ItemIssue.ItemIssueResolution', - ) - - id: str = proto.Field( - proto.STRING, - number=1, - optional=True, - ) - channel: types.Channel.ChannelEnum = proto.Field( - proto.ENUM, - number=28, - optional=True, - enum=types.Channel.ChannelEnum, - ) - language_code: str = proto.Field( - proto.STRING, - number=2, - optional=True, - ) - feed_label: str = proto.Field( - proto.STRING, - number=3, - optional=True, - ) - offer_id: str = proto.Field( - proto.STRING, - number=4, - optional=True, - ) - title: str = proto.Field( - proto.STRING, - number=5, - optional=True, - ) - brand: str = proto.Field( - proto.STRING, - number=6, - optional=True, - ) - category_l1: str = proto.Field( - proto.STRING, - number=7, - optional=True, - ) - category_l2: str = proto.Field( - proto.STRING, - number=8, - optional=True, - ) - category_l3: str = proto.Field( - proto.STRING, - number=9, - optional=True, - ) - category_l4: str = proto.Field( - proto.STRING, - number=10, - optional=True, - ) - category_l5: str = proto.Field( - proto.STRING, - number=11, - optional=True, - ) - product_type_l1: str = proto.Field( - proto.STRING, - number=12, - optional=True, - ) - product_type_l2: str = proto.Field( - proto.STRING, - number=13, - optional=True, - ) - product_type_l3: str = proto.Field( - proto.STRING, - number=14, - optional=True, - ) - product_type_l4: str = proto.Field( - proto.STRING, - number=15, - optional=True, - ) - product_type_l5: str = proto.Field( - proto.STRING, - number=16, - optional=True, - ) - price: types.Price = proto.Field( - proto.MESSAGE, - number=17, - message=types.Price, - ) - condition: str = proto.Field( - proto.STRING, - number=18, - optional=True, - ) - availability: str = proto.Field( - proto.STRING, - number=19, - optional=True, - ) - shipping_label: str = proto.Field( - proto.STRING, - number=20, - optional=True, - ) - gtin: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=21, - ) - item_group_id: str = proto.Field( - proto.STRING, - number=22, - optional=True, - ) - thumbnail_link: str = proto.Field( - proto.STRING, - number=23, - optional=True, - ) - creation_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=24, - message=timestamp_pb2.Timestamp, - ) - expiration_date: date_pb2.Date = proto.Field( - proto.MESSAGE, - number=25, - message=date_pb2.Date, - ) - aggregated_reporting_context_status: AggregatedReportingContextStatus = proto.Field( - proto.ENUM, - number=26, - optional=True, - enum=AggregatedReportingContextStatus, - ) - item_issues: MutableSequence[ItemIssue] = proto.RepeatedField( - proto.MESSAGE, - number=27, - message=ItemIssue, - ) - click_potential: ClickPotential = proto.Field( - proto.ENUM, - number=29, - enum=ClickPotential, - ) - click_potential_rank: int = proto.Field( - proto.INT64, - number=30, - optional=True, - ) - - -class PriceCompetitivenessProductView(proto.Message): - r"""Fields available for query in ``price_competitiveness_product_view`` - table. - - `Price - competitiveness `__ - report. - - Values are only set for fields requested explicitly in the request's - search query. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - report_country_code (str): - Country of the price benchmark. Represented in the ISO 3166 - format. - - Required in the ``SELECT`` clause. - - This field is a member of `oneof`_ ``_report_country_code``. - id (str): - REST ID of the product, in the form of - ``channel~languageCode~feedLabel~offerId``. Can be used to - join data with the ``product_view`` table. - - Required in the ``SELECT`` clause. - - This field is a member of `oneof`_ ``_id``. - offer_id (str): - Merchant-provided id of the product. - - This field is a member of `oneof`_ ``_offer_id``. - title (str): - Title of the product. - - This field is a member of `oneof`_ ``_title``. - brand (str): - Brand of the product. - - This field is a member of `oneof`_ ``_brand``. - category_l1 (str): - Product category (1st level) in `Google's product - taxonomy `__. - - This field is a member of `oneof`_ ``_category_l1``. - category_l2 (str): - Product category (2nd level) in `Google's product - taxonomy `__. - - This field is a member of `oneof`_ ``_category_l2``. - category_l3 (str): - Product category (3rd level) in `Google's product - taxonomy `__. - - This field is a member of `oneof`_ ``_category_l3``. - category_l4 (str): - Product category (4th level) in `Google's product - taxonomy `__. - - This field is a member of `oneof`_ ``_category_l4``. - category_l5 (str): - Product category (5th level) in `Google's product - taxonomy `__. - - This field is a member of `oneof`_ ``_category_l5``. - product_type_l1 (str): - Product type (1st level) in merchant's own `product - taxonomy `__. - - This field is a member of `oneof`_ ``_product_type_l1``. - product_type_l2 (str): - Product type (2nd level) in merchant's own `product - taxonomy `__. - - This field is a member of `oneof`_ ``_product_type_l2``. - product_type_l3 (str): - Product type (3rd level) in merchant's own `product - taxonomy `__. - - This field is a member of `oneof`_ ``_product_type_l3``. - product_type_l4 (str): - Product type (4th level) in merchant's own `product - taxonomy `__. - - This field is a member of `oneof`_ ``_product_type_l4``. - product_type_l5 (str): - Product type (5th level) in merchant's own `product - taxonomy `__. - - This field is a member of `oneof`_ ``_product_type_l5``. - price (google.shopping.type.types.Price): - Current price of the product. - benchmark_price (google.shopping.type.types.Price): - Latest available price benchmark for the - product's catalog in the benchmark country. - """ - - report_country_code: str = proto.Field( - proto.STRING, - number=1, - optional=True, - ) - id: str = proto.Field( - proto.STRING, - number=2, - optional=True, - ) - offer_id: str = proto.Field( - proto.STRING, - number=3, - optional=True, - ) - title: str = proto.Field( - proto.STRING, - number=4, - optional=True, - ) - brand: str = proto.Field( - proto.STRING, - number=5, - optional=True, - ) - category_l1: str = proto.Field( - proto.STRING, - number=6, - optional=True, - ) - category_l2: str = proto.Field( - proto.STRING, - number=7, - optional=True, - ) - category_l3: str = proto.Field( - proto.STRING, - number=8, - optional=True, - ) - category_l4: str = proto.Field( - proto.STRING, - number=9, - optional=True, - ) - category_l5: str = proto.Field( - proto.STRING, - number=10, - optional=True, - ) - product_type_l1: str = proto.Field( - proto.STRING, - number=11, - optional=True, - ) - product_type_l2: str = proto.Field( - proto.STRING, - number=12, - optional=True, - ) - product_type_l3: str = proto.Field( - proto.STRING, - number=13, - optional=True, - ) - product_type_l4: str = proto.Field( - proto.STRING, - number=14, - optional=True, - ) - product_type_l5: str = proto.Field( - proto.STRING, - number=15, - optional=True, - ) - price: types.Price = proto.Field( - proto.MESSAGE, - number=16, - message=types.Price, - ) - benchmark_price: types.Price = proto.Field( - proto.MESSAGE, - number=17, - message=types.Price, - ) - - -class PriceInsightsProductView(proto.Message): - r"""Fields available for query in ``price_insights_product_view`` table. - - `Price - insights `__ - report. - - Values are only set for fields requested explicitly in the request's - search query. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - id (str): - REST ID of the product, in the form of - ``channel~languageCode~feedLabel~offerId``. Can be used to - join data with the ``product_view`` table. - - Required in the ``SELECT`` clause. - - This field is a member of `oneof`_ ``_id``. - offer_id (str): - Merchant-provided id of the product. - - This field is a member of `oneof`_ ``_offer_id``. - title (str): - Title of the product. - - This field is a member of `oneof`_ ``_title``. - brand (str): - Brand of the product. - - This field is a member of `oneof`_ ``_brand``. - category_l1 (str): - Product category (1st level) in `Google's product - taxonomy `__. - - This field is a member of `oneof`_ ``_category_l1``. - category_l2 (str): - Product category (2nd level) in `Google's product - taxonomy `__. - - This field is a member of `oneof`_ ``_category_l2``. - category_l3 (str): - Product category (3rd level) in `Google's product - taxonomy `__. - - This field is a member of `oneof`_ ``_category_l3``. - category_l4 (str): - Product category (4th level) in `Google's product - taxonomy `__. - - This field is a member of `oneof`_ ``_category_l4``. - category_l5 (str): - Product category (5th level) in `Google's product - taxonomy `__. - - This field is a member of `oneof`_ ``_category_l5``. - product_type_l1 (str): - Product type (1st level) in merchant's own `product - taxonomy `__. - - This field is a member of `oneof`_ ``_product_type_l1``. - product_type_l2 (str): - Product type (2nd level) in merchant's own `product - taxonomy `__. - - This field is a member of `oneof`_ ``_product_type_l2``. - product_type_l3 (str): - Product type (3rd level) in merchant's own `product - taxonomy `__. - - This field is a member of `oneof`_ ``_product_type_l3``. - product_type_l4 (str): - Product type (4th level) in merchant's own `product - taxonomy `__. - - This field is a member of `oneof`_ ``_product_type_l4``. - product_type_l5 (str): - Product type (5th level) in merchant's own `product - taxonomy `__. - - This field is a member of `oneof`_ ``_product_type_l5``. - price (google.shopping.type.types.Price): - Current price of the product. - suggested_price (google.shopping.type.types.Price): - Latest suggested price for the product. - predicted_impressions_change_fraction (float): - Predicted change in impressions as a fraction - after introducing the suggested price compared - to current active price. For example, 0.05 is a - 5% predicted increase in impressions. - - This field is a member of `oneof`_ ``_predicted_impressions_change_fraction``. - predicted_clicks_change_fraction (float): - Predicted change in clicks as a fraction - after introducing the suggested price compared - to current active price. For example, 0.05 is a - 5% predicted increase in clicks. - - This field is a member of `oneof`_ ``_predicted_clicks_change_fraction``. - predicted_conversions_change_fraction (float): - Predicted change in conversions as a fraction - after introducing the suggested price compared - to current active price. For example, 0.05 is a - 5% predicted increase in conversions). - - This field is a member of `oneof`_ ``_predicted_conversions_change_fraction``. - effectiveness (google.shopping.merchant_reports_v1beta.types.PriceInsightsProductView.Effectiveness): - The predicted effectiveness of applying the - price suggestion, bucketed. - """ - class Effectiveness(proto.Enum): - r"""Predicted effectiveness bucket. - - Effectiveness indicates which products would benefit most from price - changes. This rating takes into consideration the performance boost - predicted by adjusting the sale price and the difference between - your current price and the suggested price. Price suggestions with - ``HIGH`` effectiveness are predicted to drive the largest increase - in performance. - - Values: - EFFECTIVENESS_UNSPECIFIED (0): - Effectiveness is unknown. - LOW (1): - Effectiveness is low. - MEDIUM (2): - Effectiveness is medium. - HIGH (3): - Effectiveness is high. - """ - EFFECTIVENESS_UNSPECIFIED = 0 - LOW = 1 - MEDIUM = 2 - HIGH = 3 - - id: str = proto.Field( - proto.STRING, - number=1, - optional=True, - ) - offer_id: str = proto.Field( - proto.STRING, - number=2, - optional=True, - ) - title: str = proto.Field( - proto.STRING, - number=3, - optional=True, - ) - brand: str = proto.Field( - proto.STRING, - number=4, - optional=True, - ) - category_l1: str = proto.Field( - proto.STRING, - number=5, - optional=True, - ) - category_l2: str = proto.Field( - proto.STRING, - number=6, - optional=True, - ) - category_l3: str = proto.Field( - proto.STRING, - number=7, - optional=True, - ) - category_l4: str = proto.Field( - proto.STRING, - number=8, - optional=True, - ) - category_l5: str = proto.Field( - proto.STRING, - number=9, - optional=True, - ) - product_type_l1: str = proto.Field( - proto.STRING, - number=10, - optional=True, - ) - product_type_l2: str = proto.Field( - proto.STRING, - number=11, - optional=True, - ) - product_type_l3: str = proto.Field( - proto.STRING, - number=12, - optional=True, - ) - product_type_l4: str = proto.Field( - proto.STRING, - number=13, - optional=True, - ) - product_type_l5: str = proto.Field( - proto.STRING, - number=14, - optional=True, - ) - price: types.Price = proto.Field( - proto.MESSAGE, - number=15, - message=types.Price, - ) - suggested_price: types.Price = proto.Field( - proto.MESSAGE, - number=16, - message=types.Price, - ) - predicted_impressions_change_fraction: float = proto.Field( - proto.DOUBLE, - number=17, - optional=True, - ) - predicted_clicks_change_fraction: float = proto.Field( - proto.DOUBLE, - number=18, - optional=True, - ) - predicted_conversions_change_fraction: float = proto.Field( - proto.DOUBLE, - number=19, - optional=True, - ) - effectiveness: Effectiveness = proto.Field( - proto.ENUM, - number=22, - enum=Effectiveness, - ) - - -class BestSellersProductClusterView(proto.Message): - r"""Fields available for query in ``best_sellers_product_cluster_view`` - table. - - `Best - sellers `__ - report with top product clusters. A product cluster is a grouping - for different offers and variants that represent the same product, - for example, Google Pixel 7. - - Values are only set for fields requested explicitly in the request's - search query. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - report_date (google.type.date_pb2.Date): - Report date. The value of this field can only be one of the - following: - - - The first day of the week (Monday) for weekly reports, - - The first day of the month for monthly reports. - - Required in the ``SELECT`` clause. If a ``WHERE`` condition - on ``report_date`` is not specified in the query, the latest - available weekly or monthly report is returned. - report_granularity (google.shopping.merchant_reports_v1beta.types.ReportGranularity.ReportGranularityEnum): - Granularity of the report. The ranking can be done over a - week or a month timeframe. - - Required in the ``SELECT`` clause. Condition on - ``report_granularity`` is required in the ``WHERE`` clause. - - This field is a member of `oneof`_ ``_report_granularity``. - report_country_code (str): - Country where the ranking is calculated. Represented in the - ISO 3166 format. - - Required in the ``SELECT`` clause. Condition on - ``report_country_code`` is required in the ``WHERE`` clause. - - This field is a member of `oneof`_ ``_report_country_code``. - report_category_id (int): - Google product category ID to calculate the ranking for, - represented in `Google's product - taxonomy `__. - - Required in the ``SELECT`` clause. If a ``WHERE`` condition - on ``report_category_id`` is not specified in the query, - rankings for all top-level categories are returned. - - This field is a member of `oneof`_ ``_report_category_id``. - title (str): - Title of the product cluster. - - This field is a member of `oneof`_ ``_title``. - brand (str): - Brand of the product cluster. - - This field is a member of `oneof`_ ``_brand``. - category_l1 (str): - Product category (1st level) of the product cluster, - represented in `Google's product - taxonomy `__. - - This field is a member of `oneof`_ ``_category_l1``. - category_l2 (str): - Product category (2nd level) of the product cluster, - represented in `Google's product - taxonomy `__. - - This field is a member of `oneof`_ ``_category_l2``. - category_l3 (str): - Product category (3rd level) of the product cluster, - represented in `Google's product - taxonomy `__. - - This field is a member of `oneof`_ ``_category_l3``. - category_l4 (str): - Product category (4th level) of the product cluster, - represented in `Google's product - taxonomy `__. - - This field is a member of `oneof`_ ``_category_l4``. - category_l5 (str): - Product category (5th level) of the product cluster, - represented in `Google's product - taxonomy `__. - - This field is a member of `oneof`_ ``_category_l5``. - variant_gtins (MutableSequence[str]): - GTINs of example variants of the product - cluster. - inventory_status (google.shopping.merchant_reports_v1beta.types.BestSellersProductClusterView.InventoryStatus): - Whether the product cluster is ``IN_STOCK`` in your product - data source in at least one of the countries, - ``OUT_OF_STOCK`` in your product data source in all - countries, or ``NOT_IN_INVENTORY`` at all. - - The field doesn't take the Best sellers report country - filter into account. - - This field is a member of `oneof`_ ``_inventory_status``. - brand_inventory_status (google.shopping.merchant_reports_v1beta.types.BestSellersProductClusterView.InventoryStatus): - Whether there is at least one product of the brand currently - ``IN_STOCK`` in your product data source in at least one of - the countries, all products are ``OUT_OF_STOCK`` in your - product data source in all countries, or - ``NOT_IN_INVENTORY``. - - The field doesn't take the Best sellers report country - filter into account. - - This field is a member of `oneof`_ ``_brand_inventory_status``. - rank (int): - Popularity of the product cluster on Ads and - organic surfaces, in the selected category and - country, based on the estimated number of units - sold. - - This field is a member of `oneof`_ ``_rank``. - previous_rank (int): - Popularity rank in the previous week or - month. - - This field is a member of `oneof`_ ``_previous_rank``. - relative_demand (google.shopping.merchant_reports_v1beta.types.RelativeDemand.RelativeDemandEnum): - Estimated demand in relation to the product - cluster with the highest popularity rank in the - same category and country. - - This field is a member of `oneof`_ ``_relative_demand``. - previous_relative_demand (google.shopping.merchant_reports_v1beta.types.RelativeDemand.RelativeDemandEnum): - Estimated demand in relation to the product - cluster with the highest popularity rank in the - same category and country in the previous week - or month. - - This field is a member of `oneof`_ ``_previous_relative_demand``. - relative_demand_change (google.shopping.merchant_reports_v1beta.types.RelativeDemandChangeType.RelativeDemandChangeTypeEnum): - Change in the estimated demand. Whether it - rose, sank or remained flat. - - This field is a member of `oneof`_ ``_relative_demand_change``. - """ - class InventoryStatus(proto.Enum): - r"""Status of the product cluster or brand in your inventory. - - Values: - INVENTORY_STATUS_UNSPECIFIED (0): - Not specified. - IN_STOCK (1): - You have a product for this product cluster - or brand in stock. - OUT_OF_STOCK (2): - You have a product for this product cluster - or brand in inventory but it is currently out of - stock. - NOT_IN_INVENTORY (3): - You do not have a product for this product - cluster or brand in inventory. - """ - INVENTORY_STATUS_UNSPECIFIED = 0 - IN_STOCK = 1 - OUT_OF_STOCK = 2 - NOT_IN_INVENTORY = 3 - - report_date: date_pb2.Date = proto.Field( - proto.MESSAGE, - number=1, - message=date_pb2.Date, - ) - report_granularity: 'ReportGranularity.ReportGranularityEnum' = proto.Field( - proto.ENUM, - number=2, - optional=True, - enum='ReportGranularity.ReportGranularityEnum', - ) - report_country_code: str = proto.Field( - proto.STRING, - number=3, - optional=True, - ) - report_category_id: int = proto.Field( - proto.INT64, - number=4, - optional=True, - ) - title: str = proto.Field( - proto.STRING, - number=6, - optional=True, - ) - brand: str = proto.Field( - proto.STRING, - number=7, - optional=True, - ) - category_l1: str = proto.Field( - proto.STRING, - number=8, - optional=True, - ) - category_l2: str = proto.Field( - proto.STRING, - number=9, - optional=True, - ) - category_l3: str = proto.Field( - proto.STRING, - number=10, - optional=True, - ) - category_l4: str = proto.Field( - proto.STRING, - number=11, - optional=True, - ) - category_l5: str = proto.Field( - proto.STRING, - number=12, - optional=True, - ) - variant_gtins: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=13, - ) - inventory_status: InventoryStatus = proto.Field( - proto.ENUM, - number=14, - optional=True, - enum=InventoryStatus, - ) - brand_inventory_status: InventoryStatus = proto.Field( - proto.ENUM, - number=15, - optional=True, - enum=InventoryStatus, - ) - rank: int = proto.Field( - proto.INT64, - number=16, - optional=True, - ) - previous_rank: int = proto.Field( - proto.INT64, - number=17, - optional=True, - ) - relative_demand: 'RelativeDemand.RelativeDemandEnum' = proto.Field( - proto.ENUM, - number=18, - optional=True, - enum='RelativeDemand.RelativeDemandEnum', - ) - previous_relative_demand: 'RelativeDemand.RelativeDemandEnum' = proto.Field( - proto.ENUM, - number=19, - optional=True, - enum='RelativeDemand.RelativeDemandEnum', - ) - relative_demand_change: 'RelativeDemandChangeType.RelativeDemandChangeTypeEnum' = proto.Field( - proto.ENUM, - number=20, - optional=True, - enum='RelativeDemandChangeType.RelativeDemandChangeTypeEnum', - ) - - -class BestSellersBrandView(proto.Message): - r"""Fields available for query in ``best_sellers_brand_view`` table. - - `Best - sellers `__ - report with top brands. - - Values are only set for fields requested explicitly in the request's - search query. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - report_date (google.type.date_pb2.Date): - Report date. The value of this field can only be one of the - following: - - - The first day of the week (Monday) for weekly reports, - - The first day of the month for monthly reports. - - Required in the ``SELECT`` clause. If a ``WHERE`` condition - on ``report_date`` is not specified in the query, the latest - available weekly or monthly report is returned. - report_granularity (google.shopping.merchant_reports_v1beta.types.ReportGranularity.ReportGranularityEnum): - Granularity of the report. The ranking can be done over a - week or a month timeframe. - - Required in the ``SELECT`` clause. Condition on - ``report_granularity`` is required in the ``WHERE`` clause. - - This field is a member of `oneof`_ ``_report_granularity``. - report_country_code (str): - Country where the ranking is calculated. Represented in the - ISO 3166 format. - - Required in the ``SELECT`` clause. Condition on - ``report_country_code`` is required in the ``WHERE`` clause. - - This field is a member of `oneof`_ ``_report_country_code``. - report_category_id (int): - Google product category ID to calculate the ranking for, - represented in `Google's product - taxonomy `__. - - Required in the ``SELECT`` clause. If a ``WHERE`` condition - on ``report_category_id`` is not specified in the query, - rankings for all top-level categories are returned. - - This field is a member of `oneof`_ ``_report_category_id``. - brand (str): - Name of the brand. - - This field is a member of `oneof`_ ``_brand``. - rank (int): - Popularity of the brand on Ads and organic - surfaces, in the selected category and country, - based on the estimated number of units sold. - - This field is a member of `oneof`_ ``_rank``. - previous_rank (int): - Popularity rank in the previous week or - month. - - This field is a member of `oneof`_ ``_previous_rank``. - relative_demand (google.shopping.merchant_reports_v1beta.types.RelativeDemand.RelativeDemandEnum): - Estimated demand in relation to the brand - with the highest popularity rank in the same - category and country. - - This field is a member of `oneof`_ ``_relative_demand``. - previous_relative_demand (google.shopping.merchant_reports_v1beta.types.RelativeDemand.RelativeDemandEnum): - Estimated demand in relation to the brand - with the highest popularity rank in the same - category and country in the previous week or - month. - - This field is a member of `oneof`_ ``_previous_relative_demand``. - relative_demand_change (google.shopping.merchant_reports_v1beta.types.RelativeDemandChangeType.RelativeDemandChangeTypeEnum): - Change in the estimated demand. Whether it - rose, sank or remained flat. - - This field is a member of `oneof`_ ``_relative_demand_change``. - """ - - report_date: date_pb2.Date = proto.Field( - proto.MESSAGE, - number=1, - message=date_pb2.Date, - ) - report_granularity: 'ReportGranularity.ReportGranularityEnum' = proto.Field( - proto.ENUM, - number=2, - optional=True, - enum='ReportGranularity.ReportGranularityEnum', - ) - report_country_code: str = proto.Field( - proto.STRING, - number=3, - optional=True, - ) - report_category_id: int = proto.Field( - proto.INT64, - number=4, - optional=True, - ) - brand: str = proto.Field( - proto.STRING, - number=6, - optional=True, - ) - rank: int = proto.Field( - proto.INT64, - number=7, - optional=True, - ) - previous_rank: int = proto.Field( - proto.INT64, - number=8, - optional=True, - ) - relative_demand: 'RelativeDemand.RelativeDemandEnum' = proto.Field( - proto.ENUM, - number=9, - optional=True, - enum='RelativeDemand.RelativeDemandEnum', - ) - previous_relative_demand: 'RelativeDemand.RelativeDemandEnum' = proto.Field( - proto.ENUM, - number=10, - optional=True, - enum='RelativeDemand.RelativeDemandEnum', - ) - relative_demand_change: 'RelativeDemandChangeType.RelativeDemandChangeTypeEnum' = proto.Field( - proto.ENUM, - number=11, - optional=True, - enum='RelativeDemandChangeType.RelativeDemandChangeTypeEnum', - ) - - -class NonProductPerformanceView(proto.Message): - r"""Fields available for query in ``non_product_performance_view`` - table. - - Performance data on images and online store links leading to your - non-product pages. This includes performance metrics (for example, - ``clicks``) and dimensions according to which performance metrics - are segmented (for example, ``date``). - - Segment fields cannot be selected in queries without also selecting - at least one metric field. - - Values are only set for fields requested explicitly in the request's - search query. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - date (google.type.date_pb2.Date): - Date in the merchant timezone to which metrics apply. - Segment. - - Condition on ``date`` is required in the ``WHERE`` clause. - week (google.type.date_pb2.Date): - First day of the week (Monday) of the metrics - date in the merchant timezone. Segment. - clicks (int): - Number of clicks on images and online store - links leading to your non-product pages. Metric. - - This field is a member of `oneof`_ ``_clicks``. - impressions (int): - Number of times images and online store links - leading to your non-product pages were shown. - Metric. - - This field is a member of `oneof`_ ``_impressions``. - click_through_rate (float): - Click-through rate - the number of clicks (``clicks``) - divided by the number of impressions (``impressions``) of - images and online store links leading to your non-product - pages. Metric. - - This field is a member of `oneof`_ ``_click_through_rate``. - """ - - date: date_pb2.Date = proto.Field( - proto.MESSAGE, - number=1, - message=date_pb2.Date, - ) - week: date_pb2.Date = proto.Field( - proto.MESSAGE, - number=2, - message=date_pb2.Date, - ) - clicks: int = proto.Field( - proto.INT64, - number=3, - optional=True, - ) - impressions: int = proto.Field( - proto.INT64, - number=4, - optional=True, - ) - click_through_rate: float = proto.Field( - proto.DOUBLE, - number=5, - optional=True, - ) - - -class CompetitiveVisibilityCompetitorView(proto.Message): - r"""Fields available for query in - ``competitive_visibility_competitor_view`` table. - - `Competitive - visibility `__ - report with businesses with similar visibility. - - Values are only set for fields requested explicitly in the request's - search query. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - date (google.type.date_pb2.Date): - Date of this row. - - A condition on ``date`` is required in the ``WHERE`` clause. - domain (str): - Domain of your competitor or your domain, if - 'is_your_domain' is true. - - Required in the ``SELECT`` clause. Cannot be filtered on in - the 'WHERE' clause. - - This field is a member of `oneof`_ ``_domain``. - is_your_domain (bool): - True if this row contains data for your - domain. - Cannot be filtered on in the 'WHERE' clause. - - This field is a member of `oneof`_ ``_is_your_domain``. - report_country_code (str): - Country where impressions appeared. - - Required in the ``SELECT`` clause. A condition on - ``report_country_code`` is required in the ``WHERE`` clause. - - This field is a member of `oneof`_ ``_report_country_code``. - report_category_id (int): - Google product category ID to calculate the report for, - represented in `Google's product - taxonomy `__. - - Required in the ``SELECT`` clause. A condition on - ``report_category_id`` is required in the ``WHERE`` clause. - - This field is a member of `oneof`_ ``_report_category_id``. - traffic_source (google.shopping.merchant_reports_v1beta.types.TrafficSource.TrafficSourceEnum): - Traffic source of impressions. - - Required in the ``SELECT`` clause. - - This field is a member of `oneof`_ ``_traffic_source``. - rank (int): - Position of the domain in the similar businesses ranking for - the selected keys (``date``, ``report_category_id``, - ``report_country_code``, ``traffic_source``) based on - impressions. 1 is the highest. - - Cannot be filtered on in the 'WHERE' clause. - - This field is a member of `oneof`_ ``_rank``. - ads_organic_ratio (float): - [Ads / organic ratio] - (https://support.google.com/merchants/answer/11366442#zippy=%2Cads-free-ratio) - shows how often the domain receives impressions from - Shopping ads compared to organic traffic. The number is - rounded and bucketed. - - Cannot be filtered on in the 'WHERE' clause. - - This field is a member of `oneof`_ ``_ads_organic_ratio``. - page_overlap_rate (float): - [Page overlap rate] - (https://support.google.com/merchants/answer/11366442#zippy=%2Cpage-overlap-rate) - shows how frequently competing retailers’ offers are shown - together with your offers on the same page. - - Cannot be filtered on in the 'WHERE' clause. - - This field is a member of `oneof`_ ``_page_overlap_rate``. - higher_position_rate (float): - [Higher position rate] - (https://support.google.com/merchants/answer/11366442#zippy=%2Chigher-position-rate) - shows how often a competitor’s offer got placed in a higher - position on the page than your offer. - - Cannot be filtered on in the 'WHERE' clause. - - This field is a member of `oneof`_ ``_higher_position_rate``. - relative_visibility (float): - [Relative visibility] - (https://support.google.com/merchants/answer/11366442#zippy=%2Crelative-visibility) - shows how often your competitors’ offers are shown compared - to your offers. In other words, this is the number of - displayed impressions of a competitor retailer divided by - the number of your displayed impressions during a selected - time range for a selected product category and country. - - Cannot be filtered on in the 'WHERE' clause. - - This field is a member of `oneof`_ ``_relative_visibility``. - """ - - date: date_pb2.Date = proto.Field( - proto.MESSAGE, - number=1, - message=date_pb2.Date, - ) - domain: str = proto.Field( - proto.STRING, - number=2, - optional=True, - ) - is_your_domain: bool = proto.Field( - proto.BOOL, - number=3, - optional=True, - ) - report_country_code: str = proto.Field( - proto.STRING, - number=4, - optional=True, - ) - report_category_id: int = proto.Field( - proto.INT64, - number=5, - optional=True, - ) - traffic_source: 'TrafficSource.TrafficSourceEnum' = proto.Field( - proto.ENUM, - number=6, - optional=True, - enum='TrafficSource.TrafficSourceEnum', - ) - rank: int = proto.Field( - proto.INT64, - number=7, - optional=True, - ) - ads_organic_ratio: float = proto.Field( - proto.DOUBLE, - number=8, - optional=True, - ) - page_overlap_rate: float = proto.Field( - proto.DOUBLE, - number=9, - optional=True, - ) - higher_position_rate: float = proto.Field( - proto.DOUBLE, - number=10, - optional=True, - ) - relative_visibility: float = proto.Field( - proto.DOUBLE, - number=11, - optional=True, - ) - - -class CompetitiveVisibilityTopMerchantView(proto.Message): - r"""Fields available for query in - ``competitive_visibility_top_merchant_view`` table. - - `Competitive - visibility `__ - report with business with highest visibility. - - Values are only set for fields requested explicitly in the request's - search query. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - date (google.type.date_pb2.Date): - Date of this row. - - Cannot be selected in the ``SELECT`` clause. A condition on - ``date`` is required in the ``WHERE`` clause. - domain (str): - Domain of your competitor or your domain, if - 'is_your_domain' is true. - - Required in the ``SELECT`` clause. Cannot be filtered on in - the 'WHERE' clause. - - This field is a member of `oneof`_ ``_domain``. - is_your_domain (bool): - True if this row contains data for your - domain. - Cannot be filtered on in the 'WHERE' clause. - - This field is a member of `oneof`_ ``_is_your_domain``. - report_country_code (str): - Country where impressions appeared. - - Required in the ``SELECT`` clause. A condition on - ``report_country_code`` is required in the ``WHERE`` clause. - - This field is a member of `oneof`_ ``_report_country_code``. - report_category_id (int): - Google product category ID to calculate the report for, - represented in `Google's product - taxonomy `__. - - Required in the ``SELECT`` clause. A condition on - ``report_category_id`` is required in the ``WHERE`` clause. - - This field is a member of `oneof`_ ``_report_category_id``. - traffic_source (google.shopping.merchant_reports_v1beta.types.TrafficSource.TrafficSourceEnum): - Traffic source of impressions. - - Required in the ``SELECT`` clause. - - This field is a member of `oneof`_ ``_traffic_source``. - rank (int): - Position of the domain in the top merchants ranking for the - selected keys (``date``, ``report_category_id``, - ``report_country_code``, ``traffic_source``) based on - impressions. 1 is the highest. - - Cannot be filtered on in the 'WHERE' clause. - - This field is a member of `oneof`_ ``_rank``. - ads_organic_ratio (float): - [Ads / organic ratio] - (https://support.google.com/merchants/answer/11366442#zippy=%2Cads-free-ratio) - shows how often the domain receives impressions from - Shopping ads compared to organic traffic. The number is - rounded and bucketed. - - Cannot be filtered on in the 'WHERE' clause. - - This field is a member of `oneof`_ ``_ads_organic_ratio``. - page_overlap_rate (float): - [Page overlap rate] - (https://support.google.com/merchants/answer/11366442#zippy=%2Cpage-overlap-rate) - shows how frequently competing retailers’ offers are shown - together with your offers on the same page. - - Cannot be filtered on in the 'WHERE' clause. - - This field is a member of `oneof`_ ``_page_overlap_rate``. - higher_position_rate (float): - [Higher position rate] - (https://support.google.com/merchants/answer/11366442#zippy=%2Chigher-position-rate) - shows how often a competitor’s offer got placed in a higher - position on the page than your offer. - - Cannot be filtered on in the 'WHERE' clause. - - This field is a member of `oneof`_ ``_higher_position_rate``. - """ - - date: date_pb2.Date = proto.Field( - proto.MESSAGE, - number=1, - message=date_pb2.Date, - ) - domain: str = proto.Field( - proto.STRING, - number=2, - optional=True, - ) - is_your_domain: bool = proto.Field( - proto.BOOL, - number=3, - optional=True, - ) - report_country_code: str = proto.Field( - proto.STRING, - number=4, - optional=True, - ) - report_category_id: int = proto.Field( - proto.INT64, - number=5, - optional=True, - ) - traffic_source: 'TrafficSource.TrafficSourceEnum' = proto.Field( - proto.ENUM, - number=6, - optional=True, - enum='TrafficSource.TrafficSourceEnum', - ) - rank: int = proto.Field( - proto.INT64, - number=7, - optional=True, - ) - ads_organic_ratio: float = proto.Field( - proto.DOUBLE, - number=8, - optional=True, - ) - page_overlap_rate: float = proto.Field( - proto.DOUBLE, - number=9, - optional=True, - ) - higher_position_rate: float = proto.Field( - proto.DOUBLE, - number=10, - optional=True, - ) - - -class CompetitiveVisibilityBenchmarkView(proto.Message): - r"""Fields available for query in - ``competitive_visibility_benchmark_view`` table. - - `Competitive - visibility `__ - report with the category benchmark. - - Values are only set for fields requested explicitly in the request's - search query. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - date (google.type.date_pb2.Date): - Date of this row. - - Required in the ``SELECT`` clause. A condition on ``date`` - is required in the ``WHERE`` clause. - report_country_code (str): - Country where impressions appeared. - - Required in the ``SELECT`` clause. A condition on - ``report_country_code`` is required in the ``WHERE`` clause. - - This field is a member of `oneof`_ ``_report_country_code``. - report_category_id (int): - Google product category ID to calculate the report for, - represented in `Google's product - taxonomy `__. - - Required in the ``SELECT`` clause. A condition on - ``report_category_id`` is required in the ``WHERE`` clause. - - This field is a member of `oneof`_ ``_report_category_id``. - traffic_source (google.shopping.merchant_reports_v1beta.types.TrafficSource.TrafficSourceEnum): - Traffic source of impressions. - - Required in the ``SELECT`` clause. - - This field is a member of `oneof`_ ``_traffic_source``. - your_domain_visibility_trend (float): - Change in visibility based on impressions for - your domain with respect to the start of the - selected time range (or first day with non-zero - impressions). - - Cannot be filtered on in the 'WHERE' clause. - - This field is a member of `oneof`_ ``_your_domain_visibility_trend``. - category_benchmark_visibility_trend (float): - Change in visibility based on impressions - with respect to the start of the selected time - range (or first day with non-zero impressions) - for a combined set of merchants with highest - visibility approximating the market. - - Cannot be filtered on in the 'WHERE' clause. - - This field is a member of `oneof`_ ``_category_benchmark_visibility_trend``. - """ - - date: date_pb2.Date = proto.Field( - proto.MESSAGE, - number=1, - message=date_pb2.Date, - ) - report_country_code: str = proto.Field( - proto.STRING, - number=2, - optional=True, - ) - report_category_id: int = proto.Field( - proto.INT64, - number=3, - optional=True, - ) - traffic_source: 'TrafficSource.TrafficSourceEnum' = proto.Field( - proto.ENUM, - number=4, - optional=True, - enum='TrafficSource.TrafficSourceEnum', - ) - your_domain_visibility_trend: float = proto.Field( - proto.DOUBLE, - number=5, - optional=True, - ) - category_benchmark_visibility_trend: float = proto.Field( - proto.DOUBLE, - number=6, - optional=True, - ) - - -class MarketingMethod(proto.Message): - r"""Marketing method used to promote your products on Google - (organic versus ads). - - """ - class MarketingMethodEnum(proto.Enum): - r"""Marketing method values. - - Values: - MARKETING_METHOD_ENUM_UNSPECIFIED (0): - Not specified. - ORGANIC (1): - Organic marketing. - ADS (2): - Ads-based marketing. - """ - MARKETING_METHOD_ENUM_UNSPECIFIED = 0 - ORGANIC = 1 - ADS = 2 - - -class ReportGranularity(proto.Message): - r"""Granularity of the Best sellers report. Best sellers reports - are computed over a week and a month timeframe. - - """ - class ReportGranularityEnum(proto.Enum): - r"""Report granularity values. - - Values: - REPORT_GRANULARITY_ENUM_UNSPECIFIED (0): - Not specified. - WEEKLY (1): - Report is computed over a week timeframe. - MONTHLY (2): - Report is computed over a month timeframe. - """ - REPORT_GRANULARITY_ENUM_UNSPECIFIED = 0 - WEEKLY = 1 - MONTHLY = 2 - - -class RelativeDemand(proto.Message): - r"""Relative demand of a product cluster or brand in the Best - sellers report. - - """ - class RelativeDemandEnum(proto.Enum): - r"""Relative demand values. - - Values: - RELATIVE_DEMAND_ENUM_UNSPECIFIED (0): - Not specified. - VERY_LOW (10): - Demand is 0-5% of the demand of the highest - ranked product cluster or brand. - LOW (20): - Demand is 6-10% of the demand of the highest - ranked product cluster or brand. - MEDIUM (30): - Demand is 11-20% of the demand of the highest - ranked product cluster or brand. - HIGH (40): - Demand is 21-50% of the demand of the highest - ranked product cluster or brand. - VERY_HIGH (50): - Demand is 51-100% of the demand of the - highest ranked product cluster or brand. - """ - RELATIVE_DEMAND_ENUM_UNSPECIFIED = 0 - VERY_LOW = 10 - LOW = 20 - MEDIUM = 30 - HIGH = 40 - VERY_HIGH = 50 - - -class RelativeDemandChangeType(proto.Message): - r"""Relative demand of a product cluster or brand in the Best - sellers report compared to the previous time period. - - """ - class RelativeDemandChangeTypeEnum(proto.Enum): - r"""Relative demand change type values. - - Values: - RELATIVE_DEMAND_CHANGE_TYPE_ENUM_UNSPECIFIED (0): - Not specified. - SINKER (1): - Relative demand is lower than the previous - time period. - FLAT (2): - Relative demand is equal to the previous time - period. - RISER (3): - Relative demand is higher than the previous - time period. - """ - RELATIVE_DEMAND_CHANGE_TYPE_ENUM_UNSPECIFIED = 0 - SINKER = 1 - FLAT = 2 - RISER = 3 - - -class TrafficSource(proto.Message): - r"""Traffic source of impressions in the Competitive visibility - report. - - """ - class TrafficSourceEnum(proto.Enum): - r"""Traffic source values. - - Values: - TRAFFIC_SOURCE_ENUM_UNSPECIFIED (0): - Not specified. - ORGANIC (1): - Organic traffic. - ADS (2): - Traffic from ads. - ALL (3): - Organic and ads traffic. - """ - TRAFFIC_SOURCE_ENUM_UNSPECIFIED = 0 - ORGANIC = 1 - ADS = 2 - ALL = 3 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/mypy.ini b/owl-bot-staging/google-shopping-merchant-reports/v1beta/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/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-reports/v1beta/noxfile.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/noxfile.py deleted file mode 100644 index da7084b1cfb2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/v1beta/noxfile.py +++ /dev/null @@ -1,280 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", - "3.12", - "3.13", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = 'google-shopping-merchant-reports' - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.13" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "prerelease_deps", -] - -@nox.session(python=ALL_PYTHON) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def unit(session, protobuf_implementation): - """Run the unit test suite.""" - - 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+") - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") - - # 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") - - session.run( - 'py.test', - '--quiet', - '--cov=google/shopping/merchant_reports_v1beta/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - -@nox.session(python=ALL_PYTHON[-1]) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def prerelease_deps(session, protobuf_implementation): - """Run the unit test suite against pre-release versions of dependencies.""" - - 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 test environment dependencies - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - - # Install the package without dependencies - session.install('-e', '.', '--no-deps') - - # We test the minimum dependency versions using the minimum Python - # version so the lowest python runtime that we test has a corresponding constraints - # file, located at `testing/constraints--.txt`, which contains all of the - # 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 - ) - ] - - session.install(*constraints_deps) - - prerel_deps = [ - "googleapis-common-protos", - "google-api-core", - "google-auth", - # Exclude grpcio!=1.67.0rc1 which does not support python 3.13 - "grpcio!=1.67.0rc1", - "grpcio-status", - "protobuf", - "proto-plus", - ] - - for dep in prerel_deps: - session.install("--pre", "--no-deps", "--upgrade", dep) - - # Remaining dependencies - other_deps = [ - "requests", - ] - session.install(*other_deps) - - # Print out prerelease package versions - - session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") - session.run("python", "-c", "import google.auth; print(google.auth.__version__)") - session.run("python", "-c", "import grpc; print(grpc.__version__)") - session.run( - "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" - ) - session.run( - "python", "-c", "import proto; print(proto.__version__)" - ) - - session.run( - 'py.test', - '--quiet', - '--cov=google/shopping/merchant_reports_v1beta/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - - -@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=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 docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==7.0.1", "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=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", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/samples/generated_samples/merchantapi_v1beta_generated_report_service_search_async.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/samples/generated_samples/merchantapi_v1beta_generated_report_service_search_async.py deleted file mode 100644 index 6fa9200b9512..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/v1beta/samples/generated_samples/merchantapi_v1beta_generated_report_service_search_async.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Search -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-reports - - -# [START merchantapi_v1beta_generated_ReportService_Search_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_reports_v1beta - - -async def sample_search(): - # Create a client - client = merchant_reports_v1beta.ReportServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_reports_v1beta.SearchRequest( - parent="parent_value", - query="query_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_ReportService_Search_async] diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/samples/generated_samples/merchantapi_v1beta_generated_report_service_search_sync.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/samples/generated_samples/merchantapi_v1beta_generated_report_service_search_sync.py deleted file mode 100644 index 11f591230812..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/v1beta/samples/generated_samples/merchantapi_v1beta_generated_report_service_search_sync.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Search -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-reports - - -# [START merchantapi_v1beta_generated_ReportService_Search_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_reports_v1beta - - -def sample_search(): - # Create a client - client = merchant_reports_v1beta.ReportServiceClient() - - # Initialize request argument(s) - request = merchant_reports_v1beta.SearchRequest( - parent="parent_value", - query="query_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_ReportService_Search_sync] diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.reports.v1beta.json b/owl-bot-staging/google-shopping-merchant-reports/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.reports.v1beta.json deleted file mode 100644 index 145fa5b7eb46..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.reports.v1beta.json +++ /dev/null @@ -1,176 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.shopping.merchant.reports.v1beta", - "version": "v1beta" - } - ], - "language": "PYTHON", - "name": "google-shopping-merchant-reports", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_reports_v1beta.ReportServiceAsyncClient", - "shortName": "ReportServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_reports_v1beta.ReportServiceAsyncClient.search", - "method": { - "fullName": "google.shopping.merchant.reports.v1beta.ReportService.Search", - "service": { - "fullName": "google.shopping.merchant.reports.v1beta.ReportService", - "shortName": "ReportService" - }, - "shortName": "Search" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_reports_v1beta.types.SearchRequest" - }, - { - "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_reports_v1beta.services.report_service.pagers.SearchAsyncPager", - "shortName": "search" - }, - "description": "Sample for Search", - "file": "merchantapi_v1beta_generated_report_service_search_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_ReportService_Search_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "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": 54, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_report_service_search_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_reports_v1beta.ReportServiceClient", - "shortName": "ReportServiceClient" - }, - "fullName": "google.shopping.merchant_reports_v1beta.ReportServiceClient.search", - "method": { - "fullName": "google.shopping.merchant.reports.v1beta.ReportService.Search", - "service": { - "fullName": "google.shopping.merchant.reports.v1beta.ReportService", - "shortName": "ReportService" - }, - "shortName": "Search" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_reports_v1beta.types.SearchRequest" - }, - { - "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_reports_v1beta.services.report_service.pagers.SearchPager", - "shortName": "search" - }, - "description": "Sample for Search", - "file": "merchantapi_v1beta_generated_report_service_search_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_ReportService_Search_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "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": 54, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_report_service_search_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-shopping-merchant-reports/v1beta/scripts/fixup_merchant_reports_v1beta_keywords.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/scripts/fixup_merchant_reports_v1beta_keywords.py deleted file mode 100644 index 83db92c96848..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/v1beta/scripts/fixup_merchant_reports_v1beta_keywords.py +++ /dev/null @@ -1,176 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_reportsCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'search': ('parent', 'query', 'page_size', 'page_token', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=merchant_reportsCallTransformer(), -): - """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_reports 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-reports/v1beta/setup.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/setup.py deleted file mode 100644 index 434b659ca76d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/v1beta/setup.py +++ /dev/null @@ -1,99 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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-reports' - - -description = "Google Shopping Merchant Reports API client library" - -version = None - -with open(os.path.join(package_root, 'google/shopping/merchant_reports/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.0dev,!=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.0dev,!=2.24.0,!=2.25.0", - "proto-plus >= 1.22.3, <2.0.0dev", - "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'", - "protobuf>=3.20.2,<6.0.0dev,!=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.0dev", -] -extras = { -} -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-reports" - -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-reports/v1beta/testing/constraints-3.10.txt b/owl-bot-staging/google-shopping-merchant-reports/v1beta/testing/constraints-3.10.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/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-reports/v1beta/testing/constraints-3.11.txt b/owl-bot-staging/google-shopping-merchant-reports/v1beta/testing/constraints-3.11.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/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-reports/v1beta/testing/constraints-3.12.txt b/owl-bot-staging/google-shopping-merchant-reports/v1beta/testing/constraints-3.12.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/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-reports/v1beta/testing/constraints-3.13.txt b/owl-bot-staging/google-shopping-merchant-reports/v1beta/testing/constraints-3.13.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/v1beta/testing/constraints-3.13.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-reports/v1beta/testing/constraints-3.7.txt b/owl-bot-staging/google-shopping-merchant-reports/v1beta/testing/constraints-3.7.txt deleted file mode 100644 index 130a0c0f80ab..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/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.0dev", -# 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-reports/v1beta/testing/constraints-3.8.txt b/owl-bot-staging/google-shopping-merchant-reports/v1beta/testing/constraints-3.8.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/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-reports/v1beta/testing/constraints-3.9.txt b/owl-bot-staging/google-shopping-merchant-reports/v1beta/testing/constraints-3.9.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/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-reports/v1beta/tests/__init__.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/v1beta/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-reports/v1beta/tests/unit/__init__.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/v1beta/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-reports/v1beta/tests/unit/gapic/__init__.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/v1beta/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-reports/v1beta/tests/unit/gapic/merchant_reports_v1beta/__init__.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/tests/unit/gapic/merchant_reports_v1beta/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/v1beta/tests/unit/gapic/merchant_reports_v1beta/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-reports/v1beta/tests/unit/gapic/merchant_reports_v1beta/test_report_service.py b/owl-bot-staging/google-shopping-merchant-reports/v1beta/tests/unit/gapic/merchant_reports_v1beta/test_report_service.py deleted file mode 100644 index 8d6c1d186125..000000000000 --- a/owl-bot-staging/google-shopping-merchant-reports/v1beta/tests/unit/gapic/merchant_reports_v1beta/test_report_service.py +++ /dev/null @@ -1,2333 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_reports_v1beta.services.report_service import ReportServiceAsyncClient -from google.shopping.merchant_reports_v1beta.services.report_service import ReportServiceClient -from google.shopping.merchant_reports_v1beta.services.report_service import pagers -from google.shopping.merchant_reports_v1beta.services.report_service import transports -from google.shopping.merchant_reports_v1beta.types import reports -import google.auth - - -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 ReportServiceClient._get_default_mtls_endpoint(None) is None - assert ReportServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ReportServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ReportServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ReportServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ReportServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert ReportServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert ReportServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert ReportServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - ReportServiceClient._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 ReportServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert ReportServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert ReportServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - ReportServiceClient._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 ReportServiceClient._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 ReportServiceClient._get_client_cert_source(None, False) is None - assert ReportServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert ReportServiceClient._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 ReportServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert ReportServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(ReportServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReportServiceClient)) -@mock.patch.object(ReportServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReportServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = ReportServiceClient._DEFAULT_UNIVERSE - default_endpoint = ReportServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = ReportServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert ReportServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert ReportServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == ReportServiceClient.DEFAULT_MTLS_ENDPOINT - assert ReportServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert ReportServiceClient._get_api_endpoint(None, None, default_universe, "always") == ReportServiceClient.DEFAULT_MTLS_ENDPOINT - assert ReportServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == ReportServiceClient.DEFAULT_MTLS_ENDPOINT - assert ReportServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert ReportServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - ReportServiceClient._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 ReportServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert ReportServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert ReportServiceClient._get_universe_domain(None, None) == ReportServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - ReportServiceClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ReportServiceClient, "grpc"), - (ReportServiceAsyncClient, "grpc_asyncio"), - (ReportServiceClient, "rest"), -]) -def test_report_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.ReportServiceGrpcTransport, "grpc"), - (transports.ReportServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.ReportServiceRestTransport, "rest"), -]) -def test_report_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", [ - (ReportServiceClient, "grpc"), - (ReportServiceAsyncClient, "grpc_asyncio"), - (ReportServiceClient, "rest"), -]) -def test_report_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_report_service_client_get_transport_class(): - transport = ReportServiceClient.get_transport_class() - available_transports = [ - transports.ReportServiceGrpcTransport, - transports.ReportServiceRestTransport, - ] - assert transport in available_transports - - transport = ReportServiceClient.get_transport_class("grpc") - assert transport == transports.ReportServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ReportServiceClient, transports.ReportServiceGrpcTransport, "grpc"), - (ReportServiceAsyncClient, transports.ReportServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (ReportServiceClient, transports.ReportServiceRestTransport, "rest"), -]) -@mock.patch.object(ReportServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReportServiceClient)) -@mock.patch.object(ReportServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReportServiceAsyncClient)) -def test_report_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(ReportServiceClient, '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(ReportServiceClient, '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", [ - (ReportServiceClient, transports.ReportServiceGrpcTransport, "grpc", "true"), - (ReportServiceAsyncClient, transports.ReportServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ReportServiceClient, transports.ReportServiceGrpcTransport, "grpc", "false"), - (ReportServiceAsyncClient, transports.ReportServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (ReportServiceClient, transports.ReportServiceRestTransport, "rest", "true"), - (ReportServiceClient, transports.ReportServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(ReportServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReportServiceClient)) -@mock.patch.object(ReportServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReportServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_report_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", [ - ReportServiceClient, ReportServiceAsyncClient -]) -@mock.patch.object(ReportServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ReportServiceClient)) -@mock.patch.object(ReportServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ReportServiceAsyncClient)) -def test_report_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", [ - ReportServiceClient, ReportServiceAsyncClient -]) -@mock.patch.object(ReportServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReportServiceClient)) -@mock.patch.object(ReportServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ReportServiceAsyncClient)) -def test_report_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = ReportServiceClient._DEFAULT_UNIVERSE - default_endpoint = ReportServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = ReportServiceClient._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", [ - (ReportServiceClient, transports.ReportServiceGrpcTransport, "grpc"), - (ReportServiceAsyncClient, transports.ReportServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (ReportServiceClient, transports.ReportServiceRestTransport, "rest"), -]) -def test_report_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", [ - (ReportServiceClient, transports.ReportServiceGrpcTransport, "grpc", grpc_helpers), - (ReportServiceAsyncClient, transports.ReportServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (ReportServiceClient, transports.ReportServiceRestTransport, "rest", None), -]) -def test_report_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_report_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_reports_v1beta.services.report_service.transports.ReportServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ReportServiceClient( - 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", [ - (ReportServiceClient, transports.ReportServiceGrpcTransport, "grpc", grpc_helpers), - (ReportServiceAsyncClient, transports.ReportServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_report_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", [ - reports.SearchRequest, - dict, -]) -def test_search(request_type, transport: str = 'grpc'): - client = ReportServiceClient( - 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.search), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = reports.SearchResponse( - next_page_token='next_page_token_value', - ) - response = client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = reports.SearchRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_search_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 = ReportServiceClient( - 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 = reports.SearchRequest( - parent='parent_value', - query='query_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.search), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.search(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == reports.SearchRequest( - parent='parent_value', - query='query_value', - page_token='page_token_value', - ) - -def test_search_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ReportServiceClient( - 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.search in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.search] = mock_rpc - request = {} - client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.search(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_search_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = ReportServiceAsyncClient( - 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.search in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.search] = mock_rpc - - request = {} - await client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.search(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_search_async(transport: str = 'grpc_asyncio', request_type=reports.SearchRequest): - client = ReportServiceAsyncClient( - 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.search), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(reports.SearchResponse( - next_page_token='next_page_token_value', - )) - response = await client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = reports.SearchRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_search_async_from_dict(): - await test_search_async(request_type=dict) - -def test_search_field_headers(): - client = ReportServiceClient( - 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 = reports.SearchRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - call.return_value = reports.SearchResponse() - client.search(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_search_field_headers_async(): - client = ReportServiceAsyncClient( - 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 = reports.SearchRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(reports.SearchResponse()) - await client.search(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_search_flattened(): - client = ReportServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = reports.SearchResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.search( - 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_search_flattened_error(): - client = ReportServiceClient( - 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.search( - reports.SearchRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_search_flattened_async(): - client = ReportServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = reports.SearchResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(reports.SearchResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.search( - 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_search_flattened_error_async(): - client = ReportServiceAsyncClient( - 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.search( - reports.SearchRequest(), - parent='parent_value', - ) - - -def test_search_pager(transport_name: str = "grpc"): - client = ReportServiceClient( - 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.search), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - reports.SearchResponse( - results=[ - reports.ReportRow(), - reports.ReportRow(), - reports.ReportRow(), - ], - next_page_token='abc', - ), - reports.SearchResponse( - results=[], - next_page_token='def', - ), - reports.SearchResponse( - results=[ - reports.ReportRow(), - ], - next_page_token='ghi', - ), - reports.SearchResponse( - results=[ - reports.ReportRow(), - reports.ReportRow(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.search(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, reports.ReportRow) - for i in results) -def test_search_pages(transport_name: str = "grpc"): - client = ReportServiceClient( - 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.search), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - reports.SearchResponse( - results=[ - reports.ReportRow(), - reports.ReportRow(), - reports.ReportRow(), - ], - next_page_token='abc', - ), - reports.SearchResponse( - results=[], - next_page_token='def', - ), - reports.SearchResponse( - results=[ - reports.ReportRow(), - ], - next_page_token='ghi', - ), - reports.SearchResponse( - results=[ - reports.ReportRow(), - reports.ReportRow(), - ], - ), - RuntimeError, - ) - pages = list(client.search(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_search_async_pager(): - client = ReportServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - reports.SearchResponse( - results=[ - reports.ReportRow(), - reports.ReportRow(), - reports.ReportRow(), - ], - next_page_token='abc', - ), - reports.SearchResponse( - results=[], - next_page_token='def', - ), - reports.SearchResponse( - results=[ - reports.ReportRow(), - ], - next_page_token='ghi', - ), - reports.SearchResponse( - results=[ - reports.ReportRow(), - reports.ReportRow(), - ], - ), - RuntimeError, - ) - async_pager = await client.search(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, reports.ReportRow) - for i in responses) - - -@pytest.mark.asyncio -async def test_search_async_pages(): - client = ReportServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - reports.SearchResponse( - results=[ - reports.ReportRow(), - reports.ReportRow(), - reports.ReportRow(), - ], - next_page_token='abc', - ), - reports.SearchResponse( - results=[], - next_page_token='def', - ), - reports.SearchResponse( - results=[ - reports.ReportRow(), - ], - next_page_token='ghi', - ), - reports.SearchResponse( - results=[ - reports.ReportRow(), - reports.ReportRow(), - ], - ), - 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.search(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_search_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 = ReportServiceClient( - 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.search in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.search] = mock_rpc - - request = {} - client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.search(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_search_rest_required_fields(request_type=reports.SearchRequest): - transport_class = transports.ReportServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["query"] = "" - request = 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()).search._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["query"] = 'query_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).search._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 "query" in jsonified_request - assert jsonified_request["query"] == 'query_value' - - client = ReportServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = reports.SearchResponse() - # 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 = reports.SearchResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.search(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_search_rest_unset_required_fields(): - transport = transports.ReportServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.search._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "query", ))) - - -def test_search_rest_flattened(): - client = ReportServiceClient( - 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 = reports.SearchResponse() - - # 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 = reports.SearchResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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.search(**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/reports/v1beta/{parent=accounts/*}/reports:search" % client.transport._host, args[1]) - - -def test_search_rest_flattened_error(transport: str = 'rest'): - client = ReportServiceClient( - 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.search( - reports.SearchRequest(), - parent='parent_value', - ) - - -def test_search_rest_pager(transport: str = 'rest'): - client = ReportServiceClient( - 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 = ( - reports.SearchResponse( - results=[ - reports.ReportRow(), - reports.ReportRow(), - reports.ReportRow(), - ], - next_page_token='abc', - ), - reports.SearchResponse( - results=[], - next_page_token='def', - ), - reports.SearchResponse( - results=[ - reports.ReportRow(), - ], - next_page_token='ghi', - ), - reports.SearchResponse( - results=[ - reports.ReportRow(), - reports.ReportRow(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(reports.SearchResponse.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.search(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, reports.ReportRow) - for i in results) - - pages = list(client.search(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.ReportServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ReportServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ReportServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ReportServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ReportServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ReportServiceClient( - 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 = ReportServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ReportServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ReportServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ReportServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ReportServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ReportServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ReportServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ReportServiceGrpcTransport, - transports.ReportServiceGrpcAsyncIOTransport, - transports.ReportServiceRestTransport, -]) -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 = ReportServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = ReportServiceClient( - 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_search_empty_call_grpc(): - client = ReportServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - call.return_value = reports.SearchResponse() - client.search(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reports.SearchRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = ReportServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = ReportServiceAsyncClient( - 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_search_empty_call_grpc_asyncio(): - client = ReportServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(reports.SearchResponse( - next_page_token='next_page_token_value', - )) - await client.search(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reports.SearchRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = ReportServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_search_rest_bad_request(request_type=reports.SearchRequest): - client = ReportServiceClient( - 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.search(request) - - -@pytest.mark.parametrize("request_type", [ - reports.SearchRequest, - dict, -]) -def test_search_rest_call_success(request_type): - client = ReportServiceClient( - 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 = reports.SearchResponse( - 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 = reports.SearchResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.search(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_search_rest_interceptors(null_interceptor): - transport = transports.ReportServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ReportServiceRestInterceptor(), - ) - client = ReportServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ReportServiceRestInterceptor, "post_search") as post, \ - mock.patch.object(transports.ReportServiceRestInterceptor, "pre_search") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = reports.SearchRequest.pb(reports.SearchRequest()) - 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 = reports.SearchResponse.to_json(reports.SearchResponse()) - req.return_value.content = return_value - - request = reports.SearchRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = reports.SearchResponse() - - client.search(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - -def test_initialize_client_w_rest(): - client = ReportServiceClient( - 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_search_empty_call_rest(): - client = ReportServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - client.search(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reports.SearchRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = ReportServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ReportServiceGrpcTransport, - ) - -def test_report_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ReportServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_report_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.shopping.merchant_reports_v1beta.services.report_service.transports.ReportServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ReportServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'search', - ) - 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_report_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_reports_v1beta.services.report_service.transports.ReportServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ReportServiceTransport( - 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_report_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_reports_v1beta.services.report_service.transports.ReportServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ReportServiceTransport() - adc.assert_called_once() - - -def test_report_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) - ReportServiceClient() - 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.ReportServiceGrpcTransport, - transports.ReportServiceGrpcAsyncIOTransport, - ], -) -def test_report_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.ReportServiceGrpcTransport, - transports.ReportServiceGrpcAsyncIOTransport, - transports.ReportServiceRestTransport, - ], -) -def test_report_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.ReportServiceGrpcTransport, grpc_helpers), - (transports.ReportServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_report_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.ReportServiceGrpcTransport, transports.ReportServiceGrpcAsyncIOTransport]) -def test_report_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_report_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.ReportServiceRestTransport ( - 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_report_service_host_no_port(transport_name): - client = ReportServiceClient( - 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_report_service_host_with_port(transport_name): - client = ReportServiceClient( - 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_report_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = ReportServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = ReportServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.search._session - session2 = client2.transport.search._session - assert session1 != session2 -def test_report_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ReportServiceGrpcTransport( - 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_report_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ReportServiceGrpcAsyncIOTransport( - 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.ReportServiceGrpcTransport, transports.ReportServiceGrpcAsyncIOTransport]) -def test_report_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.ReportServiceGrpcTransport, transports.ReportServiceGrpcAsyncIOTransport]) -def test_report_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_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ReportServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = ReportServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ReportServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = ReportServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = ReportServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ReportServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ReportServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = ReportServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ReportServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = ReportServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = ReportServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ReportServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = ReportServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = ReportServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ReportServiceClient.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.ReportServiceTransport, '_prep_wrapped_messages') as prep: - client = ReportServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ReportServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = ReportServiceClient.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 = ReportServiceClient( - 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 = ReportServiceAsyncClient( - 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 = ReportServiceClient( - 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 = ReportServiceClient( - 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", [ - (ReportServiceClient, transports.ReportServiceGrpcTransport), - (ReportServiceAsyncClient, transports.ReportServiceGrpcAsyncIOTransport), -]) -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/grafeas/v1/.coveragerc b/owl-bot-staging/grafeas/v1/.coveragerc deleted file mode 100644 index 4e55acc51c44..000000000000 --- a/owl-bot-staging/grafeas/v1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - grafeas/grafeas/__init__.py - grafeas/grafeas/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/grafeas/v1/.flake8 b/owl-bot-staging/grafeas/v1/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/grafeas/v1/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/grafeas/v1/MANIFEST.in b/owl-bot-staging/grafeas/v1/MANIFEST.in deleted file mode 100644 index 075904e53516..000000000000 --- a/owl-bot-staging/grafeas/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include grafeas/grafeas *.py -recursive-include grafeas/grafeas_v1 *.py diff --git a/owl-bot-staging/grafeas/v1/README.rst b/owl-bot-staging/grafeas/v1/README.rst deleted file mode 100644 index 0f879492ca1d..000000000000 --- a/owl-bot-staging/grafeas/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Grafeas Grafeas 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 Grafeas Grafeas 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 diff --git a/owl-bot-staging/grafeas/v1/docs/_static/custom.css b/owl-bot-staging/grafeas/v1/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/grafeas/v1/docs/_static/custom.css +++ /dev/null @@ -1,3 +0,0 @@ -dl.field-list > dt { - min-width: 100px -} diff --git a/owl-bot-staging/grafeas/v1/docs/conf.py b/owl-bot-staging/grafeas/v1/docs/conf.py deleted file mode 100644 index e43817cf2e74..000000000000 --- a/owl-bot-staging/grafeas/v1/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# grafeas 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("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# 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.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -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"grafeas" -copyright = u"2023, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# 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 = 'en' - -# 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"] - -# 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": "Grafeas Client Libraries for Python", - "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 = "grafeas-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, - "grafeas.tex", - u"grafeas 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, - "grafeas", - u"Grafeas Grafeas 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, - "grafeas", - u"grafeas Documentation", - author, - "grafeas", - "GAPIC library for Grafeas Grafeas API", - "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": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", 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/grafeas/v1/docs/grafeas_v1/grafeas.rst b/owl-bot-staging/grafeas/v1/docs/grafeas_v1/grafeas.rst deleted file mode 100644 index 7339fabecaee..000000000000 --- a/owl-bot-staging/grafeas/v1/docs/grafeas_v1/grafeas.rst +++ /dev/null @@ -1,10 +0,0 @@ -Grafeas -------------------------- - -.. automodule:: grafeas.grafeas_v1.services.grafeas - :members: - :inherited-members: - -.. automodule:: grafeas.grafeas_v1.services.grafeas.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/grafeas/v1/docs/grafeas_v1/services_.rst b/owl-bot-staging/grafeas/v1/docs/grafeas_v1/services_.rst deleted file mode 100644 index ca38222018ff..000000000000 --- a/owl-bot-staging/grafeas/v1/docs/grafeas_v1/services_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Grafeas Grafeas v1 API -=================================== -.. toctree:: - :maxdepth: 2 - - grafeas diff --git a/owl-bot-staging/grafeas/v1/docs/grafeas_v1/types_.rst b/owl-bot-staging/grafeas/v1/docs/grafeas_v1/types_.rst deleted file mode 100644 index 5808795e6eb1..000000000000 --- a/owl-bot-staging/grafeas/v1/docs/grafeas_v1/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Grafeas Grafeas v1 API -================================ - -.. automodule:: grafeas.grafeas_v1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/grafeas/v1/docs/index.rst b/owl-bot-staging/grafeas/v1/docs/index.rst deleted file mode 100644 index 35750509477c..000000000000 --- a/owl-bot-staging/grafeas/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - grafeas_v1/services_ - grafeas_v1/types_ diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas/__init__.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas/__init__.py deleted file mode 100644 index f2282fa0cc79..000000000000 --- a/owl-bot-staging/grafeas/v1/grafeas/grafeas/__init__.py +++ /dev/null @@ -1,211 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from grafeas.grafeas import gapic_version as package_version - -__version__ = package_version.__version__ - - -from grafeas.grafeas_v1.services.grafeas.client import GrafeasClient -from grafeas.grafeas_v1.services.grafeas.async_client import GrafeasAsyncClient - -from grafeas.grafeas_v1.types.attestation import AttestationNote -from grafeas.grafeas_v1.types.attestation import AttestationOccurrence -from grafeas.grafeas_v1.types.attestation import Jwt -from grafeas.grafeas_v1.types.build import BuildNote -from grafeas.grafeas_v1.types.build import BuildOccurrence -from grafeas.grafeas_v1.types.common import Digest -from grafeas.grafeas_v1.types.common import Envelope -from grafeas.grafeas_v1.types.common import EnvelopeSignature -from grafeas.grafeas_v1.types.common import FileLocation -from grafeas.grafeas_v1.types.common import License -from grafeas.grafeas_v1.types.common import RelatedUrl -from grafeas.grafeas_v1.types.common import Signature -from grafeas.grafeas_v1.types.common import NoteKind -from grafeas.grafeas_v1.types.compliance import ComplianceNote -from grafeas.grafeas_v1.types.compliance import ComplianceOccurrence -from grafeas.grafeas_v1.types.compliance import ComplianceVersion -from grafeas.grafeas_v1.types.compliance import NonCompliantFile -from grafeas.grafeas_v1.types.cvss import CVSS -from grafeas.grafeas_v1.types.cvss import CVSSv3 -from grafeas.grafeas_v1.types.cvss import CVSSVersion -from grafeas.grafeas_v1.types.deployment import DeploymentNote -from grafeas.grafeas_v1.types.deployment import DeploymentOccurrence -from grafeas.grafeas_v1.types.discovery import DiscoveryNote -from grafeas.grafeas_v1.types.discovery import DiscoveryOccurrence -from grafeas.grafeas_v1.types.dsse_attestation import DSSEAttestationNote -from grafeas.grafeas_v1.types.dsse_attestation import DSSEAttestationOccurrence -from grafeas.grafeas_v1.types.grafeas import BatchCreateNotesRequest -from grafeas.grafeas_v1.types.grafeas import BatchCreateNotesResponse -from grafeas.grafeas_v1.types.grafeas import BatchCreateOccurrencesRequest -from grafeas.grafeas_v1.types.grafeas import BatchCreateOccurrencesResponse -from grafeas.grafeas_v1.types.grafeas import CreateNoteRequest -from grafeas.grafeas_v1.types.grafeas import CreateOccurrenceRequest -from grafeas.grafeas_v1.types.grafeas import DeleteNoteRequest -from grafeas.grafeas_v1.types.grafeas import DeleteOccurrenceRequest -from grafeas.grafeas_v1.types.grafeas import GetNoteRequest -from grafeas.grafeas_v1.types.grafeas import GetOccurrenceNoteRequest -from grafeas.grafeas_v1.types.grafeas import GetOccurrenceRequest -from grafeas.grafeas_v1.types.grafeas import ListNoteOccurrencesRequest -from grafeas.grafeas_v1.types.grafeas import ListNoteOccurrencesResponse -from grafeas.grafeas_v1.types.grafeas import ListNotesRequest -from grafeas.grafeas_v1.types.grafeas import ListNotesResponse -from grafeas.grafeas_v1.types.grafeas import ListOccurrencesRequest -from grafeas.grafeas_v1.types.grafeas import ListOccurrencesResponse -from grafeas.grafeas_v1.types.grafeas import Note -from grafeas.grafeas_v1.types.grafeas import Occurrence -from grafeas.grafeas_v1.types.grafeas import UpdateNoteRequest -from grafeas.grafeas_v1.types.grafeas import UpdateOccurrenceRequest -from grafeas.grafeas_v1.types.image import Fingerprint -from grafeas.grafeas_v1.types.image import ImageNote -from grafeas.grafeas_v1.types.image import ImageOccurrence -from grafeas.grafeas_v1.types.image import Layer -from grafeas.grafeas_v1.types.intoto_provenance import BuilderConfig -from grafeas.grafeas_v1.types.intoto_provenance import Completeness -from grafeas.grafeas_v1.types.intoto_provenance import InTotoProvenance -from grafeas.grafeas_v1.types.intoto_provenance import Metadata -from grafeas.grafeas_v1.types.intoto_provenance import Recipe -from grafeas.grafeas_v1.types.intoto_statement import InTotoSlsaProvenanceV1 -from grafeas.grafeas_v1.types.intoto_statement import InTotoStatement -from grafeas.grafeas_v1.types.intoto_statement import Subject -from grafeas.grafeas_v1.types.package import Distribution -from grafeas.grafeas_v1.types.package import Location -from grafeas.grafeas_v1.types.package import PackageNote -from grafeas.grafeas_v1.types.package import PackageOccurrence -from grafeas.grafeas_v1.types.package import Version -from grafeas.grafeas_v1.types.package import Architecture -from grafeas.grafeas_v1.types.provenance import AliasContext -from grafeas.grafeas_v1.types.provenance import Artifact -from grafeas.grafeas_v1.types.provenance import BuildProvenance -from grafeas.grafeas_v1.types.provenance import CloudRepoSourceContext -from grafeas.grafeas_v1.types.provenance import Command -from grafeas.grafeas_v1.types.provenance import FileHashes -from grafeas.grafeas_v1.types.provenance import GerritSourceContext -from grafeas.grafeas_v1.types.provenance import GitSourceContext -from grafeas.grafeas_v1.types.provenance import Hash -from grafeas.grafeas_v1.types.provenance import ProjectRepoId -from grafeas.grafeas_v1.types.provenance import RepoId -from grafeas.grafeas_v1.types.provenance import Source -from grafeas.grafeas_v1.types.provenance import SourceContext -from grafeas.grafeas_v1.types.sbom import SbomReferenceIntotoPayload -from grafeas.grafeas_v1.types.sbom import SbomReferenceIntotoPredicate -from grafeas.grafeas_v1.types.sbom import SBOMReferenceNote -from grafeas.grafeas_v1.types.sbom import SBOMReferenceOccurrence -from grafeas.grafeas_v1.types.severity import Severity -from grafeas.grafeas_v1.types.slsa_provenance import SlsaProvenance -from grafeas.grafeas_v1.types.slsa_provenance_zero_two import SlsaProvenanceZeroTwo -from grafeas.grafeas_v1.types.upgrade import UpgradeDistribution -from grafeas.grafeas_v1.types.upgrade import UpgradeNote -from grafeas.grafeas_v1.types.upgrade import UpgradeOccurrence -from grafeas.grafeas_v1.types.upgrade import WindowsUpdate -from grafeas.grafeas_v1.types.vex import VulnerabilityAssessmentNote -from grafeas.grafeas_v1.types.vulnerability import VulnerabilityNote -from grafeas.grafeas_v1.types.vulnerability import VulnerabilityOccurrence - -__all__ = ('GrafeasClient', - 'GrafeasAsyncClient', - 'AttestationNote', - 'AttestationOccurrence', - 'Jwt', - 'BuildNote', - 'BuildOccurrence', - 'Digest', - 'Envelope', - 'EnvelopeSignature', - 'FileLocation', - 'License', - 'RelatedUrl', - 'Signature', - 'NoteKind', - 'ComplianceNote', - 'ComplianceOccurrence', - 'ComplianceVersion', - 'NonCompliantFile', - 'CVSS', - 'CVSSv3', - 'CVSSVersion', - 'DeploymentNote', - 'DeploymentOccurrence', - 'DiscoveryNote', - 'DiscoveryOccurrence', - 'DSSEAttestationNote', - 'DSSEAttestationOccurrence', - 'BatchCreateNotesRequest', - 'BatchCreateNotesResponse', - 'BatchCreateOccurrencesRequest', - 'BatchCreateOccurrencesResponse', - 'CreateNoteRequest', - 'CreateOccurrenceRequest', - 'DeleteNoteRequest', - 'DeleteOccurrenceRequest', - 'GetNoteRequest', - 'GetOccurrenceNoteRequest', - 'GetOccurrenceRequest', - 'ListNoteOccurrencesRequest', - 'ListNoteOccurrencesResponse', - 'ListNotesRequest', - 'ListNotesResponse', - 'ListOccurrencesRequest', - 'ListOccurrencesResponse', - 'Note', - 'Occurrence', - 'UpdateNoteRequest', - 'UpdateOccurrenceRequest', - 'Fingerprint', - 'ImageNote', - 'ImageOccurrence', - 'Layer', - 'BuilderConfig', - 'Completeness', - 'InTotoProvenance', - 'Metadata', - 'Recipe', - 'InTotoSlsaProvenanceV1', - 'InTotoStatement', - 'Subject', - 'Distribution', - 'Location', - 'PackageNote', - 'PackageOccurrence', - 'Version', - 'Architecture', - 'AliasContext', - 'Artifact', - 'BuildProvenance', - 'CloudRepoSourceContext', - 'Command', - 'FileHashes', - 'GerritSourceContext', - 'GitSourceContext', - 'Hash', - 'ProjectRepoId', - 'RepoId', - 'Source', - 'SourceContext', - 'SbomReferenceIntotoPayload', - 'SbomReferenceIntotoPredicate', - 'SBOMReferenceNote', - 'SBOMReferenceOccurrence', - 'Severity', - 'SlsaProvenance', - 'SlsaProvenanceZeroTwo', - 'UpgradeDistribution', - 'UpgradeNote', - 'UpgradeOccurrence', - 'WindowsUpdate', - 'VulnerabilityAssessmentNote', - 'VulnerabilityNote', - 'VulnerabilityOccurrence', -) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas/gapic_version.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/grafeas/v1/grafeas/grafeas/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/grafeas/v1/grafeas/grafeas/py.typed b/owl-bot-staging/grafeas/v1/grafeas/grafeas/py.typed deleted file mode 100644 index 49e8f71d60b7..000000000000 --- a/owl-bot-staging/grafeas/v1/grafeas/grafeas/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The grafeas package uses inline types. diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/__init__.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/__init__.py deleted file mode 100644 index 7a4f4fa690fd..000000000000 --- a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/__init__.py +++ /dev/null @@ -1,212 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from grafeas.grafeas_v1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.grafeas import GrafeasClient -from .services.grafeas import GrafeasAsyncClient - -from .types.attestation import AttestationNote -from .types.attestation import AttestationOccurrence -from .types.attestation import Jwt -from .types.build import BuildNote -from .types.build import BuildOccurrence -from .types.common import Digest -from .types.common import Envelope -from .types.common import EnvelopeSignature -from .types.common import FileLocation -from .types.common import License -from .types.common import RelatedUrl -from .types.common import Signature -from .types.common import NoteKind -from .types.compliance import ComplianceNote -from .types.compliance import ComplianceOccurrence -from .types.compliance import ComplianceVersion -from .types.compliance import NonCompliantFile -from .types.cvss import CVSS -from .types.cvss import CVSSv3 -from .types.cvss import CVSSVersion -from .types.deployment import DeploymentNote -from .types.deployment import DeploymentOccurrence -from .types.discovery import DiscoveryNote -from .types.discovery import DiscoveryOccurrence -from .types.dsse_attestation import DSSEAttestationNote -from .types.dsse_attestation import DSSEAttestationOccurrence -from .types.grafeas import BatchCreateNotesRequest -from .types.grafeas import BatchCreateNotesResponse -from .types.grafeas import BatchCreateOccurrencesRequest -from .types.grafeas import BatchCreateOccurrencesResponse -from .types.grafeas import CreateNoteRequest -from .types.grafeas import CreateOccurrenceRequest -from .types.grafeas import DeleteNoteRequest -from .types.grafeas import DeleteOccurrenceRequest -from .types.grafeas import GetNoteRequest -from .types.grafeas import GetOccurrenceNoteRequest -from .types.grafeas import GetOccurrenceRequest -from .types.grafeas import ListNoteOccurrencesRequest -from .types.grafeas import ListNoteOccurrencesResponse -from .types.grafeas import ListNotesRequest -from .types.grafeas import ListNotesResponse -from .types.grafeas import ListOccurrencesRequest -from .types.grafeas import ListOccurrencesResponse -from .types.grafeas import Note -from .types.grafeas import Occurrence -from .types.grafeas import UpdateNoteRequest -from .types.grafeas import UpdateOccurrenceRequest -from .types.image import Fingerprint -from .types.image import ImageNote -from .types.image import ImageOccurrence -from .types.image import Layer -from .types.intoto_provenance import BuilderConfig -from .types.intoto_provenance import Completeness -from .types.intoto_provenance import InTotoProvenance -from .types.intoto_provenance import Metadata -from .types.intoto_provenance import Recipe -from .types.intoto_statement import InTotoSlsaProvenanceV1 -from .types.intoto_statement import InTotoStatement -from .types.intoto_statement import Subject -from .types.package import Distribution -from .types.package import Location -from .types.package import PackageNote -from .types.package import PackageOccurrence -from .types.package import Version -from .types.package import Architecture -from .types.provenance import AliasContext -from .types.provenance import Artifact -from .types.provenance import BuildProvenance -from .types.provenance import CloudRepoSourceContext -from .types.provenance import Command -from .types.provenance import FileHashes -from .types.provenance import GerritSourceContext -from .types.provenance import GitSourceContext -from .types.provenance import Hash -from .types.provenance import ProjectRepoId -from .types.provenance import RepoId -from .types.provenance import Source -from .types.provenance import SourceContext -from .types.sbom import SbomReferenceIntotoPayload -from .types.sbom import SbomReferenceIntotoPredicate -from .types.sbom import SBOMReferenceNote -from .types.sbom import SBOMReferenceOccurrence -from .types.severity import Severity -from .types.slsa_provenance import SlsaProvenance -from .types.slsa_provenance_zero_two import SlsaProvenanceZeroTwo -from .types.upgrade import UpgradeDistribution -from .types.upgrade import UpgradeNote -from .types.upgrade import UpgradeOccurrence -from .types.upgrade import WindowsUpdate -from .types.vex import VulnerabilityAssessmentNote -from .types.vulnerability import VulnerabilityNote -from .types.vulnerability import VulnerabilityOccurrence - -__all__ = ( - 'GrafeasAsyncClient', -'AliasContext', -'Architecture', -'Artifact', -'AttestationNote', -'AttestationOccurrence', -'BatchCreateNotesRequest', -'BatchCreateNotesResponse', -'BatchCreateOccurrencesRequest', -'BatchCreateOccurrencesResponse', -'BuildNote', -'BuildOccurrence', -'BuildProvenance', -'BuilderConfig', -'CVSS', -'CVSSVersion', -'CVSSv3', -'CloudRepoSourceContext', -'Command', -'Completeness', -'ComplianceNote', -'ComplianceOccurrence', -'ComplianceVersion', -'CreateNoteRequest', -'CreateOccurrenceRequest', -'DSSEAttestationNote', -'DSSEAttestationOccurrence', -'DeleteNoteRequest', -'DeleteOccurrenceRequest', -'DeploymentNote', -'DeploymentOccurrence', -'Digest', -'DiscoveryNote', -'DiscoveryOccurrence', -'Distribution', -'Envelope', -'EnvelopeSignature', -'FileHashes', -'FileLocation', -'Fingerprint', -'GerritSourceContext', -'GetNoteRequest', -'GetOccurrenceNoteRequest', -'GetOccurrenceRequest', -'GitSourceContext', -'GrafeasClient', -'Hash', -'ImageNote', -'ImageOccurrence', -'InTotoProvenance', -'InTotoSlsaProvenanceV1', -'InTotoStatement', -'Jwt', -'Layer', -'License', -'ListNoteOccurrencesRequest', -'ListNoteOccurrencesResponse', -'ListNotesRequest', -'ListNotesResponse', -'ListOccurrencesRequest', -'ListOccurrencesResponse', -'Location', -'Metadata', -'NonCompliantFile', -'Note', -'NoteKind', -'Occurrence', -'PackageNote', -'PackageOccurrence', -'ProjectRepoId', -'Recipe', -'RelatedUrl', -'RepoId', -'SBOMReferenceNote', -'SBOMReferenceOccurrence', -'SbomReferenceIntotoPayload', -'SbomReferenceIntotoPredicate', -'Severity', -'Signature', -'SlsaProvenance', -'SlsaProvenanceZeroTwo', -'Source', -'SourceContext', -'Subject', -'UpdateNoteRequest', -'UpdateOccurrenceRequest', -'UpgradeDistribution', -'UpgradeNote', -'UpgradeOccurrence', -'Version', -'VulnerabilityAssessmentNote', -'VulnerabilityNote', -'VulnerabilityOccurrence', -'WindowsUpdate', -) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/gapic_metadata.json b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/gapic_metadata.json deleted file mode 100644 index ec505dda48a9..000000000000 --- a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/gapic_metadata.json +++ /dev/null @@ -1,238 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "grafeas.grafeas_v1", - "protoPackage": "grafeas.v1", - "schema": "1.0", - "services": { - "Grafeas": { - "clients": { - "grpc": { - "libraryClient": "GrafeasClient", - "rpcs": { - "BatchCreateNotes": { - "methods": [ - "batch_create_notes" - ] - }, - "BatchCreateOccurrences": { - "methods": [ - "batch_create_occurrences" - ] - }, - "CreateNote": { - "methods": [ - "create_note" - ] - }, - "CreateOccurrence": { - "methods": [ - "create_occurrence" - ] - }, - "DeleteNote": { - "methods": [ - "delete_note" - ] - }, - "DeleteOccurrence": { - "methods": [ - "delete_occurrence" - ] - }, - "GetNote": { - "methods": [ - "get_note" - ] - }, - "GetOccurrence": { - "methods": [ - "get_occurrence" - ] - }, - "GetOccurrenceNote": { - "methods": [ - "get_occurrence_note" - ] - }, - "ListNoteOccurrences": { - "methods": [ - "list_note_occurrences" - ] - }, - "ListNotes": { - "methods": [ - "list_notes" - ] - }, - "ListOccurrences": { - "methods": [ - "list_occurrences" - ] - }, - "UpdateNote": { - "methods": [ - "update_note" - ] - }, - "UpdateOccurrence": { - "methods": [ - "update_occurrence" - ] - } - } - }, - "grpc-async": { - "libraryClient": "GrafeasAsyncClient", - "rpcs": { - "BatchCreateNotes": { - "methods": [ - "batch_create_notes" - ] - }, - "BatchCreateOccurrences": { - "methods": [ - "batch_create_occurrences" - ] - }, - "CreateNote": { - "methods": [ - "create_note" - ] - }, - "CreateOccurrence": { - "methods": [ - "create_occurrence" - ] - }, - "DeleteNote": { - "methods": [ - "delete_note" - ] - }, - "DeleteOccurrence": { - "methods": [ - "delete_occurrence" - ] - }, - "GetNote": { - "methods": [ - "get_note" - ] - }, - "GetOccurrence": { - "methods": [ - "get_occurrence" - ] - }, - "GetOccurrenceNote": { - "methods": [ - "get_occurrence_note" - ] - }, - "ListNoteOccurrences": { - "methods": [ - "list_note_occurrences" - ] - }, - "ListNotes": { - "methods": [ - "list_notes" - ] - }, - "ListOccurrences": { - "methods": [ - "list_occurrences" - ] - }, - "UpdateNote": { - "methods": [ - "update_note" - ] - }, - "UpdateOccurrence": { - "methods": [ - "update_occurrence" - ] - } - } - }, - "rest": { - "libraryClient": "GrafeasClient", - "rpcs": { - "BatchCreateNotes": { - "methods": [ - "batch_create_notes" - ] - }, - "BatchCreateOccurrences": { - "methods": [ - "batch_create_occurrences" - ] - }, - "CreateNote": { - "methods": [ - "create_note" - ] - }, - "CreateOccurrence": { - "methods": [ - "create_occurrence" - ] - }, - "DeleteNote": { - "methods": [ - "delete_note" - ] - }, - "DeleteOccurrence": { - "methods": [ - "delete_occurrence" - ] - }, - "GetNote": { - "methods": [ - "get_note" - ] - }, - "GetOccurrence": { - "methods": [ - "get_occurrence" - ] - }, - "GetOccurrenceNote": { - "methods": [ - "get_occurrence_note" - ] - }, - "ListNoteOccurrences": { - "methods": [ - "list_note_occurrences" - ] - }, - "ListNotes": { - "methods": [ - "list_notes" - ] - }, - "ListOccurrences": { - "methods": [ - "list_occurrences" - ] - }, - "UpdateNote": { - "methods": [ - "update_note" - ] - }, - "UpdateOccurrence": { - "methods": [ - "update_occurrence" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/gapic_version.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/grafeas/v1/grafeas/grafeas_v1/py.typed b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/py.typed deleted file mode 100644 index 49e8f71d60b7..000000000000 --- a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The grafeas package uses inline types. diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/__init__.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/grafeas/v1/grafeas/grafeas_v1/services/grafeas/__init__.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/__init__.py deleted file mode 100644 index b1d682230d78..000000000000 --- a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 GrafeasClient -from .async_client import GrafeasAsyncClient - -__all__ = ( - 'GrafeasClient', - 'GrafeasAsyncClient', -) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/async_client.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/async_client.py deleted file mode 100644 index 764b1ddf1932..000000000000 --- a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/async_client.py +++ /dev/null @@ -1,1886 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 grafeas.grafeas_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 - - -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 timestamp_pb2 # type: ignore -from grafeas.grafeas_v1.services.grafeas import pagers -from grafeas.grafeas_v1.types import attestation -from grafeas.grafeas_v1.types import build -from grafeas.grafeas_v1.types import common -from grafeas.grafeas_v1.types import compliance -from grafeas.grafeas_v1.types import deployment -from grafeas.grafeas_v1.types import discovery -from grafeas.grafeas_v1.types import dsse_attestation -from grafeas.grafeas_v1.types import grafeas -from grafeas.grafeas_v1.types import image -from grafeas.grafeas_v1.types import package -from grafeas.grafeas_v1.types import sbom -from grafeas.grafeas_v1.types import upgrade -from grafeas.grafeas_v1.types import vex -from grafeas.grafeas_v1.types import vulnerability -from .transports.base import GrafeasTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import GrafeasGrpcAsyncIOTransport -from .client import GrafeasClient - -try: - from google.api_core import client_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 GrafeasAsyncClient: - """`Grafeas `__ API. - - Retrieves analysis results of Cloud components such as Docker - container images. - - Analysis results are stored as a series of occurrences. An - ``Occurrence`` contains information about a specific analysis - instance on a resource. An occurrence refers to a ``Note``. A note - contains details describing the analysis and is generally stored in - a separate project, called a ``Provider``. Multiple occurrences can - refer to the same note. - - For example, an SSL vulnerability could affect multiple images. In - this case, there would be one note for the vulnerability and an - occurrence for each image with the vulnerability referring to that - note. - """ - - _client: GrafeasClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = GrafeasClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = GrafeasClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = GrafeasClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = GrafeasClient._DEFAULT_UNIVERSE - - note_path = staticmethod(GrafeasClient.note_path) - parse_note_path = staticmethod(GrafeasClient.parse_note_path) - occurrence_path = staticmethod(GrafeasClient.occurrence_path) - parse_occurrence_path = staticmethod(GrafeasClient.parse_occurrence_path) - project_path = staticmethod(GrafeasClient.project_path) - parse_project_path = staticmethod(GrafeasClient.parse_project_path) - common_billing_account_path = staticmethod(GrafeasClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(GrafeasClient.parse_common_billing_account_path) - common_folder_path = staticmethod(GrafeasClient.common_folder_path) - parse_common_folder_path = staticmethod(GrafeasClient.parse_common_folder_path) - common_organization_path = staticmethod(GrafeasClient.common_organization_path) - parse_common_organization_path = staticmethod(GrafeasClient.parse_common_organization_path) - common_project_path = staticmethod(GrafeasClient.common_project_path) - parse_common_project_path = staticmethod(GrafeasClient.parse_common_project_path) - common_location_path = staticmethod(GrafeasClient.common_location_path) - parse_common_location_path = staticmethod(GrafeasClient.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: - GrafeasAsyncClient: The constructed client. - """ - return GrafeasClient.from_service_account_info.__func__(GrafeasAsyncClient, 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: - GrafeasAsyncClient: The constructed client. - """ - return GrafeasClient.from_service_account_file.__func__(GrafeasAsyncClient, 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 GrafeasClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> GrafeasTransport: - """Returns the transport used by the client instance. - - Returns: - GrafeasTransport: 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 = GrafeasClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, GrafeasTransport, Callable[..., GrafeasTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the grafeas 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,GrafeasTransport,Callable[..., GrafeasTransport]]]): - 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 GrafeasTransport 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 = GrafeasClient( - 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 `grafeas_v1.GrafeasAsyncClient`.", - extra = { - "serviceName": "grafeas.v1.Grafeas", - "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": "grafeas.v1.Grafeas", - "credentialsType": None, - } - ) - - async def get_occurrence(self, - request: Optional[Union[grafeas.GetOccurrenceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> grafeas.Occurrence: - r"""Gets the specified occurrence. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - async def sample_get_occurrence(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.GetOccurrenceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_occurrence(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[grafeas.grafeas_v1.types.GetOccurrenceRequest, dict]]): - The request object. Request to get an occurrence. - name (:class:`str`): - The name of the occurrence in the form of - ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_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: - grafeas.grafeas_v1.types.Occurrence: - An instance of an analysis type that - has been found on a 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.GetOccurrenceRequest): - request = grafeas.GetOccurrenceRequest(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_occurrence] - - # Certain 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_occurrences(self, - request: Optional[Union[grafeas.ListOccurrencesRequest, dict]] = None, - *, - parent: Optional[str] = None, - filter: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListOccurrencesAsyncPager: - r"""Lists occurrences for the specified project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - async def sample_list_occurrences(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.ListOccurrencesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_occurrences(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[grafeas.grafeas_v1.types.ListOccurrencesRequest, dict]]): - The request object. Request to list occurrences. - parent (:class:`str`): - The name of the project to list occurrences for in the - form of ``projects/[PROJECT_ID]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (:class:`str`): - The filter expression. - This corresponds to the ``filter`` 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: - grafeas.grafeas_v1.services.grafeas.pagers.ListOccurrencesAsyncPager: - Response for listing occurrences. - - 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. - has_flattened_params = any([parent, filter]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.ListOccurrencesRequest): - request = grafeas.ListOccurrencesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if filter is not None: - request.filter = filter - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_occurrences] - - # Certain 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.ListOccurrencesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_occurrence(self, - request: Optional[Union[grafeas.DeleteOccurrenceRequest, dict]] = None, - *, - name: Optional[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 occurrence. For example, use - this method to delete an occurrence when the occurrence - is no longer applicable for the given resource. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - async def sample_delete_occurrence(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.DeleteOccurrenceRequest( - name="name_value", - ) - - # Make the request - await client.delete_occurrence(request=request) - - Args: - request (Optional[Union[grafeas.grafeas_v1.types.DeleteOccurrenceRequest, dict]]): - The request object. Request to delete an occurrence. - name (:class:`str`): - The name of the occurrence in the form of - ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_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`. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.DeleteOccurrenceRequest): - request = grafeas.DeleteOccurrenceRequest(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_occurrence] - - # Certain 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 create_occurrence(self, - request: Optional[Union[grafeas.CreateOccurrenceRequest, dict]] = None, - *, - parent: Optional[str] = None, - occurrence: Optional[grafeas.Occurrence] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> grafeas.Occurrence: - r"""Creates a new occurrence. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - async def sample_create_occurrence(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.CreateOccurrenceRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_occurrence(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[grafeas.grafeas_v1.types.CreateOccurrenceRequest, dict]]): - The request object. Request to create a new occurrence. - parent (:class:`str`): - The name of the project in the form of - ``projects/[PROJECT_ID]``, under which the occurrence is - to be created. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - occurrence (:class:`grafeas.grafeas_v1.types.Occurrence`): - The occurrence to create. - This corresponds to the ``occurrence`` 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: - grafeas.grafeas_v1.types.Occurrence: - An instance of an analysis type that - has been found on a 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. - has_flattened_params = any([parent, occurrence]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.CreateOccurrenceRequest): - request = grafeas.CreateOccurrenceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if occurrence is not None: - request.occurrence = occurrence - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_occurrence] - - # Certain 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 batch_create_occurrences(self, - request: Optional[Union[grafeas.BatchCreateOccurrencesRequest, dict]] = None, - *, - parent: Optional[str] = None, - occurrences: Optional[MutableSequence[grafeas.Occurrence]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> grafeas.BatchCreateOccurrencesResponse: - r"""Creates new occurrences in batch. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - async def sample_batch_create_occurrences(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.BatchCreateOccurrencesRequest( - parent="parent_value", - ) - - # Make the request - response = await client.batch_create_occurrences(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[grafeas.grafeas_v1.types.BatchCreateOccurrencesRequest, dict]]): - The request object. Request to create occurrences in - batch. - parent (:class:`str`): - The name of the project in the form of - ``projects/[PROJECT_ID]``, under which the occurrences - are to be created. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - occurrences (:class:`MutableSequence[grafeas.grafeas_v1.types.Occurrence]`): - The occurrences to create. Max - allowed length is 1000. - - This corresponds to the ``occurrences`` 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: - grafeas.grafeas_v1.types.BatchCreateOccurrencesResponse: - Response for creating occurrences in - batch. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, occurrences]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.BatchCreateOccurrencesRequest): - request = grafeas.BatchCreateOccurrencesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if occurrences: - request.occurrences.extend(occurrences) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.batch_create_occurrences] - - # Certain 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_occurrence(self, - request: Optional[Union[grafeas.UpdateOccurrenceRequest, dict]] = None, - *, - name: Optional[str] = None, - occurrence: Optional[grafeas.Occurrence] = 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]]] = (), - ) -> grafeas.Occurrence: - r"""Updates the specified occurrence. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - async def sample_update_occurrence(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.UpdateOccurrenceRequest( - name="name_value", - ) - - # Make the request - response = await client.update_occurrence(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[grafeas.grafeas_v1.types.UpdateOccurrenceRequest, dict]]): - The request object. Request to update an occurrence. - name (:class:`str`): - The name of the occurrence in the form of - ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - occurrence (:class:`grafeas.grafeas_v1.types.Occurrence`): - The updated occurrence. - This corresponds to the ``occurrence`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The fields to update. - 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: - grafeas.grafeas_v1.types.Occurrence: - An instance of an analysis type that - has been found on a 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. - has_flattened_params = any([name, occurrence, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.UpdateOccurrenceRequest): - request = grafeas.UpdateOccurrenceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if occurrence is not None: - request.occurrence = occurrence - 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_occurrence] - - # Certain 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_occurrence_note(self, - request: Optional[Union[grafeas.GetOccurrenceNoteRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> grafeas.Note: - r"""Gets the note attached to the specified occurrence. - Consumer projects can use this method to get a note that - belongs to a provider project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - async def sample_get_occurrence_note(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.GetOccurrenceNoteRequest( - name="name_value", - ) - - # Make the request - response = await client.get_occurrence_note(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[grafeas.grafeas_v1.types.GetOccurrenceNoteRequest, dict]]): - The request object. Request to get the note to which the - specified occurrence is attached. - name (:class:`str`): - The name of the occurrence in the form of - ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_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: - grafeas.grafeas_v1.types.Note: - A type of analysis that can be done - for a 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.GetOccurrenceNoteRequest): - request = grafeas.GetOccurrenceNoteRequest(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_occurrence_note] - - # Certain 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_note(self, - request: Optional[Union[grafeas.GetNoteRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> grafeas.Note: - r"""Gets the specified note. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - async def sample_get_note(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.GetNoteRequest( - name="name_value", - ) - - # Make the request - response = await client.get_note(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[grafeas.grafeas_v1.types.GetNoteRequest, dict]]): - The request object. Request to get a note. - name (:class:`str`): - The name of the note in the form of - ``projects/[PROVIDER_ID]/notes/[NOTE_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: - grafeas.grafeas_v1.types.Note: - A type of analysis that can be done - for a 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.GetNoteRequest): - request = grafeas.GetNoteRequest(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_note] - - # Certain 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_notes(self, - request: Optional[Union[grafeas.ListNotesRequest, dict]] = None, - *, - parent: Optional[str] = None, - filter: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListNotesAsyncPager: - r"""Lists notes for the specified project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - async def sample_list_notes(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.ListNotesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_notes(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[grafeas.grafeas_v1.types.ListNotesRequest, dict]]): - The request object. Request to list notes. - parent (:class:`str`): - The name of the project to list notes for in the form of - ``projects/[PROJECT_ID]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (:class:`str`): - The filter expression. - This corresponds to the ``filter`` 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: - grafeas.grafeas_v1.services.grafeas.pagers.ListNotesAsyncPager: - Response for listing notes. - - 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. - has_flattened_params = any([parent, filter]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.ListNotesRequest): - request = grafeas.ListNotesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if filter is not None: - request.filter = filter - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_notes] - - # Certain 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.ListNotesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_note(self, - request: Optional[Union[grafeas.DeleteNoteRequest, dict]] = None, - *, - name: Optional[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 note. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - async def sample_delete_note(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.DeleteNoteRequest( - name="name_value", - ) - - # Make the request - await client.delete_note(request=request) - - Args: - request (Optional[Union[grafeas.grafeas_v1.types.DeleteNoteRequest, dict]]): - The request object. Request to delete a note. - name (:class:`str`): - The name of the note in the form of - ``projects/[PROVIDER_ID]/notes/[NOTE_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`. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.DeleteNoteRequest): - request = grafeas.DeleteNoteRequest(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_note] - - # Certain 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 create_note(self, - request: Optional[Union[grafeas.CreateNoteRequest, dict]] = None, - *, - parent: Optional[str] = None, - note_id: Optional[str] = None, - note: Optional[grafeas.Note] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> grafeas.Note: - r"""Creates a new note. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - async def sample_create_note(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.CreateNoteRequest( - parent="parent_value", - note_id="note_id_value", - ) - - # Make the request - response = await client.create_note(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[grafeas.grafeas_v1.types.CreateNoteRequest, dict]]): - The request object. Request to create a new note. - parent (:class:`str`): - The name of the project in the form of - ``projects/[PROJECT_ID]``, under which the note is to be - created. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - note_id (:class:`str`): - The ID to use for this note. - This corresponds to the ``note_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - note (:class:`grafeas.grafeas_v1.types.Note`): - The note to create. - This corresponds to the ``note`` 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: - grafeas.grafeas_v1.types.Note: - A type of analysis that can be done - for a 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. - has_flattened_params = any([parent, note_id, note]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.CreateNoteRequest): - request = grafeas.CreateNoteRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if note_id is not None: - request.note_id = note_id - if note is not None: - request.note = note - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_note] - - # Certain 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 batch_create_notes(self, - request: Optional[Union[grafeas.BatchCreateNotesRequest, dict]] = None, - *, - parent: Optional[str] = None, - notes: Optional[MutableMapping[str, grafeas.Note]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> grafeas.BatchCreateNotesResponse: - r"""Creates new notes in batch. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - async def sample_batch_create_notes(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.BatchCreateNotesRequest( - parent="parent_value", - ) - - # Make the request - response = await client.batch_create_notes(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[grafeas.grafeas_v1.types.BatchCreateNotesRequest, dict]]): - The request object. Request to create notes in batch. - parent (:class:`str`): - The name of the project in the form of - ``projects/[PROJECT_ID]``, under which the notes are to - be created. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - notes (:class:`MutableMapping[str, grafeas.grafeas_v1.types.Note]`): - The notes to create. Max allowed - length is 1000. - - This corresponds to the ``notes`` 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: - grafeas.grafeas_v1.types.BatchCreateNotesResponse: - Response for creating notes in batch. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, notes]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.BatchCreateNotesRequest): - request = grafeas.BatchCreateNotesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - if notes: - request.notes.update(notes) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.batch_create_notes] - - # Certain 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_note(self, - request: Optional[Union[grafeas.UpdateNoteRequest, dict]] = None, - *, - name: Optional[str] = None, - note: Optional[grafeas.Note] = 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]]] = (), - ) -> grafeas.Note: - r"""Updates the specified note. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - async def sample_update_note(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.UpdateNoteRequest( - name="name_value", - ) - - # Make the request - response = await client.update_note(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[grafeas.grafeas_v1.types.UpdateNoteRequest, dict]]): - The request object. Request to update a note. - name (:class:`str`): - The name of the note in the form of - ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - note (:class:`grafeas.grafeas_v1.types.Note`): - The updated note. - This corresponds to the ``note`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The fields to update. - 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: - grafeas.grafeas_v1.types.Note: - A type of analysis that can be done - for a 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. - has_flattened_params = any([name, note, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.UpdateNoteRequest): - request = grafeas.UpdateNoteRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if note is not None: - request.note = note - 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_note] - - # Certain 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_note_occurrences(self, - request: Optional[Union[grafeas.ListNoteOccurrencesRequest, dict]] = None, - *, - name: Optional[str] = None, - filter: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListNoteOccurrencesAsyncPager: - r"""Lists occurrences referencing the specified note. - Provider projects can use this method to get all - occurrences across consumer projects referencing the - specified note. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - async def sample_list_note_occurrences(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.ListNoteOccurrencesRequest( - name="name_value", - ) - - # Make the request - page_result = client.list_note_occurrences(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[grafeas.grafeas_v1.types.ListNoteOccurrencesRequest, dict]]): - The request object. Request to list occurrences for a - note. - name (:class:`str`): - The name of the note to list occurrences for in the form - of ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (:class:`str`): - The filter expression. - This corresponds to the ``filter`` 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: - grafeas.grafeas_v1.services.grafeas.pagers.ListNoteOccurrencesAsyncPager: - Response for listing occurrences for - a note. - 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. - has_flattened_params = any([name, filter]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.ListNoteOccurrencesRequest): - request = grafeas.ListNoteOccurrencesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if filter is not None: - request.filter = filter - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_note_occurrences] - - # Certain 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, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListNoteOccurrencesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self) -> "GrafeasAsyncClient": - 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__) - - -__all__ = ( - "GrafeasAsyncClient", -) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/client.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/client.py deleted file mode 100644 index b8987a77daf1..000000000000 --- a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/client.py +++ /dev/null @@ -1,2225 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -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 grafeas.grafeas_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 - -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 timestamp_pb2 # type: ignore -from grafeas.grafeas_v1.services.grafeas import pagers -from grafeas.grafeas_v1.types import attestation -from grafeas.grafeas_v1.types import build -from grafeas.grafeas_v1.types import common -from grafeas.grafeas_v1.types import compliance -from grafeas.grafeas_v1.types import deployment -from grafeas.grafeas_v1.types import discovery -from grafeas.grafeas_v1.types import dsse_attestation -from grafeas.grafeas_v1.types import grafeas -from grafeas.grafeas_v1.types import image -from grafeas.grafeas_v1.types import package -from grafeas.grafeas_v1.types import sbom -from grafeas.grafeas_v1.types import upgrade -from grafeas.grafeas_v1.types import vex -from grafeas.grafeas_v1.types import vulnerability -from .transports.base import GrafeasTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import GrafeasGrpcTransport -from .transports.grpc_asyncio import GrafeasGrpcAsyncIOTransport -from .transports.rest import GrafeasRestTransport - - -class GrafeasClientMeta(type): - """Metaclass for the Grafeas 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[GrafeasTransport]] - _transport_registry["grpc"] = GrafeasGrpcTransport - _transport_registry["grpc_asyncio"] = GrafeasGrpcAsyncIOTransport - _transport_registry["rest"] = GrafeasRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[GrafeasTransport]: - """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 GrafeasClient(metaclass=GrafeasClientMeta): - """`Grafeas `__ API. - - Retrieves analysis results of Cloud components such as Docker - container images. - - Analysis results are stored as a series of occurrences. An - ``Occurrence`` contains information about a specific analysis - instance on a resource. An occurrence refers to a ``Note``. A note - contains details describing the analysis and is generally stored in - a separate project, called a ``Provider``. Multiple occurrences can - refer to the same note. - - For example, an SSL vulnerability could affect multiple images. In - this case, there would be one note for the vulnerability and an - occurrence for each image with the vulnerability referring to that - note. - """ - - @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 = "containeranalysis.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "containeranalysis.{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: - GrafeasClient: 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: - GrafeasClient: 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) -> GrafeasTransport: - """Returns the transport used by the client instance. - - Returns: - GrafeasTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def note_path(project: str,note: str,) -> str: - """Returns a fully-qualified note string.""" - return "projects/{project}/notes/{note}".format(project=project, note=note, ) - - @staticmethod - def parse_note_path(path: str) -> Dict[str,str]: - """Parses a note path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/notes/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def occurrence_path(project: str,occurrence: str,) -> str: - """Returns a fully-qualified occurrence string.""" - return "projects/{project}/occurrences/{occurrence}".format(project=project, occurrence=occurrence, ) - - @staticmethod - def parse_occurrence_path(path: str) -> Dict[str,str]: - """Parses a occurrence path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/occurrences/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def project_path(project: str,) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_project_path(path: str) -> Dict[str,str]: - """Parses a project path into its component segments.""" - m = re.match(r"^projects/(?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 = GrafeasClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = GrafeasClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = GrafeasClient._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 = GrafeasClient._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 - - @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, GrafeasTransport, Callable[..., GrafeasTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the grafeas 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,GrafeasTransport,Callable[..., GrafeasTransport]]]): - 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 GrafeasTransport 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 = GrafeasClient._read_environment_variables() - self._client_cert_source = GrafeasClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = GrafeasClient._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, GrafeasTransport) - if transport_provided: - # transport is a GrafeasTransport 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(GrafeasTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - GrafeasClient._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[GrafeasTransport], Callable[..., GrafeasTransport]] = ( - GrafeasClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., GrafeasTransport], 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 `grafeas_v1.GrafeasClient`.", - extra = { - "serviceName": "grafeas.v1.Grafeas", - "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": "grafeas.v1.Grafeas", - "credentialsType": None, - } - ) - - def get_occurrence(self, - request: Optional[Union[grafeas.GetOccurrenceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> grafeas.Occurrence: - r"""Gets the specified occurrence. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - def sample_get_occurrence(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.GetOccurrenceRequest( - name="name_value", - ) - - # Make the request - response = client.get_occurrence(request=request) - - # Handle the response - print(response) - - Args: - request (Union[grafeas.grafeas_v1.types.GetOccurrenceRequest, dict]): - The request object. Request to get an occurrence. - name (str): - The name of the occurrence in the form of - ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_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: - grafeas.grafeas_v1.types.Occurrence: - An instance of an analysis type that - has been found on a 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.GetOccurrenceRequest): - request = grafeas.GetOccurrenceRequest(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_occurrence] - - # Certain 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_occurrences(self, - request: Optional[Union[grafeas.ListOccurrencesRequest, dict]] = None, - *, - parent: Optional[str] = None, - filter: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListOccurrencesPager: - r"""Lists occurrences for the specified project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - def sample_list_occurrences(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.ListOccurrencesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_occurrences(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[grafeas.grafeas_v1.types.ListOccurrencesRequest, dict]): - The request object. Request to list occurrences. - parent (str): - The name of the project to list occurrences for in the - form of ``projects/[PROJECT_ID]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (str): - The filter expression. - This corresponds to the ``filter`` 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: - grafeas.grafeas_v1.services.grafeas.pagers.ListOccurrencesPager: - Response for listing occurrences. - - 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. - has_flattened_params = any([parent, filter]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.ListOccurrencesRequest): - request = grafeas.ListOccurrencesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if filter is not None: - request.filter = filter - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_occurrences] - - # Certain 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.ListOccurrencesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_occurrence(self, - request: Optional[Union[grafeas.DeleteOccurrenceRequest, dict]] = None, - *, - name: Optional[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 occurrence. For example, use - this method to delete an occurrence when the occurrence - is no longer applicable for the given resource. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - def sample_delete_occurrence(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.DeleteOccurrenceRequest( - name="name_value", - ) - - # Make the request - client.delete_occurrence(request=request) - - Args: - request (Union[grafeas.grafeas_v1.types.DeleteOccurrenceRequest, dict]): - The request object. Request to delete an occurrence. - name (str): - The name of the occurrence in the form of - ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_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`. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.DeleteOccurrenceRequest): - request = grafeas.DeleteOccurrenceRequest(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_occurrence] - - # Certain 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 create_occurrence(self, - request: Optional[Union[grafeas.CreateOccurrenceRequest, dict]] = None, - *, - parent: Optional[str] = None, - occurrence: Optional[grafeas.Occurrence] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> grafeas.Occurrence: - r"""Creates a new occurrence. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - def sample_create_occurrence(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.CreateOccurrenceRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_occurrence(request=request) - - # Handle the response - print(response) - - Args: - request (Union[grafeas.grafeas_v1.types.CreateOccurrenceRequest, dict]): - The request object. Request to create a new occurrence. - parent (str): - The name of the project in the form of - ``projects/[PROJECT_ID]``, under which the occurrence is - to be created. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - occurrence (grafeas.grafeas_v1.types.Occurrence): - The occurrence to create. - This corresponds to the ``occurrence`` 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: - grafeas.grafeas_v1.types.Occurrence: - An instance of an analysis type that - has been found on a 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. - has_flattened_params = any([parent, occurrence]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.CreateOccurrenceRequest): - request = grafeas.CreateOccurrenceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if occurrence is not None: - request.occurrence = occurrence - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_occurrence] - - # Certain 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 batch_create_occurrences(self, - request: Optional[Union[grafeas.BatchCreateOccurrencesRequest, dict]] = None, - *, - parent: Optional[str] = None, - occurrences: Optional[MutableSequence[grafeas.Occurrence]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> grafeas.BatchCreateOccurrencesResponse: - r"""Creates new occurrences in batch. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - def sample_batch_create_occurrences(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.BatchCreateOccurrencesRequest( - parent="parent_value", - ) - - # Make the request - response = client.batch_create_occurrences(request=request) - - # Handle the response - print(response) - - Args: - request (Union[grafeas.grafeas_v1.types.BatchCreateOccurrencesRequest, dict]): - The request object. Request to create occurrences in - batch. - parent (str): - The name of the project in the form of - ``projects/[PROJECT_ID]``, under which the occurrences - are to be created. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - occurrences (MutableSequence[grafeas.grafeas_v1.types.Occurrence]): - The occurrences to create. Max - allowed length is 1000. - - This corresponds to the ``occurrences`` 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: - grafeas.grafeas_v1.types.BatchCreateOccurrencesResponse: - Response for creating occurrences in - batch. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, occurrences]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.BatchCreateOccurrencesRequest): - request = grafeas.BatchCreateOccurrencesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if occurrences is not None: - request.occurrences = occurrences - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.batch_create_occurrences] - - # Certain 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_occurrence(self, - request: Optional[Union[grafeas.UpdateOccurrenceRequest, dict]] = None, - *, - name: Optional[str] = None, - occurrence: Optional[grafeas.Occurrence] = 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]]] = (), - ) -> grafeas.Occurrence: - r"""Updates the specified occurrence. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - def sample_update_occurrence(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.UpdateOccurrenceRequest( - name="name_value", - ) - - # Make the request - response = client.update_occurrence(request=request) - - # Handle the response - print(response) - - Args: - request (Union[grafeas.grafeas_v1.types.UpdateOccurrenceRequest, dict]): - The request object. Request to update an occurrence. - name (str): - The name of the occurrence in the form of - ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - occurrence (grafeas.grafeas_v1.types.Occurrence): - The updated occurrence. - This corresponds to the ``occurrence`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The fields to update. - 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: - grafeas.grafeas_v1.types.Occurrence: - An instance of an analysis type that - has been found on a 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. - has_flattened_params = any([name, occurrence, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.UpdateOccurrenceRequest): - request = grafeas.UpdateOccurrenceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if occurrence is not None: - request.occurrence = occurrence - 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_occurrence] - - # Certain 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_occurrence_note(self, - request: Optional[Union[grafeas.GetOccurrenceNoteRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> grafeas.Note: - r"""Gets the note attached to the specified occurrence. - Consumer projects can use this method to get a note that - belongs to a provider project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - def sample_get_occurrence_note(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.GetOccurrenceNoteRequest( - name="name_value", - ) - - # Make the request - response = client.get_occurrence_note(request=request) - - # Handle the response - print(response) - - Args: - request (Union[grafeas.grafeas_v1.types.GetOccurrenceNoteRequest, dict]): - The request object. Request to get the note to which the - specified occurrence is attached. - name (str): - The name of the occurrence in the form of - ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_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: - grafeas.grafeas_v1.types.Note: - A type of analysis that can be done - for a 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.GetOccurrenceNoteRequest): - request = grafeas.GetOccurrenceNoteRequest(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_occurrence_note] - - # Certain 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_note(self, - request: Optional[Union[grafeas.GetNoteRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> grafeas.Note: - r"""Gets the specified note. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - def sample_get_note(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.GetNoteRequest( - name="name_value", - ) - - # Make the request - response = client.get_note(request=request) - - # Handle the response - print(response) - - Args: - request (Union[grafeas.grafeas_v1.types.GetNoteRequest, dict]): - The request object. Request to get a note. - name (str): - The name of the note in the form of - ``projects/[PROVIDER_ID]/notes/[NOTE_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: - grafeas.grafeas_v1.types.Note: - A type of analysis that can be done - for a 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.GetNoteRequest): - request = grafeas.GetNoteRequest(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_note] - - # Certain 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_notes(self, - request: Optional[Union[grafeas.ListNotesRequest, dict]] = None, - *, - parent: Optional[str] = None, - filter: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListNotesPager: - r"""Lists notes for the specified project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - def sample_list_notes(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.ListNotesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_notes(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[grafeas.grafeas_v1.types.ListNotesRequest, dict]): - The request object. Request to list notes. - parent (str): - The name of the project to list notes for in the form of - ``projects/[PROJECT_ID]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (str): - The filter expression. - This corresponds to the ``filter`` 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: - grafeas.grafeas_v1.services.grafeas.pagers.ListNotesPager: - Response for listing notes. - - 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. - has_flattened_params = any([parent, filter]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.ListNotesRequest): - request = grafeas.ListNotesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if filter is not None: - request.filter = filter - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_notes] - - # Certain 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.ListNotesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_note(self, - request: Optional[Union[grafeas.DeleteNoteRequest, dict]] = None, - *, - name: Optional[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 note. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - def sample_delete_note(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.DeleteNoteRequest( - name="name_value", - ) - - # Make the request - client.delete_note(request=request) - - Args: - request (Union[grafeas.grafeas_v1.types.DeleteNoteRequest, dict]): - The request object. Request to delete a note. - name (str): - The name of the note in the form of - ``projects/[PROVIDER_ID]/notes/[NOTE_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`. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.DeleteNoteRequest): - request = grafeas.DeleteNoteRequest(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_note] - - # Certain 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 create_note(self, - request: Optional[Union[grafeas.CreateNoteRequest, dict]] = None, - *, - parent: Optional[str] = None, - note_id: Optional[str] = None, - note: Optional[grafeas.Note] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> grafeas.Note: - r"""Creates a new note. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - def sample_create_note(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.CreateNoteRequest( - parent="parent_value", - note_id="note_id_value", - ) - - # Make the request - response = client.create_note(request=request) - - # Handle the response - print(response) - - Args: - request (Union[grafeas.grafeas_v1.types.CreateNoteRequest, dict]): - The request object. Request to create a new note. - parent (str): - The name of the project in the form of - ``projects/[PROJECT_ID]``, under which the note is to be - created. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - note_id (str): - The ID to use for this note. - This corresponds to the ``note_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - note (grafeas.grafeas_v1.types.Note): - The note to create. - This corresponds to the ``note`` 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: - grafeas.grafeas_v1.types.Note: - A type of analysis that can be done - for a 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. - has_flattened_params = any([parent, note_id, note]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.CreateNoteRequest): - request = grafeas.CreateNoteRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if note_id is not None: - request.note_id = note_id - if note is not None: - request.note = note - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_note] - - # Certain 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 batch_create_notes(self, - request: Optional[Union[grafeas.BatchCreateNotesRequest, dict]] = None, - *, - parent: Optional[str] = None, - notes: Optional[MutableMapping[str, grafeas.Note]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> grafeas.BatchCreateNotesResponse: - r"""Creates new notes in batch. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - def sample_batch_create_notes(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.BatchCreateNotesRequest( - parent="parent_value", - ) - - # Make the request - response = client.batch_create_notes(request=request) - - # Handle the response - print(response) - - Args: - request (Union[grafeas.grafeas_v1.types.BatchCreateNotesRequest, dict]): - The request object. Request to create notes in batch. - parent (str): - The name of the project in the form of - ``projects/[PROJECT_ID]``, under which the notes are to - be created. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - notes (MutableMapping[str, grafeas.grafeas_v1.types.Note]): - The notes to create. Max allowed - length is 1000. - - This corresponds to the ``notes`` 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: - grafeas.grafeas_v1.types.BatchCreateNotesResponse: - Response for creating notes in batch. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, notes]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.BatchCreateNotesRequest): - request = grafeas.BatchCreateNotesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if notes is not None: - request.notes = notes - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.batch_create_notes] - - # Certain 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_note(self, - request: Optional[Union[grafeas.UpdateNoteRequest, dict]] = None, - *, - name: Optional[str] = None, - note: Optional[grafeas.Note] = 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]]] = (), - ) -> grafeas.Note: - r"""Updates the specified note. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - def sample_update_note(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.UpdateNoteRequest( - name="name_value", - ) - - # Make the request - response = client.update_note(request=request) - - # Handle the response - print(response) - - Args: - request (Union[grafeas.grafeas_v1.types.UpdateNoteRequest, dict]): - The request object. Request to update a note. - name (str): - The name of the note in the form of - ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - note (grafeas.grafeas_v1.types.Note): - The updated note. - This corresponds to the ``note`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The fields to update. - 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: - grafeas.grafeas_v1.types.Note: - A type of analysis that can be done - for a 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. - has_flattened_params = any([name, note, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.UpdateNoteRequest): - request = grafeas.UpdateNoteRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if note is not None: - request.note = note - 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_note] - - # Certain 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_note_occurrences(self, - request: Optional[Union[grafeas.ListNoteOccurrencesRequest, dict]] = None, - *, - name: Optional[str] = None, - filter: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListNoteOccurrencesPager: - r"""Lists occurrences referencing the specified note. - Provider projects can use this method to get all - occurrences across consumer projects referencing the - specified note. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - def sample_list_note_occurrences(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.ListNoteOccurrencesRequest( - name="name_value", - ) - - # Make the request - page_result = client.list_note_occurrences(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[grafeas.grafeas_v1.types.ListNoteOccurrencesRequest, dict]): - The request object. Request to list occurrences for a - note. - name (str): - The name of the note to list occurrences for in the form - of ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (str): - The filter expression. - This corresponds to the ``filter`` 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: - grafeas.grafeas_v1.services.grafeas.pagers.ListNoteOccurrencesPager: - Response for listing occurrences for - a note. - 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. - has_flattened_params = any([name, filter]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.ListNoteOccurrencesRequest): - request = grafeas.ListNoteOccurrencesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if filter is not None: - request.filter = filter - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_note_occurrences] - - # Certain 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, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListNoteOccurrencesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "GrafeasClient": - 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__) - - -__all__ = ( - "GrafeasClient", -) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/pagers.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/pagers.py deleted file mode 100644 index e568551ef27e..000000000000 --- a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/pagers.py +++ /dev/null @@ -1,444 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 grafeas.grafeas_v1.types import grafeas - - -class ListOccurrencesPager: - """A pager for iterating through ``list_occurrences`` requests. - - This class thinly wraps an initial - :class:`grafeas.grafeas_v1.types.ListOccurrencesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``occurrences`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListOccurrences`` requests and continue to iterate - through the ``occurrences`` field on the - corresponding responses. - - All the usual :class:`grafeas.grafeas_v1.types.ListOccurrencesResponse` - 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[..., grafeas.ListOccurrencesResponse], - request: grafeas.ListOccurrencesRequest, - response: grafeas.ListOccurrencesResponse, - *, - 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 (grafeas.grafeas_v1.types.ListOccurrencesRequest): - The initial request object. - response (grafeas.grafeas_v1.types.ListOccurrencesResponse): - 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 = grafeas.ListOccurrencesRequest(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[grafeas.ListOccurrencesResponse]: - 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[grafeas.Occurrence]: - for page in self.pages: - yield from page.occurrences - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListOccurrencesAsyncPager: - """A pager for iterating through ``list_occurrences`` requests. - - This class thinly wraps an initial - :class:`grafeas.grafeas_v1.types.ListOccurrencesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``occurrences`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListOccurrences`` requests and continue to iterate - through the ``occurrences`` field on the - corresponding responses. - - All the usual :class:`grafeas.grafeas_v1.types.ListOccurrencesResponse` - 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[grafeas.ListOccurrencesResponse]], - request: grafeas.ListOccurrencesRequest, - response: grafeas.ListOccurrencesResponse, - *, - 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 (grafeas.grafeas_v1.types.ListOccurrencesRequest): - The initial request object. - response (grafeas.grafeas_v1.types.ListOccurrencesResponse): - 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 = grafeas.ListOccurrencesRequest(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[grafeas.ListOccurrencesResponse]: - 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[grafeas.Occurrence]: - async def async_generator(): - async for page in self.pages: - for response in page.occurrences: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListNotesPager: - """A pager for iterating through ``list_notes`` requests. - - This class thinly wraps an initial - :class:`grafeas.grafeas_v1.types.ListNotesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``notes`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListNotes`` requests and continue to iterate - through the ``notes`` field on the - corresponding responses. - - All the usual :class:`grafeas.grafeas_v1.types.ListNotesResponse` - 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[..., grafeas.ListNotesResponse], - request: grafeas.ListNotesRequest, - response: grafeas.ListNotesResponse, - *, - 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 (grafeas.grafeas_v1.types.ListNotesRequest): - The initial request object. - response (grafeas.grafeas_v1.types.ListNotesResponse): - 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 = grafeas.ListNotesRequest(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[grafeas.ListNotesResponse]: - 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[grafeas.Note]: - for page in self.pages: - yield from page.notes - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListNotesAsyncPager: - """A pager for iterating through ``list_notes`` requests. - - This class thinly wraps an initial - :class:`grafeas.grafeas_v1.types.ListNotesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``notes`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListNotes`` requests and continue to iterate - through the ``notes`` field on the - corresponding responses. - - All the usual :class:`grafeas.grafeas_v1.types.ListNotesResponse` - 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[grafeas.ListNotesResponse]], - request: grafeas.ListNotesRequest, - response: grafeas.ListNotesResponse, - *, - 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 (grafeas.grafeas_v1.types.ListNotesRequest): - The initial request object. - response (grafeas.grafeas_v1.types.ListNotesResponse): - 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 = grafeas.ListNotesRequest(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[grafeas.ListNotesResponse]: - 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[grafeas.Note]: - async def async_generator(): - async for page in self.pages: - for response in page.notes: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListNoteOccurrencesPager: - """A pager for iterating through ``list_note_occurrences`` requests. - - This class thinly wraps an initial - :class:`grafeas.grafeas_v1.types.ListNoteOccurrencesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``occurrences`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListNoteOccurrences`` requests and continue to iterate - through the ``occurrences`` field on the - corresponding responses. - - All the usual :class:`grafeas.grafeas_v1.types.ListNoteOccurrencesResponse` - 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[..., grafeas.ListNoteOccurrencesResponse], - request: grafeas.ListNoteOccurrencesRequest, - response: grafeas.ListNoteOccurrencesResponse, - *, - 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 (grafeas.grafeas_v1.types.ListNoteOccurrencesRequest): - The initial request object. - response (grafeas.grafeas_v1.types.ListNoteOccurrencesResponse): - 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 = grafeas.ListNoteOccurrencesRequest(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[grafeas.ListNoteOccurrencesResponse]: - 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[grafeas.Occurrence]: - for page in self.pages: - yield from page.occurrences - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListNoteOccurrencesAsyncPager: - """A pager for iterating through ``list_note_occurrences`` requests. - - This class thinly wraps an initial - :class:`grafeas.grafeas_v1.types.ListNoteOccurrencesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``occurrences`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListNoteOccurrences`` requests and continue to iterate - through the ``occurrences`` field on the - corresponding responses. - - All the usual :class:`grafeas.grafeas_v1.types.ListNoteOccurrencesResponse` - 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[grafeas.ListNoteOccurrencesResponse]], - request: grafeas.ListNoteOccurrencesRequest, - response: grafeas.ListNoteOccurrencesResponse, - *, - 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 (grafeas.grafeas_v1.types.ListNoteOccurrencesRequest): - The initial request object. - response (grafeas.grafeas_v1.types.ListNoteOccurrencesResponse): - 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 = grafeas.ListNoteOccurrencesRequest(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[grafeas.ListNoteOccurrencesResponse]: - 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[grafeas.Occurrence]: - async def async_generator(): - async for page in self.pages: - for response in page.occurrences: - 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/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/README.rst b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/README.rst deleted file mode 100644 index 1085202fe2c8..000000000000 --- a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`GrafeasTransport` is the ABC for all transports. -- public child `GrafeasGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `GrafeasGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseGrafeasRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `GrafeasRestTransport` 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/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/__init__.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/__init__.py deleted file mode 100644 index af77bbdd97ec..000000000000 --- a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 GrafeasTransport -from .grpc import GrafeasGrpcTransport -from .grpc_asyncio import GrafeasGrpcAsyncIOTransport -from .rest import GrafeasRestTransport -from .rest import GrafeasRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[GrafeasTransport]] -_transport_registry['grpc'] = GrafeasGrpcTransport -_transport_registry['grpc_asyncio'] = GrafeasGrpcAsyncIOTransport -_transport_registry['rest'] = GrafeasRestTransport - -__all__ = ( - 'GrafeasTransport', - 'GrafeasGrpcTransport', - 'GrafeasGrpcAsyncIOTransport', - 'GrafeasRestTransport', - 'GrafeasRestInterceptor', -) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/base.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/base.py deleted file mode 100644 index 6fbf36ad7b3d..000000000000 --- a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/base.py +++ /dev/null @@ -1,416 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 grafeas.grafeas_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 - -from google.protobuf import empty_pb2 # type: ignore -from grafeas.grafeas_v1.types import grafeas - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class GrafeasTransport(abc.ABC): - """Abstract transport class for Grafeas.""" - - AUTH_SCOPES = ( - ) - - DEFAULT_HOST: str = 'containeranalysis.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: 'containeranalysis.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to 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_occurrence: gapic_v1.method.wrap_method( - self.get_occurrence, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.list_occurrences: gapic_v1.method.wrap_method( - self.list_occurrences, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.delete_occurrence: gapic_v1.method.wrap_method( - self.delete_occurrence, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.create_occurrence: gapic_v1.method.wrap_method( - self.create_occurrence, - default_timeout=30.0, - client_info=client_info, - ), - self.batch_create_occurrences: gapic_v1.method.wrap_method( - self.batch_create_occurrences, - default_timeout=30.0, - client_info=client_info, - ), - self.update_occurrence: gapic_v1.method.wrap_method( - self.update_occurrence, - default_timeout=30.0, - client_info=client_info, - ), - self.get_occurrence_note: gapic_v1.method.wrap_method( - self.get_occurrence_note, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.get_note: gapic_v1.method.wrap_method( - self.get_note, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.list_notes: gapic_v1.method.wrap_method( - self.list_notes, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.delete_note: gapic_v1.method.wrap_method( - self.delete_note, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.create_note: gapic_v1.method.wrap_method( - self.create_note, - default_timeout=30.0, - client_info=client_info, - ), - self.batch_create_notes: gapic_v1.method.wrap_method( - self.batch_create_notes, - default_timeout=30.0, - client_info=client_info, - ), - self.update_note: gapic_v1.method.wrap_method( - self.update_note, - default_timeout=30.0, - client_info=client_info, - ), - self.list_note_occurrences: gapic_v1.method.wrap_method( - self.list_note_occurrences, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def get_occurrence(self) -> Callable[ - [grafeas.GetOccurrenceRequest], - Union[ - grafeas.Occurrence, - Awaitable[grafeas.Occurrence] - ]]: - raise NotImplementedError() - - @property - def list_occurrences(self) -> Callable[ - [grafeas.ListOccurrencesRequest], - Union[ - grafeas.ListOccurrencesResponse, - Awaitable[grafeas.ListOccurrencesResponse] - ]]: - raise NotImplementedError() - - @property - def delete_occurrence(self) -> Callable[ - [grafeas.DeleteOccurrenceRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def create_occurrence(self) -> Callable[ - [grafeas.CreateOccurrenceRequest], - Union[ - grafeas.Occurrence, - Awaitable[grafeas.Occurrence] - ]]: - raise NotImplementedError() - - @property - def batch_create_occurrences(self) -> Callable[ - [grafeas.BatchCreateOccurrencesRequest], - Union[ - grafeas.BatchCreateOccurrencesResponse, - Awaitable[grafeas.BatchCreateOccurrencesResponse] - ]]: - raise NotImplementedError() - - @property - def update_occurrence(self) -> Callable[ - [grafeas.UpdateOccurrenceRequest], - Union[ - grafeas.Occurrence, - Awaitable[grafeas.Occurrence] - ]]: - raise NotImplementedError() - - @property - def get_occurrence_note(self) -> Callable[ - [grafeas.GetOccurrenceNoteRequest], - Union[ - grafeas.Note, - Awaitable[grafeas.Note] - ]]: - raise NotImplementedError() - - @property - def get_note(self) -> Callable[ - [grafeas.GetNoteRequest], - Union[ - grafeas.Note, - Awaitable[grafeas.Note] - ]]: - raise NotImplementedError() - - @property - def list_notes(self) -> Callable[ - [grafeas.ListNotesRequest], - Union[ - grafeas.ListNotesResponse, - Awaitable[grafeas.ListNotesResponse] - ]]: - raise NotImplementedError() - - @property - def delete_note(self) -> Callable[ - [grafeas.DeleteNoteRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def create_note(self) -> Callable[ - [grafeas.CreateNoteRequest], - Union[ - grafeas.Note, - Awaitable[grafeas.Note] - ]]: - raise NotImplementedError() - - @property - def batch_create_notes(self) -> Callable[ - [grafeas.BatchCreateNotesRequest], - Union[ - grafeas.BatchCreateNotesResponse, - Awaitable[grafeas.BatchCreateNotesResponse] - ]]: - raise NotImplementedError() - - @property - def update_note(self) -> Callable[ - [grafeas.UpdateNoteRequest], - Union[ - grafeas.Note, - Awaitable[grafeas.Note] - ]]: - raise NotImplementedError() - - @property - def list_note_occurrences(self) -> Callable[ - [grafeas.ListNoteOccurrencesRequest], - Union[ - grafeas.ListNoteOccurrencesResponse, - Awaitable[grafeas.ListNoteOccurrencesResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'GrafeasTransport', -) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/grpc.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/grpc.py deleted file mode 100644 index 04285daa7edd..000000000000 --- a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/grpc.py +++ /dev/null @@ -1,708 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 grafeas.grafeas_v1.types import grafeas -from .base import GrafeasTransport, 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": "grafeas.v1.Grafeas", - "rpcName": 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": "grafeas.v1.Grafeas", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class GrafeasGrpcTransport(GrafeasTransport): - """gRPC backend transport for Grafeas. - - `Grafeas `__ API. - - Retrieves analysis results of Cloud components such as Docker - container images. - - Analysis results are stored as a series of occurrences. An - ``Occurrence`` contains information about a specific analysis - instance on a resource. An occurrence refers to a ``Note``. A note - contains details describing the analysis and is generally stored in - a separate project, called a ``Provider``. Multiple occurrences can - refer to the same note. - - For example, an SSL vulnerability could affect multiple images. In - this case, there would be one note for the vulnerability and an - occurrence for each image with the vulnerability referring to that - note. - - This 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 = 'containeranalysis.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: 'containeranalysis.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to 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 = 'containeranalysis.googleapis.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_occurrence(self) -> Callable[ - [grafeas.GetOccurrenceRequest], - grafeas.Occurrence]: - r"""Return a callable for the get occurrence method over gRPC. - - Gets the specified occurrence. - - Returns: - Callable[[~.GetOccurrenceRequest], - ~.Occurrence]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_occurrence' not in self._stubs: - self._stubs['get_occurrence'] = self._logged_channel.unary_unary( - '/grafeas.v1.Grafeas/GetOccurrence', - request_serializer=grafeas.GetOccurrenceRequest.serialize, - response_deserializer=grafeas.Occurrence.deserialize, - ) - return self._stubs['get_occurrence'] - - @property - def list_occurrences(self) -> Callable[ - [grafeas.ListOccurrencesRequest], - grafeas.ListOccurrencesResponse]: - r"""Return a callable for the list occurrences method over gRPC. - - Lists occurrences for the specified project. - - Returns: - Callable[[~.ListOccurrencesRequest], - ~.ListOccurrencesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_occurrences' not in self._stubs: - self._stubs['list_occurrences'] = self._logged_channel.unary_unary( - '/grafeas.v1.Grafeas/ListOccurrences', - request_serializer=grafeas.ListOccurrencesRequest.serialize, - response_deserializer=grafeas.ListOccurrencesResponse.deserialize, - ) - return self._stubs['list_occurrences'] - - @property - def delete_occurrence(self) -> Callable[ - [grafeas.DeleteOccurrenceRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete occurrence method over gRPC. - - Deletes the specified occurrence. For example, use - this method to delete an occurrence when the occurrence - is no longer applicable for the given resource. - - Returns: - Callable[[~.DeleteOccurrenceRequest], - ~.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_occurrence' not in self._stubs: - self._stubs['delete_occurrence'] = self._logged_channel.unary_unary( - '/grafeas.v1.Grafeas/DeleteOccurrence', - request_serializer=grafeas.DeleteOccurrenceRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_occurrence'] - - @property - def create_occurrence(self) -> Callable[ - [grafeas.CreateOccurrenceRequest], - grafeas.Occurrence]: - r"""Return a callable for the create occurrence method over gRPC. - - Creates a new occurrence. - - Returns: - Callable[[~.CreateOccurrenceRequest], - ~.Occurrence]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_occurrence' not in self._stubs: - self._stubs['create_occurrence'] = self._logged_channel.unary_unary( - '/grafeas.v1.Grafeas/CreateOccurrence', - request_serializer=grafeas.CreateOccurrenceRequest.serialize, - response_deserializer=grafeas.Occurrence.deserialize, - ) - return self._stubs['create_occurrence'] - - @property - def batch_create_occurrences(self) -> Callable[ - [grafeas.BatchCreateOccurrencesRequest], - grafeas.BatchCreateOccurrencesResponse]: - r"""Return a callable for the batch create occurrences method over gRPC. - - Creates new occurrences in batch. - - Returns: - Callable[[~.BatchCreateOccurrencesRequest], - ~.BatchCreateOccurrencesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_create_occurrences' not in self._stubs: - self._stubs['batch_create_occurrences'] = self._logged_channel.unary_unary( - '/grafeas.v1.Grafeas/BatchCreateOccurrences', - request_serializer=grafeas.BatchCreateOccurrencesRequest.serialize, - response_deserializer=grafeas.BatchCreateOccurrencesResponse.deserialize, - ) - return self._stubs['batch_create_occurrences'] - - @property - def update_occurrence(self) -> Callable[ - [grafeas.UpdateOccurrenceRequest], - grafeas.Occurrence]: - r"""Return a callable for the update occurrence method over gRPC. - - Updates the specified occurrence. - - Returns: - Callable[[~.UpdateOccurrenceRequest], - ~.Occurrence]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_occurrence' not in self._stubs: - self._stubs['update_occurrence'] = self._logged_channel.unary_unary( - '/grafeas.v1.Grafeas/UpdateOccurrence', - request_serializer=grafeas.UpdateOccurrenceRequest.serialize, - response_deserializer=grafeas.Occurrence.deserialize, - ) - return self._stubs['update_occurrence'] - - @property - def get_occurrence_note(self) -> Callable[ - [grafeas.GetOccurrenceNoteRequest], - grafeas.Note]: - r"""Return a callable for the get occurrence note method over gRPC. - - Gets the note attached to the specified occurrence. - Consumer projects can use this method to get a note that - belongs to a provider project. - - Returns: - Callable[[~.GetOccurrenceNoteRequest], - ~.Note]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_occurrence_note' not in self._stubs: - self._stubs['get_occurrence_note'] = self._logged_channel.unary_unary( - '/grafeas.v1.Grafeas/GetOccurrenceNote', - request_serializer=grafeas.GetOccurrenceNoteRequest.serialize, - response_deserializer=grafeas.Note.deserialize, - ) - return self._stubs['get_occurrence_note'] - - @property - def get_note(self) -> Callable[ - [grafeas.GetNoteRequest], - grafeas.Note]: - r"""Return a callable for the get note method over gRPC. - - Gets the specified note. - - Returns: - Callable[[~.GetNoteRequest], - ~.Note]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_note' not in self._stubs: - self._stubs['get_note'] = self._logged_channel.unary_unary( - '/grafeas.v1.Grafeas/GetNote', - request_serializer=grafeas.GetNoteRequest.serialize, - response_deserializer=grafeas.Note.deserialize, - ) - return self._stubs['get_note'] - - @property - def list_notes(self) -> Callable[ - [grafeas.ListNotesRequest], - grafeas.ListNotesResponse]: - r"""Return a callable for the list notes method over gRPC. - - Lists notes for the specified project. - - Returns: - Callable[[~.ListNotesRequest], - ~.ListNotesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_notes' not in self._stubs: - self._stubs['list_notes'] = self._logged_channel.unary_unary( - '/grafeas.v1.Grafeas/ListNotes', - request_serializer=grafeas.ListNotesRequest.serialize, - response_deserializer=grafeas.ListNotesResponse.deserialize, - ) - return self._stubs['list_notes'] - - @property - def delete_note(self) -> Callable[ - [grafeas.DeleteNoteRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete note method over gRPC. - - Deletes the specified note. - - Returns: - Callable[[~.DeleteNoteRequest], - ~.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_note' not in self._stubs: - self._stubs['delete_note'] = self._logged_channel.unary_unary( - '/grafeas.v1.Grafeas/DeleteNote', - request_serializer=grafeas.DeleteNoteRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_note'] - - @property - def create_note(self) -> Callable[ - [grafeas.CreateNoteRequest], - grafeas.Note]: - r"""Return a callable for the create note method over gRPC. - - Creates a new note. - - Returns: - Callable[[~.CreateNoteRequest], - ~.Note]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_note' not in self._stubs: - self._stubs['create_note'] = self._logged_channel.unary_unary( - '/grafeas.v1.Grafeas/CreateNote', - request_serializer=grafeas.CreateNoteRequest.serialize, - response_deserializer=grafeas.Note.deserialize, - ) - return self._stubs['create_note'] - - @property - def batch_create_notes(self) -> Callable[ - [grafeas.BatchCreateNotesRequest], - grafeas.BatchCreateNotesResponse]: - r"""Return a callable for the batch create notes method over gRPC. - - Creates new notes in batch. - - Returns: - Callable[[~.BatchCreateNotesRequest], - ~.BatchCreateNotesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_create_notes' not in self._stubs: - self._stubs['batch_create_notes'] = self._logged_channel.unary_unary( - '/grafeas.v1.Grafeas/BatchCreateNotes', - request_serializer=grafeas.BatchCreateNotesRequest.serialize, - response_deserializer=grafeas.BatchCreateNotesResponse.deserialize, - ) - return self._stubs['batch_create_notes'] - - @property - def update_note(self) -> Callable[ - [grafeas.UpdateNoteRequest], - grafeas.Note]: - r"""Return a callable for the update note method over gRPC. - - Updates the specified note. - - Returns: - Callable[[~.UpdateNoteRequest], - ~.Note]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_note' not in self._stubs: - self._stubs['update_note'] = self._logged_channel.unary_unary( - '/grafeas.v1.Grafeas/UpdateNote', - request_serializer=grafeas.UpdateNoteRequest.serialize, - response_deserializer=grafeas.Note.deserialize, - ) - return self._stubs['update_note'] - - @property - def list_note_occurrences(self) -> Callable[ - [grafeas.ListNoteOccurrencesRequest], - grafeas.ListNoteOccurrencesResponse]: - r"""Return a callable for the list note occurrences method over gRPC. - - Lists occurrences referencing the specified note. - Provider projects can use this method to get all - occurrences across consumer projects referencing the - specified note. - - Returns: - Callable[[~.ListNoteOccurrencesRequest], - ~.ListNoteOccurrencesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_note_occurrences' not in self._stubs: - self._stubs['list_note_occurrences'] = self._logged_channel.unary_unary( - '/grafeas.v1.Grafeas/ListNoteOccurrences', - request_serializer=grafeas.ListNoteOccurrencesRequest.serialize, - response_deserializer=grafeas.ListNoteOccurrencesResponse.deserialize, - ) - return self._stubs['list_note_occurrences'] - - def close(self): - self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'GrafeasGrpcTransport', -) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/grpc_asyncio.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/grpc_asyncio.py deleted file mode 100644 index 3f476b208ac4..000000000000 --- a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/grpc_asyncio.py +++ /dev/null @@ -1,873 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 grafeas.grafeas_v1.types import grafeas -from .base import GrafeasTransport, DEFAULT_CLIENT_INFO -from .grpc import GrafeasGrpcTransport - -try: - from google.api_core import client_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": "grafeas.v1.Grafeas", - "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": "grafeas.v1.Grafeas", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class GrafeasGrpcAsyncIOTransport(GrafeasTransport): - """gRPC AsyncIO backend transport for Grafeas. - - `Grafeas `__ API. - - Retrieves analysis results of Cloud components such as Docker - container images. - - Analysis results are stored as a series of occurrences. An - ``Occurrence`` contains information about a specific analysis - instance on a resource. An occurrence refers to a ``Note``. A note - contains details describing the analysis and is generally stored in - a separate project, called a ``Provider``. Multiple occurrences can - refer to the same note. - - For example, an SSL vulnerability could affect multiple images. In - this case, there would be one note for the vulnerability and an - occurrence for each image with the vulnerability referring to that - note. - - This 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 = 'containeranalysis.googleapis.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 = 'containeranalysis.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: 'containeranalysis.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to 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_occurrence(self) -> Callable[ - [grafeas.GetOccurrenceRequest], - Awaitable[grafeas.Occurrence]]: - r"""Return a callable for the get occurrence method over gRPC. - - Gets the specified occurrence. - - Returns: - Callable[[~.GetOccurrenceRequest], - Awaitable[~.Occurrence]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_occurrence' not in self._stubs: - self._stubs['get_occurrence'] = self._logged_channel.unary_unary( - '/grafeas.v1.Grafeas/GetOccurrence', - request_serializer=grafeas.GetOccurrenceRequest.serialize, - response_deserializer=grafeas.Occurrence.deserialize, - ) - return self._stubs['get_occurrence'] - - @property - def list_occurrences(self) -> Callable[ - [grafeas.ListOccurrencesRequest], - Awaitable[grafeas.ListOccurrencesResponse]]: - r"""Return a callable for the list occurrences method over gRPC. - - Lists occurrences for the specified project. - - Returns: - Callable[[~.ListOccurrencesRequest], - Awaitable[~.ListOccurrencesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_occurrences' not in self._stubs: - self._stubs['list_occurrences'] = self._logged_channel.unary_unary( - '/grafeas.v1.Grafeas/ListOccurrences', - request_serializer=grafeas.ListOccurrencesRequest.serialize, - response_deserializer=grafeas.ListOccurrencesResponse.deserialize, - ) - return self._stubs['list_occurrences'] - - @property - def delete_occurrence(self) -> Callable[ - [grafeas.DeleteOccurrenceRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete occurrence method over gRPC. - - Deletes the specified occurrence. For example, use - this method to delete an occurrence when the occurrence - is no longer applicable for the given resource. - - Returns: - Callable[[~.DeleteOccurrenceRequest], - 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_occurrence' not in self._stubs: - self._stubs['delete_occurrence'] = self._logged_channel.unary_unary( - '/grafeas.v1.Grafeas/DeleteOccurrence', - request_serializer=grafeas.DeleteOccurrenceRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_occurrence'] - - @property - def create_occurrence(self) -> Callable[ - [grafeas.CreateOccurrenceRequest], - Awaitable[grafeas.Occurrence]]: - r"""Return a callable for the create occurrence method over gRPC. - - Creates a new occurrence. - - Returns: - Callable[[~.CreateOccurrenceRequest], - Awaitable[~.Occurrence]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_occurrence' not in self._stubs: - self._stubs['create_occurrence'] = self._logged_channel.unary_unary( - '/grafeas.v1.Grafeas/CreateOccurrence', - request_serializer=grafeas.CreateOccurrenceRequest.serialize, - response_deserializer=grafeas.Occurrence.deserialize, - ) - return self._stubs['create_occurrence'] - - @property - def batch_create_occurrences(self) -> Callable[ - [grafeas.BatchCreateOccurrencesRequest], - Awaitable[grafeas.BatchCreateOccurrencesResponse]]: - r"""Return a callable for the batch create occurrences method over gRPC. - - Creates new occurrences in batch. - - Returns: - Callable[[~.BatchCreateOccurrencesRequest], - Awaitable[~.BatchCreateOccurrencesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_create_occurrences' not in self._stubs: - self._stubs['batch_create_occurrences'] = self._logged_channel.unary_unary( - '/grafeas.v1.Grafeas/BatchCreateOccurrences', - request_serializer=grafeas.BatchCreateOccurrencesRequest.serialize, - response_deserializer=grafeas.BatchCreateOccurrencesResponse.deserialize, - ) - return self._stubs['batch_create_occurrences'] - - @property - def update_occurrence(self) -> Callable[ - [grafeas.UpdateOccurrenceRequest], - Awaitable[grafeas.Occurrence]]: - r"""Return a callable for the update occurrence method over gRPC. - - Updates the specified occurrence. - - Returns: - Callable[[~.UpdateOccurrenceRequest], - Awaitable[~.Occurrence]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_occurrence' not in self._stubs: - self._stubs['update_occurrence'] = self._logged_channel.unary_unary( - '/grafeas.v1.Grafeas/UpdateOccurrence', - request_serializer=grafeas.UpdateOccurrenceRequest.serialize, - response_deserializer=grafeas.Occurrence.deserialize, - ) - return self._stubs['update_occurrence'] - - @property - def get_occurrence_note(self) -> Callable[ - [grafeas.GetOccurrenceNoteRequest], - Awaitable[grafeas.Note]]: - r"""Return a callable for the get occurrence note method over gRPC. - - Gets the note attached to the specified occurrence. - Consumer projects can use this method to get a note that - belongs to a provider project. - - Returns: - Callable[[~.GetOccurrenceNoteRequest], - Awaitable[~.Note]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_occurrence_note' not in self._stubs: - self._stubs['get_occurrence_note'] = self._logged_channel.unary_unary( - '/grafeas.v1.Grafeas/GetOccurrenceNote', - request_serializer=grafeas.GetOccurrenceNoteRequest.serialize, - response_deserializer=grafeas.Note.deserialize, - ) - return self._stubs['get_occurrence_note'] - - @property - def get_note(self) -> Callable[ - [grafeas.GetNoteRequest], - Awaitable[grafeas.Note]]: - r"""Return a callable for the get note method over gRPC. - - Gets the specified note. - - Returns: - Callable[[~.GetNoteRequest], - Awaitable[~.Note]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_note' not in self._stubs: - self._stubs['get_note'] = self._logged_channel.unary_unary( - '/grafeas.v1.Grafeas/GetNote', - request_serializer=grafeas.GetNoteRequest.serialize, - response_deserializer=grafeas.Note.deserialize, - ) - return self._stubs['get_note'] - - @property - def list_notes(self) -> Callable[ - [grafeas.ListNotesRequest], - Awaitable[grafeas.ListNotesResponse]]: - r"""Return a callable for the list notes method over gRPC. - - Lists notes for the specified project. - - Returns: - Callable[[~.ListNotesRequest], - Awaitable[~.ListNotesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_notes' not in self._stubs: - self._stubs['list_notes'] = self._logged_channel.unary_unary( - '/grafeas.v1.Grafeas/ListNotes', - request_serializer=grafeas.ListNotesRequest.serialize, - response_deserializer=grafeas.ListNotesResponse.deserialize, - ) - return self._stubs['list_notes'] - - @property - def delete_note(self) -> Callable[ - [grafeas.DeleteNoteRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete note method over gRPC. - - Deletes the specified note. - - Returns: - Callable[[~.DeleteNoteRequest], - 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_note' not in self._stubs: - self._stubs['delete_note'] = self._logged_channel.unary_unary( - '/grafeas.v1.Grafeas/DeleteNote', - request_serializer=grafeas.DeleteNoteRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_note'] - - @property - def create_note(self) -> Callable[ - [grafeas.CreateNoteRequest], - Awaitable[grafeas.Note]]: - r"""Return a callable for the create note method over gRPC. - - Creates a new note. - - Returns: - Callable[[~.CreateNoteRequest], - Awaitable[~.Note]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_note' not in self._stubs: - self._stubs['create_note'] = self._logged_channel.unary_unary( - '/grafeas.v1.Grafeas/CreateNote', - request_serializer=grafeas.CreateNoteRequest.serialize, - response_deserializer=grafeas.Note.deserialize, - ) - return self._stubs['create_note'] - - @property - def batch_create_notes(self) -> Callable[ - [grafeas.BatchCreateNotesRequest], - Awaitable[grafeas.BatchCreateNotesResponse]]: - r"""Return a callable for the batch create notes method over gRPC. - - Creates new notes in batch. - - Returns: - Callable[[~.BatchCreateNotesRequest], - Awaitable[~.BatchCreateNotesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_create_notes' not in self._stubs: - self._stubs['batch_create_notes'] = self._logged_channel.unary_unary( - '/grafeas.v1.Grafeas/BatchCreateNotes', - request_serializer=grafeas.BatchCreateNotesRequest.serialize, - response_deserializer=grafeas.BatchCreateNotesResponse.deserialize, - ) - return self._stubs['batch_create_notes'] - - @property - def update_note(self) -> Callable[ - [grafeas.UpdateNoteRequest], - Awaitable[grafeas.Note]]: - r"""Return a callable for the update note method over gRPC. - - Updates the specified note. - - Returns: - Callable[[~.UpdateNoteRequest], - Awaitable[~.Note]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_note' not in self._stubs: - self._stubs['update_note'] = self._logged_channel.unary_unary( - '/grafeas.v1.Grafeas/UpdateNote', - request_serializer=grafeas.UpdateNoteRequest.serialize, - response_deserializer=grafeas.Note.deserialize, - ) - return self._stubs['update_note'] - - @property - def list_note_occurrences(self) -> Callable[ - [grafeas.ListNoteOccurrencesRequest], - Awaitable[grafeas.ListNoteOccurrencesResponse]]: - r"""Return a callable for the list note occurrences method over gRPC. - - Lists occurrences referencing the specified note. - Provider projects can use this method to get all - occurrences across consumer projects referencing the - specified note. - - Returns: - Callable[[~.ListNoteOccurrencesRequest], - Awaitable[~.ListNoteOccurrencesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_note_occurrences' not in self._stubs: - self._stubs['list_note_occurrences'] = self._logged_channel.unary_unary( - '/grafeas.v1.Grafeas/ListNoteOccurrences', - request_serializer=grafeas.ListNoteOccurrencesRequest.serialize, - response_deserializer=grafeas.ListNoteOccurrencesResponse.deserialize, - ) - return self._stubs['list_note_occurrences'] - - 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_occurrence: self._wrap_method( - self.get_occurrence, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.list_occurrences: self._wrap_method( - self.list_occurrences, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.delete_occurrence: self._wrap_method( - self.delete_occurrence, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.create_occurrence: self._wrap_method( - self.create_occurrence, - default_timeout=30.0, - client_info=client_info, - ), - self.batch_create_occurrences: self._wrap_method( - self.batch_create_occurrences, - default_timeout=30.0, - client_info=client_info, - ), - self.update_occurrence: self._wrap_method( - self.update_occurrence, - default_timeout=30.0, - client_info=client_info, - ), - self.get_occurrence_note: self._wrap_method( - self.get_occurrence_note, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.get_note: self._wrap_method( - self.get_note, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.list_notes: self._wrap_method( - self.list_notes, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.delete_note: self._wrap_method( - self.delete_note, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.create_note: self._wrap_method( - self.create_note, - default_timeout=30.0, - client_info=client_info, - ), - self.batch_create_notes: self._wrap_method( - self.batch_create_notes, - default_timeout=30.0, - client_info=client_info, - ), - self.update_note: self._wrap_method( - self.update_note, - default_timeout=30.0, - client_info=client_info, - ), - self.list_note_occurrences: self._wrap_method( - self.list_note_occurrences, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - 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__ = ( - 'GrafeasGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/rest.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/rest.py deleted file mode 100644 index 6733a8041d21..000000000000 --- a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/rest.py +++ /dev/null @@ -1,2241 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -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 grafeas.grafeas_v1.types import grafeas - - -from .rest_base import _BaseGrafeasRestTransport -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}", -) - - -class GrafeasRestInterceptor: - """Interceptor for Grafeas. - - 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 GrafeasRestTransport. - - .. code-block:: python - class MyCustomGrafeasInterceptor(GrafeasRestInterceptor): - def pre_batch_create_notes(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_batch_create_notes(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_batch_create_occurrences(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_batch_create_occurrences(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_note(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_note(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_occurrence(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_occurrence(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_note(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_delete_occurrence(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_note(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_note(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_occurrence(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_occurrence(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_occurrence_note(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_occurrence_note(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_note_occurrences(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_note_occurrences(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_notes(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_notes(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_occurrences(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_occurrences(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_note(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_note(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_occurrence(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_occurrence(self, response): - logging.log(f"Received response: {response}") - return response - - transport = GrafeasRestTransport(interceptor=MyCustomGrafeasInterceptor()) - client = GrafeasClient(transport=transport) - - - """ - def pre_batch_create_notes(self, request: grafeas.BatchCreateNotesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[grafeas.BatchCreateNotesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for batch_create_notes - - Override in a subclass to manipulate the request or metadata - before they are sent to the Grafeas server. - """ - return request, metadata - - def post_batch_create_notes(self, response: grafeas.BatchCreateNotesResponse) -> grafeas.BatchCreateNotesResponse: - """Post-rpc interceptor for batch_create_notes - - Override in a subclass to manipulate the response - after it is returned by the Grafeas server but before - it is returned to user code. - """ - return response - - def pre_batch_create_occurrences(self, request: grafeas.BatchCreateOccurrencesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[grafeas.BatchCreateOccurrencesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for batch_create_occurrences - - Override in a subclass to manipulate the request or metadata - before they are sent to the Grafeas server. - """ - return request, metadata - - def post_batch_create_occurrences(self, response: grafeas.BatchCreateOccurrencesResponse) -> grafeas.BatchCreateOccurrencesResponse: - """Post-rpc interceptor for batch_create_occurrences - - Override in a subclass to manipulate the response - after it is returned by the Grafeas server but before - it is returned to user code. - """ - return response - - def pre_create_note(self, request: grafeas.CreateNoteRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[grafeas.CreateNoteRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for create_note - - Override in a subclass to manipulate the request or metadata - before they are sent to the Grafeas server. - """ - return request, metadata - - def post_create_note(self, response: grafeas.Note) -> grafeas.Note: - """Post-rpc interceptor for create_note - - Override in a subclass to manipulate the response - after it is returned by the Grafeas server but before - it is returned to user code. - """ - return response - - def pre_create_occurrence(self, request: grafeas.CreateOccurrenceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[grafeas.CreateOccurrenceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for create_occurrence - - Override in a subclass to manipulate the request or metadata - before they are sent to the Grafeas server. - """ - return request, metadata - - def post_create_occurrence(self, response: grafeas.Occurrence) -> grafeas.Occurrence: - """Post-rpc interceptor for create_occurrence - - Override in a subclass to manipulate the response - after it is returned by the Grafeas server but before - it is returned to user code. - """ - return response - - def pre_delete_note(self, request: grafeas.DeleteNoteRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[grafeas.DeleteNoteRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_note - - Override in a subclass to manipulate the request or metadata - before they are sent to the Grafeas server. - """ - return request, metadata - - def pre_delete_occurrence(self, request: grafeas.DeleteOccurrenceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[grafeas.DeleteOccurrenceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_occurrence - - Override in a subclass to manipulate the request or metadata - before they are sent to the Grafeas server. - """ - return request, metadata - - def pre_get_note(self, request: grafeas.GetNoteRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[grafeas.GetNoteRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_note - - Override in a subclass to manipulate the request or metadata - before they are sent to the Grafeas server. - """ - return request, metadata - - def post_get_note(self, response: grafeas.Note) -> grafeas.Note: - """Post-rpc interceptor for get_note - - Override in a subclass to manipulate the response - after it is returned by the Grafeas server but before - it is returned to user code. - """ - return response - - def pre_get_occurrence(self, request: grafeas.GetOccurrenceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[grafeas.GetOccurrenceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_occurrence - - Override in a subclass to manipulate the request or metadata - before they are sent to the Grafeas server. - """ - return request, metadata - - def post_get_occurrence(self, response: grafeas.Occurrence) -> grafeas.Occurrence: - """Post-rpc interceptor for get_occurrence - - Override in a subclass to manipulate the response - after it is returned by the Grafeas server but before - it is returned to user code. - """ - return response - - def pre_get_occurrence_note(self, request: grafeas.GetOccurrenceNoteRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[grafeas.GetOccurrenceNoteRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_occurrence_note - - Override in a subclass to manipulate the request or metadata - before they are sent to the Grafeas server. - """ - return request, metadata - - def post_get_occurrence_note(self, response: grafeas.Note) -> grafeas.Note: - """Post-rpc interceptor for get_occurrence_note - - Override in a subclass to manipulate the response - after it is returned by the Grafeas server but before - it is returned to user code. - """ - return response - - def pre_list_note_occurrences(self, request: grafeas.ListNoteOccurrencesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[grafeas.ListNoteOccurrencesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_note_occurrences - - Override in a subclass to manipulate the request or metadata - before they are sent to the Grafeas server. - """ - return request, metadata - - def post_list_note_occurrences(self, response: grafeas.ListNoteOccurrencesResponse) -> grafeas.ListNoteOccurrencesResponse: - """Post-rpc interceptor for list_note_occurrences - - Override in a subclass to manipulate the response - after it is returned by the Grafeas server but before - it is returned to user code. - """ - return response - - def pre_list_notes(self, request: grafeas.ListNotesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[grafeas.ListNotesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_notes - - Override in a subclass to manipulate the request or metadata - before they are sent to the Grafeas server. - """ - return request, metadata - - def post_list_notes(self, response: grafeas.ListNotesResponse) -> grafeas.ListNotesResponse: - """Post-rpc interceptor for list_notes - - Override in a subclass to manipulate the response - after it is returned by the Grafeas server but before - it is returned to user code. - """ - return response - - def pre_list_occurrences(self, request: grafeas.ListOccurrencesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[grafeas.ListOccurrencesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_occurrences - - Override in a subclass to manipulate the request or metadata - before they are sent to the Grafeas server. - """ - return request, metadata - - def post_list_occurrences(self, response: grafeas.ListOccurrencesResponse) -> grafeas.ListOccurrencesResponse: - """Post-rpc interceptor for list_occurrences - - Override in a subclass to manipulate the response - after it is returned by the Grafeas server but before - it is returned to user code. - """ - return response - - def pre_update_note(self, request: grafeas.UpdateNoteRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[grafeas.UpdateNoteRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for update_note - - Override in a subclass to manipulate the request or metadata - before they are sent to the Grafeas server. - """ - return request, metadata - - def post_update_note(self, response: grafeas.Note) -> grafeas.Note: - """Post-rpc interceptor for update_note - - Override in a subclass to manipulate the response - after it is returned by the Grafeas server but before - it is returned to user code. - """ - return response - - def pre_update_occurrence(self, request: grafeas.UpdateOccurrenceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[grafeas.UpdateOccurrenceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for update_occurrence - - Override in a subclass to manipulate the request or metadata - before they are sent to the Grafeas server. - """ - return request, metadata - - def post_update_occurrence(self, response: grafeas.Occurrence) -> grafeas.Occurrence: - """Post-rpc interceptor for update_occurrence - - Override in a subclass to manipulate the response - after it is returned by the Grafeas server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class GrafeasRestStub: - _session: AuthorizedSession - _host: str - _interceptor: GrafeasRestInterceptor - - -class GrafeasRestTransport(_BaseGrafeasRestTransport): - """REST backend synchronous transport for Grafeas. - - `Grafeas `__ API. - - Retrieves analysis results of Cloud components such as Docker - container images. - - Analysis results are stored as a series of occurrences. An - ``Occurrence`` contains information about a specific analysis - instance on a resource. An occurrence refers to a ``Note``. A note - contains details describing the analysis and is generally stored in - a separate project, called a ``Provider``. Multiple occurrences can - refer to the same note. - - For example, an SSL vulnerability could affect multiple images. In - this case, there would be one note for the vulnerability and an - occurrence for each image with the vulnerability referring to that - note. - - This 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 = 'containeranalysis.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[GrafeasRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'containeranalysis.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to 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 GrafeasRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _BatchCreateNotes(_BaseGrafeasRestTransport._BaseBatchCreateNotes, GrafeasRestStub): - def __hash__(self): - return hash("GrafeasRestTransport.BatchCreateNotes") - - @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: grafeas.BatchCreateNotesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> grafeas.BatchCreateNotesResponse: - r"""Call the batch create notes method over HTTP. - - Args: - request (~.grafeas.BatchCreateNotesRequest): - The request object. Request to create notes in batch. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.grafeas.BatchCreateNotesResponse: - Response for creating notes in batch. - """ - - http_options = _BaseGrafeasRestTransport._BaseBatchCreateNotes._get_http_options() - - request, metadata = self._interceptor.pre_batch_create_notes(request, metadata) - transcoded_request = _BaseGrafeasRestTransport._BaseBatchCreateNotes._get_transcoded_request(http_options, request) - - body = _BaseGrafeasRestTransport._BaseBatchCreateNotes._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseGrafeasRestTransport._BaseBatchCreateNotes._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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 grafeas_v1.GrafeasClient.BatchCreateNotes", - extra = { - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "BatchCreateNotes", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = GrafeasRestTransport._BatchCreateNotes._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 = grafeas.BatchCreateNotesResponse() - pb_resp = grafeas.BatchCreateNotesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_batch_create_notes(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = grafeas.BatchCreateNotesResponse.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 grafeas_v1.GrafeasClient.batch_create_notes", - extra = { - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "BatchCreateNotes", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _BatchCreateOccurrences(_BaseGrafeasRestTransport._BaseBatchCreateOccurrences, GrafeasRestStub): - def __hash__(self): - return hash("GrafeasRestTransport.BatchCreateOccurrences") - - @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: grafeas.BatchCreateOccurrencesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> grafeas.BatchCreateOccurrencesResponse: - r"""Call the batch create occurrences method over HTTP. - - Args: - request (~.grafeas.BatchCreateOccurrencesRequest): - The request object. Request to create occurrences in - batch. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.grafeas.BatchCreateOccurrencesResponse: - Response for creating occurrences in - batch. - - """ - - http_options = _BaseGrafeasRestTransport._BaseBatchCreateOccurrences._get_http_options() - - request, metadata = self._interceptor.pre_batch_create_occurrences(request, metadata) - transcoded_request = _BaseGrafeasRestTransport._BaseBatchCreateOccurrences._get_transcoded_request(http_options, request) - - body = _BaseGrafeasRestTransport._BaseBatchCreateOccurrences._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseGrafeasRestTransport._BaseBatchCreateOccurrences._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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 grafeas_v1.GrafeasClient.BatchCreateOccurrences", - extra = { - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "BatchCreateOccurrences", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = GrafeasRestTransport._BatchCreateOccurrences._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 = grafeas.BatchCreateOccurrencesResponse() - pb_resp = grafeas.BatchCreateOccurrencesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_batch_create_occurrences(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = grafeas.BatchCreateOccurrencesResponse.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 grafeas_v1.GrafeasClient.batch_create_occurrences", - extra = { - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "BatchCreateOccurrences", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _CreateNote(_BaseGrafeasRestTransport._BaseCreateNote, GrafeasRestStub): - def __hash__(self): - return hash("GrafeasRestTransport.CreateNote") - - @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: grafeas.CreateNoteRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> grafeas.Note: - r"""Call the create note method over HTTP. - - Args: - request (~.grafeas.CreateNoteRequest): - The request object. Request to create a new note. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.grafeas.Note: - A type of analysis that can be done - for a resource. - - """ - - http_options = _BaseGrafeasRestTransport._BaseCreateNote._get_http_options() - - request, metadata = self._interceptor.pre_create_note(request, metadata) - transcoded_request = _BaseGrafeasRestTransport._BaseCreateNote._get_transcoded_request(http_options, request) - - body = _BaseGrafeasRestTransport._BaseCreateNote._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseGrafeasRestTransport._BaseCreateNote._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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 grafeas_v1.GrafeasClient.CreateNote", - extra = { - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "CreateNote", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = GrafeasRestTransport._CreateNote._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 = grafeas.Note() - pb_resp = grafeas.Note.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_create_note(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = grafeas.Note.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 grafeas_v1.GrafeasClient.create_note", - extra = { - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "CreateNote", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _CreateOccurrence(_BaseGrafeasRestTransport._BaseCreateOccurrence, GrafeasRestStub): - def __hash__(self): - return hash("GrafeasRestTransport.CreateOccurrence") - - @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: grafeas.CreateOccurrenceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> grafeas.Occurrence: - r"""Call the create occurrence method over HTTP. - - Args: - request (~.grafeas.CreateOccurrenceRequest): - The request object. Request to create a new occurrence. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.grafeas.Occurrence: - An instance of an analysis type that - has been found on a resource. - - """ - - http_options = _BaseGrafeasRestTransport._BaseCreateOccurrence._get_http_options() - - request, metadata = self._interceptor.pre_create_occurrence(request, metadata) - transcoded_request = _BaseGrafeasRestTransport._BaseCreateOccurrence._get_transcoded_request(http_options, request) - - body = _BaseGrafeasRestTransport._BaseCreateOccurrence._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseGrafeasRestTransport._BaseCreateOccurrence._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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 grafeas_v1.GrafeasClient.CreateOccurrence", - extra = { - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "CreateOccurrence", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = GrafeasRestTransport._CreateOccurrence._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 = grafeas.Occurrence() - pb_resp = grafeas.Occurrence.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_create_occurrence(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = grafeas.Occurrence.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 grafeas_v1.GrafeasClient.create_occurrence", - extra = { - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "CreateOccurrence", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _DeleteNote(_BaseGrafeasRestTransport._BaseDeleteNote, GrafeasRestStub): - def __hash__(self): - return hash("GrafeasRestTransport.DeleteNote") - - @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: grafeas.DeleteNoteRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ): - r"""Call the delete note method over HTTP. - - Args: - request (~.grafeas.DeleteNoteRequest): - The request object. Request to delete a note. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, 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 = _BaseGrafeasRestTransport._BaseDeleteNote._get_http_options() - - request, metadata = self._interceptor.pre_delete_note(request, metadata) - transcoded_request = _BaseGrafeasRestTransport._BaseDeleteNote._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseGrafeasRestTransport._BaseDeleteNote._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(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 grafeas_v1.GrafeasClient.DeleteNote", - extra = { - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "DeleteNote", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = GrafeasRestTransport._DeleteNote._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 _DeleteOccurrence(_BaseGrafeasRestTransport._BaseDeleteOccurrence, GrafeasRestStub): - def __hash__(self): - return hash("GrafeasRestTransport.DeleteOccurrence") - - @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: grafeas.DeleteOccurrenceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ): - r"""Call the delete occurrence method over HTTP. - - Args: - request (~.grafeas.DeleteOccurrenceRequest): - The request object. Request to delete an occurrence. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, 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 = _BaseGrafeasRestTransport._BaseDeleteOccurrence._get_http_options() - - request, metadata = self._interceptor.pre_delete_occurrence(request, metadata) - transcoded_request = _BaseGrafeasRestTransport._BaseDeleteOccurrence._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseGrafeasRestTransport._BaseDeleteOccurrence._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(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 grafeas_v1.GrafeasClient.DeleteOccurrence", - extra = { - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "DeleteOccurrence", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = GrafeasRestTransport._DeleteOccurrence._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 _GetNote(_BaseGrafeasRestTransport._BaseGetNote, GrafeasRestStub): - def __hash__(self): - return hash("GrafeasRestTransport.GetNote") - - @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: grafeas.GetNoteRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> grafeas.Note: - r"""Call the get note method over HTTP. - - Args: - request (~.grafeas.GetNoteRequest): - The request object. Request to get a note. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.grafeas.Note: - A type of analysis that can be done - for a resource. - - """ - - http_options = _BaseGrafeasRestTransport._BaseGetNote._get_http_options() - - request, metadata = self._interceptor.pre_get_note(request, metadata) - transcoded_request = _BaseGrafeasRestTransport._BaseGetNote._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseGrafeasRestTransport._BaseGetNote._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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 grafeas_v1.GrafeasClient.GetNote", - extra = { - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "GetNote", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = GrafeasRestTransport._GetNote._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 = grafeas.Note() - pb_resp = grafeas.Note.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_note(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = grafeas.Note.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 grafeas_v1.GrafeasClient.get_note", - extra = { - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "GetNote", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetOccurrence(_BaseGrafeasRestTransport._BaseGetOccurrence, GrafeasRestStub): - def __hash__(self): - return hash("GrafeasRestTransport.GetOccurrence") - - @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: grafeas.GetOccurrenceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> grafeas.Occurrence: - r"""Call the get occurrence method over HTTP. - - Args: - request (~.grafeas.GetOccurrenceRequest): - The request object. Request to get an occurrence. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.grafeas.Occurrence: - An instance of an analysis type that - has been found on a resource. - - """ - - http_options = _BaseGrafeasRestTransport._BaseGetOccurrence._get_http_options() - - request, metadata = self._interceptor.pre_get_occurrence(request, metadata) - transcoded_request = _BaseGrafeasRestTransport._BaseGetOccurrence._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseGrafeasRestTransport._BaseGetOccurrence._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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 grafeas_v1.GrafeasClient.GetOccurrence", - extra = { - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "GetOccurrence", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = GrafeasRestTransport._GetOccurrence._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 = grafeas.Occurrence() - pb_resp = grafeas.Occurrence.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_occurrence(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = grafeas.Occurrence.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 grafeas_v1.GrafeasClient.get_occurrence", - extra = { - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "GetOccurrence", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetOccurrenceNote(_BaseGrafeasRestTransport._BaseGetOccurrenceNote, GrafeasRestStub): - def __hash__(self): - return hash("GrafeasRestTransport.GetOccurrenceNote") - - @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: grafeas.GetOccurrenceNoteRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> grafeas.Note: - r"""Call the get occurrence note method over HTTP. - - Args: - request (~.grafeas.GetOccurrenceNoteRequest): - The request object. Request to get the note to which the - specified occurrence is attached. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.grafeas.Note: - A type of analysis that can be done - for a resource. - - """ - - http_options = _BaseGrafeasRestTransport._BaseGetOccurrenceNote._get_http_options() - - request, metadata = self._interceptor.pre_get_occurrence_note(request, metadata) - transcoded_request = _BaseGrafeasRestTransport._BaseGetOccurrenceNote._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseGrafeasRestTransport._BaseGetOccurrenceNote._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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 grafeas_v1.GrafeasClient.GetOccurrenceNote", - extra = { - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "GetOccurrenceNote", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = GrafeasRestTransport._GetOccurrenceNote._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 = grafeas.Note() - pb_resp = grafeas.Note.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_occurrence_note(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = grafeas.Note.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 grafeas_v1.GrafeasClient.get_occurrence_note", - extra = { - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "GetOccurrenceNote", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListNoteOccurrences(_BaseGrafeasRestTransport._BaseListNoteOccurrences, GrafeasRestStub): - def __hash__(self): - return hash("GrafeasRestTransport.ListNoteOccurrences") - - @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: grafeas.ListNoteOccurrencesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> grafeas.ListNoteOccurrencesResponse: - r"""Call the list note occurrences method over HTTP. - - Args: - request (~.grafeas.ListNoteOccurrencesRequest): - The request object. Request to list occurrences for a - note. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.grafeas.ListNoteOccurrencesResponse: - Response for listing occurrences for - a note. - - """ - - http_options = _BaseGrafeasRestTransport._BaseListNoteOccurrences._get_http_options() - - request, metadata = self._interceptor.pre_list_note_occurrences(request, metadata) - transcoded_request = _BaseGrafeasRestTransport._BaseListNoteOccurrences._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseGrafeasRestTransport._BaseListNoteOccurrences._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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 grafeas_v1.GrafeasClient.ListNoteOccurrences", - extra = { - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "ListNoteOccurrences", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = GrafeasRestTransport._ListNoteOccurrences._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 = grafeas.ListNoteOccurrencesResponse() - pb_resp = grafeas.ListNoteOccurrencesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_note_occurrences(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = grafeas.ListNoteOccurrencesResponse.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 grafeas_v1.GrafeasClient.list_note_occurrences", - extra = { - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "ListNoteOccurrences", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListNotes(_BaseGrafeasRestTransport._BaseListNotes, GrafeasRestStub): - def __hash__(self): - return hash("GrafeasRestTransport.ListNotes") - - @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: grafeas.ListNotesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> grafeas.ListNotesResponse: - r"""Call the list notes method over HTTP. - - Args: - request (~.grafeas.ListNotesRequest): - The request object. Request to list notes. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.grafeas.ListNotesResponse: - Response for listing notes. - """ - - http_options = _BaseGrafeasRestTransport._BaseListNotes._get_http_options() - - request, metadata = self._interceptor.pre_list_notes(request, metadata) - transcoded_request = _BaseGrafeasRestTransport._BaseListNotes._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseGrafeasRestTransport._BaseListNotes._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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 grafeas_v1.GrafeasClient.ListNotes", - extra = { - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "ListNotes", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = GrafeasRestTransport._ListNotes._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 = grafeas.ListNotesResponse() - pb_resp = grafeas.ListNotesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_notes(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = grafeas.ListNotesResponse.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 grafeas_v1.GrafeasClient.list_notes", - extra = { - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "ListNotes", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListOccurrences(_BaseGrafeasRestTransport._BaseListOccurrences, GrafeasRestStub): - def __hash__(self): - return hash("GrafeasRestTransport.ListOccurrences") - - @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: grafeas.ListOccurrencesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> grafeas.ListOccurrencesResponse: - r"""Call the list occurrences method over HTTP. - - Args: - request (~.grafeas.ListOccurrencesRequest): - The request object. Request to list occurrences. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.grafeas.ListOccurrencesResponse: - Response for listing occurrences. - """ - - http_options = _BaseGrafeasRestTransport._BaseListOccurrences._get_http_options() - - request, metadata = self._interceptor.pre_list_occurrences(request, metadata) - transcoded_request = _BaseGrafeasRestTransport._BaseListOccurrences._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseGrafeasRestTransport._BaseListOccurrences._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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 grafeas_v1.GrafeasClient.ListOccurrences", - extra = { - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "ListOccurrences", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = GrafeasRestTransport._ListOccurrences._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 = grafeas.ListOccurrencesResponse() - pb_resp = grafeas.ListOccurrencesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_occurrences(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = grafeas.ListOccurrencesResponse.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 grafeas_v1.GrafeasClient.list_occurrences", - extra = { - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "ListOccurrences", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UpdateNote(_BaseGrafeasRestTransport._BaseUpdateNote, GrafeasRestStub): - def __hash__(self): - return hash("GrafeasRestTransport.UpdateNote") - - @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: grafeas.UpdateNoteRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> grafeas.Note: - r"""Call the update note method over HTTP. - - Args: - request (~.grafeas.UpdateNoteRequest): - The request object. Request to update a note. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.grafeas.Note: - A type of analysis that can be done - for a resource. - - """ - - http_options = _BaseGrafeasRestTransport._BaseUpdateNote._get_http_options() - - request, metadata = self._interceptor.pre_update_note(request, metadata) - transcoded_request = _BaseGrafeasRestTransport._BaseUpdateNote._get_transcoded_request(http_options, request) - - body = _BaseGrafeasRestTransport._BaseUpdateNote._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseGrafeasRestTransport._BaseUpdateNote._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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 grafeas_v1.GrafeasClient.UpdateNote", - extra = { - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "UpdateNote", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = GrafeasRestTransport._UpdateNote._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 = grafeas.Note() - pb_resp = grafeas.Note.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_update_note(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = grafeas.Note.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 grafeas_v1.GrafeasClient.update_note", - extra = { - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "UpdateNote", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UpdateOccurrence(_BaseGrafeasRestTransport._BaseUpdateOccurrence, GrafeasRestStub): - def __hash__(self): - return hash("GrafeasRestTransport.UpdateOccurrence") - - @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: grafeas.UpdateOccurrenceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> grafeas.Occurrence: - r"""Call the update occurrence method over HTTP. - - Args: - request (~.grafeas.UpdateOccurrenceRequest): - The request object. Request to update an occurrence. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.grafeas.Occurrence: - An instance of an analysis type that - has been found on a resource. - - """ - - http_options = _BaseGrafeasRestTransport._BaseUpdateOccurrence._get_http_options() - - request, metadata = self._interceptor.pre_update_occurrence(request, metadata) - transcoded_request = _BaseGrafeasRestTransport._BaseUpdateOccurrence._get_transcoded_request(http_options, request) - - body = _BaseGrafeasRestTransport._BaseUpdateOccurrence._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseGrafeasRestTransport._BaseUpdateOccurrence._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - 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 grafeas_v1.GrafeasClient.UpdateOccurrence", - extra = { - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "UpdateOccurrence", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = GrafeasRestTransport._UpdateOccurrence._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 = grafeas.Occurrence() - pb_resp = grafeas.Occurrence.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_update_occurrence(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = grafeas.Occurrence.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 grafeas_v1.GrafeasClient.update_occurrence", - extra = { - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "UpdateOccurrence", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def batch_create_notes(self) -> Callable[ - [grafeas.BatchCreateNotesRequest], - grafeas.BatchCreateNotesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._BatchCreateNotes(self._session, self._host, self._interceptor) # type: ignore - - @property - def batch_create_occurrences(self) -> Callable[ - [grafeas.BatchCreateOccurrencesRequest], - grafeas.BatchCreateOccurrencesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._BatchCreateOccurrences(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_note(self) -> Callable[ - [grafeas.CreateNoteRequest], - grafeas.Note]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateNote(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_occurrence(self) -> Callable[ - [grafeas.CreateOccurrenceRequest], - grafeas.Occurrence]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateOccurrence(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_note(self) -> Callable[ - [grafeas.DeleteNoteRequest], - 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._DeleteNote(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_occurrence(self) -> Callable[ - [grafeas.DeleteOccurrenceRequest], - 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._DeleteOccurrence(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_note(self) -> Callable[ - [grafeas.GetNoteRequest], - grafeas.Note]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetNote(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_occurrence(self) -> Callable[ - [grafeas.GetOccurrenceRequest], - grafeas.Occurrence]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetOccurrence(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_occurrence_note(self) -> Callable[ - [grafeas.GetOccurrenceNoteRequest], - grafeas.Note]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetOccurrenceNote(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_note_occurrences(self) -> Callable[ - [grafeas.ListNoteOccurrencesRequest], - grafeas.ListNoteOccurrencesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListNoteOccurrences(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_notes(self) -> Callable[ - [grafeas.ListNotesRequest], - grafeas.ListNotesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListNotes(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_occurrences(self) -> Callable[ - [grafeas.ListOccurrencesRequest], - grafeas.ListOccurrencesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListOccurrences(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_note(self) -> Callable[ - [grafeas.UpdateNoteRequest], - grafeas.Note]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateNote(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_occurrence(self) -> Callable[ - [grafeas.UpdateOccurrenceRequest], - grafeas.Occurrence]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateOccurrence(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'GrafeasRestTransport', -) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/rest_base.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/rest_base.py deleted file mode 100644 index 64f998e72c3e..000000000000 --- a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/services/grafeas/transports/rest_base.py +++ /dev/null @@ -1,732 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 GrafeasTransport, 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 grafeas.grafeas_v1.types import grafeas - - -class _BaseGrafeasRestTransport(GrafeasTransport): - """Base REST backend transport for Grafeas. - - 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 = 'containeranalysis.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: 'containeranalysis.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 _BaseBatchCreateNotes: - 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': '/v1/{parent=projects/*}/notes:batchCreate', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}/notes:batchCreate', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = grafeas.BatchCreateNotesRequest.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(_BaseGrafeasRestTransport._BaseBatchCreateNotes._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseBatchCreateOccurrences: - 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': '/v1/{parent=projects/*}/occurrences:batchCreate', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}/occurrences:batchCreate', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = grafeas.BatchCreateOccurrencesRequest.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(_BaseGrafeasRestTransport._BaseBatchCreateOccurrences._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseCreateNote: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "noteId" : "", } - - @classmethod - def _get_unset_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': '/v1/{parent=projects/*}/notes', - 'body': 'note', - }, - { - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}/notes', - 'body': 'note', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = grafeas.CreateNoteRequest.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(_BaseGrafeasRestTransport._BaseCreateNote._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseCreateOccurrence: - 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': '/v1/{parent=projects/*}/occurrences', - 'body': 'occurrence', - }, - { - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}/occurrences', - 'body': 'occurrence', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = grafeas.CreateOccurrenceRequest.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(_BaseGrafeasRestTransport._BaseCreateOccurrence._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteNote: - 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': '/v1/{name=projects/*/notes/*}', - }, - { - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/notes/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = grafeas.DeleteNoteRequest.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(_BaseGrafeasRestTransport._BaseDeleteNote._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteOccurrence: - 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': '/v1/{name=projects/*/occurrences/*}', - }, - { - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/occurrences/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = grafeas.DeleteOccurrenceRequest.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(_BaseGrafeasRestTransport._BaseDeleteOccurrence._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetNote: - 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': '/v1/{name=projects/*/notes/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/notes/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = grafeas.GetNoteRequest.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(_BaseGrafeasRestTransport._BaseGetNote._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetOccurrence: - 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': '/v1/{name=projects/*/occurrences/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/occurrences/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = grafeas.GetOccurrenceRequest.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(_BaseGrafeasRestTransport._BaseGetOccurrence._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetOccurrenceNote: - 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': '/v1/{name=projects/*/occurrences/*}/notes', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/occurrences/*}/notes', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = grafeas.GetOccurrenceNoteRequest.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(_BaseGrafeasRestTransport._BaseGetOccurrenceNote._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListNoteOccurrences: - 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': '/v1/{name=projects/*/notes/*}/occurrences', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/notes/*}/occurrences', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = grafeas.ListNoteOccurrencesRequest.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(_BaseGrafeasRestTransport._BaseListNoteOccurrences._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListNotes: - 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': '/v1/{parent=projects/*}/notes', - }, - { - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}/notes', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = grafeas.ListNotesRequest.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(_BaseGrafeasRestTransport._BaseListNotes._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListOccurrences: - 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': '/v1/{parent=projects/*}/occurrences', - }, - { - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}/occurrences', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = grafeas.ListOccurrencesRequest.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(_BaseGrafeasRestTransport._BaseListOccurrences._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateNote: - 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': '/v1/{name=projects/*/notes/*}', - 'body': 'note', - }, - { - 'method': 'patch', - 'uri': '/v1/{name=projects/*/locations/*/notes/*}', - 'body': 'note', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = grafeas.UpdateNoteRequest.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(_BaseGrafeasRestTransport._BaseUpdateNote._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateOccurrence: - 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': '/v1/{name=projects/*/occurrences/*}', - 'body': 'occurrence', - }, - { - 'method': 'patch', - 'uri': '/v1/{name=projects/*/locations/*/occurrences/*}', - 'body': 'occurrence', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = grafeas.UpdateOccurrenceRequest.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(_BaseGrafeasRestTransport._BaseUpdateOccurrence._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseGrafeasRestTransport', -) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/__init__.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/__init__.py deleted file mode 100644 index 76e667190447..000000000000 --- a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/__init__.py +++ /dev/null @@ -1,244 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .attestation import ( - AttestationNote, - AttestationOccurrence, - Jwt, -) -from .build import ( - BuildNote, - BuildOccurrence, -) -from .common import ( - Digest, - Envelope, - EnvelopeSignature, - FileLocation, - License, - RelatedUrl, - Signature, - NoteKind, -) -from .compliance import ( - ComplianceNote, - ComplianceOccurrence, - ComplianceVersion, - NonCompliantFile, -) -from .cvss import ( - CVSS, - CVSSv3, - CVSSVersion, -) -from .deployment import ( - DeploymentNote, - DeploymentOccurrence, -) -from .discovery import ( - DiscoveryNote, - DiscoveryOccurrence, -) -from .dsse_attestation import ( - DSSEAttestationNote, - DSSEAttestationOccurrence, -) -from .grafeas import ( - BatchCreateNotesRequest, - BatchCreateNotesResponse, - BatchCreateOccurrencesRequest, - BatchCreateOccurrencesResponse, - CreateNoteRequest, - CreateOccurrenceRequest, - DeleteNoteRequest, - DeleteOccurrenceRequest, - GetNoteRequest, - GetOccurrenceNoteRequest, - GetOccurrenceRequest, - ListNoteOccurrencesRequest, - ListNoteOccurrencesResponse, - ListNotesRequest, - ListNotesResponse, - ListOccurrencesRequest, - ListOccurrencesResponse, - Note, - Occurrence, - UpdateNoteRequest, - UpdateOccurrenceRequest, -) -from .image import ( - Fingerprint, - ImageNote, - ImageOccurrence, - Layer, -) -from .intoto_provenance import ( - BuilderConfig, - Completeness, - InTotoProvenance, - Metadata, - Recipe, -) -from .intoto_statement import ( - InTotoSlsaProvenanceV1, - InTotoStatement, - Subject, -) -from .package import ( - Distribution, - Location, - PackageNote, - PackageOccurrence, - Version, - Architecture, -) -from .provenance import ( - AliasContext, - Artifact, - BuildProvenance, - CloudRepoSourceContext, - Command, - FileHashes, - GerritSourceContext, - GitSourceContext, - Hash, - ProjectRepoId, - RepoId, - Source, - SourceContext, -) -from .sbom import ( - SbomReferenceIntotoPayload, - SbomReferenceIntotoPredicate, - SBOMReferenceNote, - SBOMReferenceOccurrence, -) -from .severity import ( - Severity, -) -from .slsa_provenance import ( - SlsaProvenance, -) -from .slsa_provenance_zero_two import ( - SlsaProvenanceZeroTwo, -) -from .upgrade import ( - UpgradeDistribution, - UpgradeNote, - UpgradeOccurrence, - WindowsUpdate, -) -from .vex import ( - VulnerabilityAssessmentNote, -) -from .vulnerability import ( - VulnerabilityNote, - VulnerabilityOccurrence, -) - -__all__ = ( - 'AttestationNote', - 'AttestationOccurrence', - 'Jwt', - 'BuildNote', - 'BuildOccurrence', - 'Digest', - 'Envelope', - 'EnvelopeSignature', - 'FileLocation', - 'License', - 'RelatedUrl', - 'Signature', - 'NoteKind', - 'ComplianceNote', - 'ComplianceOccurrence', - 'ComplianceVersion', - 'NonCompliantFile', - 'CVSS', - 'CVSSv3', - 'CVSSVersion', - 'DeploymentNote', - 'DeploymentOccurrence', - 'DiscoveryNote', - 'DiscoveryOccurrence', - 'DSSEAttestationNote', - 'DSSEAttestationOccurrence', - 'BatchCreateNotesRequest', - 'BatchCreateNotesResponse', - 'BatchCreateOccurrencesRequest', - 'BatchCreateOccurrencesResponse', - 'CreateNoteRequest', - 'CreateOccurrenceRequest', - 'DeleteNoteRequest', - 'DeleteOccurrenceRequest', - 'GetNoteRequest', - 'GetOccurrenceNoteRequest', - 'GetOccurrenceRequest', - 'ListNoteOccurrencesRequest', - 'ListNoteOccurrencesResponse', - 'ListNotesRequest', - 'ListNotesResponse', - 'ListOccurrencesRequest', - 'ListOccurrencesResponse', - 'Note', - 'Occurrence', - 'UpdateNoteRequest', - 'UpdateOccurrenceRequest', - 'Fingerprint', - 'ImageNote', - 'ImageOccurrence', - 'Layer', - 'BuilderConfig', - 'Completeness', - 'InTotoProvenance', - 'Metadata', - 'Recipe', - 'InTotoSlsaProvenanceV1', - 'InTotoStatement', - 'Subject', - 'Distribution', - 'Location', - 'PackageNote', - 'PackageOccurrence', - 'Version', - 'Architecture', - 'AliasContext', - 'Artifact', - 'BuildProvenance', - 'CloudRepoSourceContext', - 'Command', - 'FileHashes', - 'GerritSourceContext', - 'GitSourceContext', - 'Hash', - 'ProjectRepoId', - 'RepoId', - 'Source', - 'SourceContext', - 'SbomReferenceIntotoPayload', - 'SbomReferenceIntotoPredicate', - 'SBOMReferenceNote', - 'SBOMReferenceOccurrence', - 'Severity', - 'SlsaProvenance', - 'SlsaProvenanceZeroTwo', - 'UpgradeDistribution', - 'UpgradeNote', - 'UpgradeOccurrence', - 'WindowsUpdate', - 'VulnerabilityAssessmentNote', - 'VulnerabilityNote', - 'VulnerabilityOccurrence', -) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/attestation.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/attestation.py deleted file mode 100644 index b001a8ec82a7..000000000000 --- a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/attestation.py +++ /dev/null @@ -1,148 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 grafeas.grafeas_v1.types import common - - -__protobuf__ = proto.module( - package='grafeas.v1', - manifest={ - 'AttestationNote', - 'Jwt', - 'AttestationOccurrence', - }, -) - - -class AttestationNote(proto.Message): - r"""Note kind that represents a logical attestation "role" or - "authority". For example, an organization might have one - ``Authority`` for "QA" and one for "build". This note is intended to - act strictly as a grouping mechanism for the attached occurrences - (Attestations). This grouping mechanism also provides a security - boundary, since IAM ACLs gate the ability for a principle to attach - an occurrence to a given note. It also provides a single point of - lookup to find all attached attestation occurrences, even if they - don't all live in the same project. - - Attributes: - hint (grafeas.grafeas_v1.types.AttestationNote.Hint): - Hint hints at the purpose of the attestation - authority. - """ - - class Hint(proto.Message): - r"""This submessage provides human-readable hints about the - purpose of the authority. Because the name of a note acts as its - resource reference, it is important to disambiguate the - canonical name of the Note (which might be a UUID for security - purposes) from "readable" names more suitable for debug output. - Note that these hints should not be used to look up authorities - in security sensitive contexts, such as when looking up - attestations to verify. - - Attributes: - human_readable_name (str): - Required. The human readable name of this - attestation authority, for example "qa". - """ - - human_readable_name: str = proto.Field( - proto.STRING, - number=1, - ) - - hint: Hint = proto.Field( - proto.MESSAGE, - number=1, - message=Hint, - ) - - -class Jwt(proto.Message): - r""" - - Attributes: - compact_jwt (str): - The compact encoding of a JWS, which is - always three base64 encoded strings joined by - periods. For details, see: - - https://tools.ietf.org/html/rfc7515.html#section-3.1 - """ - - compact_jwt: str = proto.Field( - proto.STRING, - number=1, - ) - - -class AttestationOccurrence(proto.Message): - r"""Occurrence that represents a single "attestation". The - authenticity of an attestation can be verified using the - attached signature. If the verifier trusts the public key of the - signer, then verifying the signature is sufficient to establish - trust. In this circumstance, the authority to which this - attestation is attached is primarily useful for lookup (how to - find this attestation if you already know the authority and - artifact to be verified) and intent (for which authority this - attestation was intended to sign. - - Attributes: - serialized_payload (bytes): - Required. The serialized payload that is verified by one or - more ``signatures``. - signatures (MutableSequence[grafeas.grafeas_v1.types.Signature]): - One or more signatures over ``serialized_payload``. Verifier - implementations should consider this attestation message - verified if at least one ``signature`` verifies - ``serialized_payload``. See ``Signature`` in common.proto - for more details on signature structure and verification. - jwts (MutableSequence[grafeas.grafeas_v1.types.Jwt]): - One or more JWTs encoding a self-contained attestation. Each - JWT encodes the payload that it verifies within the JWT - itself. Verifier implementation SHOULD ignore the - ``serialized_payload`` field when verifying these JWTs. If - only JWTs are present on this AttestationOccurrence, then - the ``serialized_payload`` SHOULD be left empty. Each JWT - SHOULD encode a claim specific to the ``resource_uri`` of - this Occurrence, but this is not validated by Grafeas - metadata API implementations. The JWT itself is opaque to - Grafeas. - """ - - serialized_payload: bytes = proto.Field( - proto.BYTES, - number=1, - ) - signatures: MutableSequence[common.Signature] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=common.Signature, - ) - jwts: MutableSequence['Jwt'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Jwt', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/build.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/build.py deleted file mode 100644 index 10eea8a73894..000000000000 --- a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/build.py +++ /dev/null @@ -1,115 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 grafeas.grafeas_v1.types import intoto_provenance as g_intoto_provenance -from grafeas.grafeas_v1.types import intoto_statement as g_intoto_statement -from grafeas.grafeas_v1.types import provenance as g_provenance - - -__protobuf__ = proto.module( - package='grafeas.v1', - manifest={ - 'BuildNote', - 'BuildOccurrence', - }, -) - - -class BuildNote(proto.Message): - r"""Note holding the version of the provider's builder and the - signature of the provenance message in the build details - occurrence. - - Attributes: - builder_version (str): - Required. Immutable. Version of the builder - which produced this build. - """ - - builder_version: str = proto.Field( - proto.STRING, - number=1, - ) - - -class BuildOccurrence(proto.Message): - r"""Details of a build occurrence. - - Attributes: - provenance (grafeas.grafeas_v1.types.BuildProvenance): - The actual provenance for the build. - provenance_bytes (str): - Serialized JSON representation of the provenance, used in - generating the build signature in the corresponding build - note. After verifying the signature, ``provenance_bytes`` - can be unmarshalled and compared to the provenance to - confirm that it is unchanged. A base64-encoded string - representation of the provenance bytes is used for the - signature in order to interoperate with openssl which - expects this format for signature verification. - - The serialized form is captured both to avoid ambiguity in - how the provenance is marshalled to json as well to prevent - incompatibilities with future changes. - intoto_provenance (grafeas.grafeas_v1.types.InTotoProvenance): - Deprecated. See InTotoStatement for the - replacement. In-toto Provenance representation - as defined in spec. - intoto_statement (grafeas.grafeas_v1.types.InTotoStatement): - In-toto Statement representation as defined in spec. The - intoto_statement can contain any type of provenance. The - serialized payload of the statement can be stored and signed - in the Occurrence's envelope. - in_toto_slsa_provenance_v1 (grafeas.grafeas_v1.types.InTotoSlsaProvenanceV1): - In-Toto Slsa Provenance V1 represents a slsa - provenance meeting the slsa spec, wrapped in an - in-toto statement. This allows for direct - jsonification of a to-spec in-toto slsa - statement with a to-spec slsa provenance. - """ - - provenance: g_provenance.BuildProvenance = proto.Field( - proto.MESSAGE, - number=1, - message=g_provenance.BuildProvenance, - ) - provenance_bytes: str = proto.Field( - proto.STRING, - number=2, - ) - intoto_provenance: g_intoto_provenance.InTotoProvenance = proto.Field( - proto.MESSAGE, - number=3, - message=g_intoto_provenance.InTotoProvenance, - ) - intoto_statement: g_intoto_statement.InTotoStatement = proto.Field( - proto.MESSAGE, - number=4, - message=g_intoto_statement.InTotoStatement, - ) - in_toto_slsa_provenance_v1: g_intoto_statement.InTotoSlsaProvenanceV1 = proto.Field( - proto.MESSAGE, - number=5, - message=g_intoto_statement.InTotoSlsaProvenanceV1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/common.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/common.py deleted file mode 100644 index 047f564874ba..000000000000 --- a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/common.py +++ /dev/null @@ -1,295 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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='grafeas.v1', - manifest={ - 'NoteKind', - 'RelatedUrl', - 'Signature', - 'Envelope', - 'EnvelopeSignature', - 'FileLocation', - 'License', - 'Digest', - }, -) - - -class NoteKind(proto.Enum): - r"""Kind represents the kinds of notes supported. - - Values: - NOTE_KIND_UNSPECIFIED (0): - Default value. This value is unused. - VULNERABILITY (1): - The note and occurrence represent a package - vulnerability. - BUILD (2): - The note and occurrence assert build - provenance. - IMAGE (3): - This represents an image basis relationship. - PACKAGE (4): - This represents a package installed via a - package manager. - DEPLOYMENT (5): - The note and occurrence track deployment - events. - DISCOVERY (6): - The note and occurrence track the initial - discovery status of a resource. - ATTESTATION (7): - This represents a logical "role" that can - attest to artifacts. - UPGRADE (8): - This represents an available package upgrade. - COMPLIANCE (9): - This represents a Compliance Note - DSSE_ATTESTATION (10): - This represents a DSSE attestation Note - VULNERABILITY_ASSESSMENT (11): - This represents a Vulnerability Assessment. - SBOM_REFERENCE (12): - This represents an SBOM Reference. - """ - NOTE_KIND_UNSPECIFIED = 0 - VULNERABILITY = 1 - BUILD = 2 - IMAGE = 3 - PACKAGE = 4 - DEPLOYMENT = 5 - DISCOVERY = 6 - ATTESTATION = 7 - UPGRADE = 8 - COMPLIANCE = 9 - DSSE_ATTESTATION = 10 - VULNERABILITY_ASSESSMENT = 11 - SBOM_REFERENCE = 12 - - -class RelatedUrl(proto.Message): - r"""Metadata for any related URL information. - - Attributes: - url (str): - Specific URL associated with the resource. - label (str): - Label to describe usage of the URL. - """ - - url: str = proto.Field( - proto.STRING, - number=1, - ) - label: str = proto.Field( - proto.STRING, - number=2, - ) - - -class Signature(proto.Message): - r"""Verifiers (e.g. Kritis implementations) MUST verify signatures with - respect to the trust anchors defined in policy (e.g. a Kritis - policy). Typically this means that the verifier has been configured - with a map from ``public_key_id`` to public key material (and any - required parameters, e.g. signing algorithm). - - In particular, verification implementations MUST NOT treat the - signature ``public_key_id`` as anything more than a key lookup hint. - The ``public_key_id`` DOES NOT validate or authenticate a public - key; it only provides a mechanism for quickly selecting a public key - ALREADY CONFIGURED on the verifier through a trusted channel. - Verification implementations MUST reject signatures in any of the - following circumstances: - - - The ``public_key_id`` is not recognized by the verifier. - - The public key that ``public_key_id`` refers to does not verify - the signature with respect to the payload. - - The ``signature`` contents SHOULD NOT be "attached" (where the - payload is included with the serialized ``signature`` bytes). - Verifiers MUST ignore any "attached" payload and only verify - signatures with respect to explicitly provided payload (e.g. a - ``payload`` field on the proto message that holds this Signature, or - the canonical serialization of the proto message that holds this - signature). - - Attributes: - signature (bytes): - The content of the signature, an opaque - bytestring. The payload that this signature - verifies MUST be unambiguously provided with the - Signature during verification. A wrapper message - might provide the payload explicitly. - Alternatively, a message might have a canonical - serialization that can always be unambiguously - computed to derive the payload. - public_key_id (str): - The identifier for the public key that verifies this - signature. - - - The ``public_key_id`` is required. - - The ``public_key_id`` SHOULD be an RFC3986 conformant - URI. - - When possible, the ``public_key_id`` SHOULD be an - immutable reference, such as a cryptographic digest. - - Examples of valid ``public_key_id``\ s: - - OpenPGP V4 public key fingerprint: - - - "openpgp4fpr:74FAF3B861BDA0870C7B6DEF607E48D2A663AEEA" - See - https://www.iana.org/assignments/uri-schemes/prov/openpgp4fpr - for more details on this scheme. - - RFC6920 digest-named SubjectPublicKeyInfo (digest of the DER - serialization): - - - "ni:///sha-256;cD9o9Cq6LG3jD0iKXqEi_vdjJGecm_iXkbqVoScViaU" - - "nih:///sha-256;703f68f42aba2c6de30f488a5ea122fef76324679c9bf89791ba95a1271589a5". - """ - - signature: bytes = proto.Field( - proto.BYTES, - number=1, - ) - public_key_id: str = proto.Field( - proto.STRING, - number=2, - ) - - -class Envelope(proto.Message): - r"""MUST match - https://github.com/secure-systems-lab/dsse/blob/master/envelope.proto. - An authenticated message of arbitrary type. - - Attributes: - payload (bytes): - - payload_type (str): - - signatures (MutableSequence[grafeas.grafeas_v1.types.EnvelopeSignature]): - - """ - - payload: bytes = proto.Field( - proto.BYTES, - number=1, - ) - payload_type: str = proto.Field( - proto.STRING, - number=2, - ) - signatures: MutableSequence['EnvelopeSignature'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='EnvelopeSignature', - ) - - -class EnvelopeSignature(proto.Message): - r""" - - Attributes: - sig (bytes): - - keyid (str): - - """ - - sig: bytes = proto.Field( - proto.BYTES, - number=1, - ) - keyid: str = proto.Field( - proto.STRING, - number=2, - ) - - -class FileLocation(proto.Message): - r"""Indicates the location at which a package was found. - - Attributes: - file_path (str): - For jars that are contained inside .war - files, this filepath can indicate the path to - war file combined with the path to jar file. - """ - - file_path: str = proto.Field( - proto.STRING, - number=1, - ) - - -class License(proto.Message): - r"""License information. - - Attributes: - expression (str): - Often a single license can be used to - represent the licensing terms. Sometimes it is - necessary to include a choice of one or more - licenses or some combination of license - identifiers. - Examples: "LGPL-2.1-only OR MIT", "LGPL-2.1-only - AND MIT", "GPL-2.0-or-later WITH - Bison-exception-2.2". - comments (str): - Comments - """ - - expression: str = proto.Field( - proto.STRING, - number=1, - ) - comments: str = proto.Field( - proto.STRING, - number=2, - ) - - -class Digest(proto.Message): - r"""Digest information. - - Attributes: - algo (str): - ``SHA1``, ``SHA512`` etc. - digest_bytes (bytes): - Value of the digest. - """ - - algo: str = proto.Field( - proto.STRING, - number=1, - ) - digest_bytes: bytes = proto.Field( - proto.BYTES, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/compliance.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/compliance.py deleted file mode 100644 index b770fe9748cc..000000000000 --- a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/compliance.py +++ /dev/null @@ -1,215 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 grafeas.grafeas_v1.types import severity as g_severity - - -__protobuf__ = proto.module( - package='grafeas.v1', - manifest={ - 'ComplianceNote', - 'ComplianceVersion', - 'ComplianceOccurrence', - 'NonCompliantFile', - }, -) - - -class ComplianceNote(proto.Message): - r""" - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - title (str): - The title that identifies this compliance - check. - description (str): - A description about this compliance check. - version (MutableSequence[grafeas.grafeas_v1.types.ComplianceVersion]): - The OS and config versions the benchmark - applies to. - rationale (str): - A rationale for the existence of this - compliance check. - remediation (str): - A description of remediation steps if the - compliance check fails. - cis_benchmark (grafeas.grafeas_v1.types.ComplianceNote.CisBenchmark): - - This field is a member of `oneof`_ ``compliance_type``. - scan_instructions (bytes): - Serialized scan instructions with a - predefined format. - impact (str): - - This field is a member of `oneof`_ ``potential_impact``. - """ - - class CisBenchmark(proto.Message): - r"""A compliance check that is a CIS benchmark. - - Attributes: - profile_level (int): - - severity (grafeas.grafeas_v1.types.Severity): - - """ - - profile_level: int = proto.Field( - proto.INT32, - number=1, - ) - severity: g_severity.Severity = proto.Field( - proto.ENUM, - number=2, - enum=g_severity.Severity, - ) - - title: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - version: MutableSequence['ComplianceVersion'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='ComplianceVersion', - ) - rationale: str = proto.Field( - proto.STRING, - number=4, - ) - remediation: str = proto.Field( - proto.STRING, - number=5, - ) - cis_benchmark: CisBenchmark = proto.Field( - proto.MESSAGE, - number=6, - oneof='compliance_type', - message=CisBenchmark, - ) - scan_instructions: bytes = proto.Field( - proto.BYTES, - number=7, - ) - impact: str = proto.Field( - proto.STRING, - number=8, - oneof='potential_impact', - ) - - -class ComplianceVersion(proto.Message): - r"""Describes the CIS benchmark version that is applicable to a - given OS and os version. - - Attributes: - cpe_uri (str): - The CPE URI - (https://cpe.mitre.org/specification/) this - benchmark is applicable to. - benchmark_document (str): - The name of the document that defines this - benchmark, e.g. "CIS Container-Optimized OS". - version (str): - The version of the benchmark. This is set to - the version of the OS-specific CIS document the - benchmark is defined in. - """ - - cpe_uri: str = proto.Field( - proto.STRING, - number=1, - ) - benchmark_document: str = proto.Field( - proto.STRING, - number=3, - ) - version: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ComplianceOccurrence(proto.Message): - r"""An indication that the compliance checks in the associated - ComplianceNote were not satisfied for particular resources or a - specified reason. - - Attributes: - non_compliant_files (MutableSequence[grafeas.grafeas_v1.types.NonCompliantFile]): - - non_compliance_reason (str): - - version (grafeas.grafeas_v1.types.ComplianceVersion): - The OS and config version the benchmark was - run on. - """ - - non_compliant_files: MutableSequence['NonCompliantFile'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='NonCompliantFile', - ) - non_compliance_reason: str = proto.Field( - proto.STRING, - number=3, - ) - version: 'ComplianceVersion' = proto.Field( - proto.MESSAGE, - number=4, - message='ComplianceVersion', - ) - - -class NonCompliantFile(proto.Message): - r"""Details about files that caused a compliance check to fail. - - Attributes: - path (str): - Empty if ``display_command`` is set. - display_command (str): - Command to display the non-compliant files. - reason (str): - Explains why a file is non compliant for a - CIS check. - """ - - path: str = proto.Field( - proto.STRING, - number=1, - ) - display_command: str = proto.Field( - proto.STRING, - number=2, - ) - reason: str = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/cvss.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/cvss.py deleted file mode 100644 index e0e252edac00..000000000000 --- a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/cvss.py +++ /dev/null @@ -1,464 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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='grafeas.v1', - manifest={ - 'CVSSVersion', - 'CVSSv3', - 'CVSS', - }, -) - - -class CVSSVersion(proto.Enum): - r"""CVSS Version. - - Values: - CVSS_VERSION_UNSPECIFIED (0): - No description available. - CVSS_VERSION_2 (1): - No description available. - CVSS_VERSION_3 (2): - No description available. - """ - CVSS_VERSION_UNSPECIFIED = 0 - CVSS_VERSION_2 = 1 - CVSS_VERSION_3 = 2 - - -class CVSSv3(proto.Message): - r"""Common Vulnerability Scoring System version 3. - For details, see - https://www.first.org/cvss/specification-document - - Attributes: - base_score (float): - The base score is a function of the base - metric scores. - exploitability_score (float): - - impact_score (float): - - attack_vector (grafeas.grafeas_v1.types.CVSSv3.AttackVector): - Base Metrics - Represents the intrinsic characteristics of a - vulnerability that are constant over time and - across user environments. - attack_complexity (grafeas.grafeas_v1.types.CVSSv3.AttackComplexity): - - privileges_required (grafeas.grafeas_v1.types.CVSSv3.PrivilegesRequired): - - user_interaction (grafeas.grafeas_v1.types.CVSSv3.UserInteraction): - - scope (grafeas.grafeas_v1.types.CVSSv3.Scope): - - confidentiality_impact (grafeas.grafeas_v1.types.CVSSv3.Impact): - - integrity_impact (grafeas.grafeas_v1.types.CVSSv3.Impact): - - availability_impact (grafeas.grafeas_v1.types.CVSSv3.Impact): - - """ - class AttackVector(proto.Enum): - r""" - - Values: - ATTACK_VECTOR_UNSPECIFIED (0): - No description available. - ATTACK_VECTOR_NETWORK (1): - No description available. - ATTACK_VECTOR_ADJACENT (2): - No description available. - ATTACK_VECTOR_LOCAL (3): - No description available. - ATTACK_VECTOR_PHYSICAL (4): - No description available. - """ - ATTACK_VECTOR_UNSPECIFIED = 0 - ATTACK_VECTOR_NETWORK = 1 - ATTACK_VECTOR_ADJACENT = 2 - ATTACK_VECTOR_LOCAL = 3 - ATTACK_VECTOR_PHYSICAL = 4 - - class AttackComplexity(proto.Enum): - r""" - - Values: - ATTACK_COMPLEXITY_UNSPECIFIED (0): - No description available. - ATTACK_COMPLEXITY_LOW (1): - No description available. - ATTACK_COMPLEXITY_HIGH (2): - No description available. - """ - ATTACK_COMPLEXITY_UNSPECIFIED = 0 - ATTACK_COMPLEXITY_LOW = 1 - ATTACK_COMPLEXITY_HIGH = 2 - - class PrivilegesRequired(proto.Enum): - r""" - - Values: - PRIVILEGES_REQUIRED_UNSPECIFIED (0): - No description available. - PRIVILEGES_REQUIRED_NONE (1): - No description available. - PRIVILEGES_REQUIRED_LOW (2): - No description available. - PRIVILEGES_REQUIRED_HIGH (3): - No description available. - """ - PRIVILEGES_REQUIRED_UNSPECIFIED = 0 - PRIVILEGES_REQUIRED_NONE = 1 - PRIVILEGES_REQUIRED_LOW = 2 - PRIVILEGES_REQUIRED_HIGH = 3 - - class UserInteraction(proto.Enum): - r""" - - Values: - USER_INTERACTION_UNSPECIFIED (0): - No description available. - USER_INTERACTION_NONE (1): - No description available. - USER_INTERACTION_REQUIRED (2): - No description available. - """ - USER_INTERACTION_UNSPECIFIED = 0 - USER_INTERACTION_NONE = 1 - USER_INTERACTION_REQUIRED = 2 - - class Scope(proto.Enum): - r""" - - Values: - SCOPE_UNSPECIFIED (0): - No description available. - SCOPE_UNCHANGED (1): - No description available. - SCOPE_CHANGED (2): - No description available. - """ - SCOPE_UNSPECIFIED = 0 - SCOPE_UNCHANGED = 1 - SCOPE_CHANGED = 2 - - class Impact(proto.Enum): - r""" - - Values: - IMPACT_UNSPECIFIED (0): - No description available. - IMPACT_HIGH (1): - No description available. - IMPACT_LOW (2): - No description available. - IMPACT_NONE (3): - No description available. - """ - IMPACT_UNSPECIFIED = 0 - IMPACT_HIGH = 1 - IMPACT_LOW = 2 - IMPACT_NONE = 3 - - base_score: float = proto.Field( - proto.FLOAT, - number=1, - ) - exploitability_score: float = proto.Field( - proto.FLOAT, - number=2, - ) - impact_score: float = proto.Field( - proto.FLOAT, - number=3, - ) - attack_vector: AttackVector = proto.Field( - proto.ENUM, - number=5, - enum=AttackVector, - ) - attack_complexity: AttackComplexity = proto.Field( - proto.ENUM, - number=6, - enum=AttackComplexity, - ) - privileges_required: PrivilegesRequired = proto.Field( - proto.ENUM, - number=7, - enum=PrivilegesRequired, - ) - user_interaction: UserInteraction = proto.Field( - proto.ENUM, - number=8, - enum=UserInteraction, - ) - scope: Scope = proto.Field( - proto.ENUM, - number=9, - enum=Scope, - ) - confidentiality_impact: Impact = proto.Field( - proto.ENUM, - number=10, - enum=Impact, - ) - integrity_impact: Impact = proto.Field( - proto.ENUM, - number=11, - enum=Impact, - ) - availability_impact: Impact = proto.Field( - proto.ENUM, - number=12, - enum=Impact, - ) - - -class CVSS(proto.Message): - r"""Common Vulnerability Scoring System. - For details, see - https://www.first.org/cvss/specification-document This is a - message we will try to use for storing various versions of CVSS - rather than making a separate proto for storing a specific - version. - - Attributes: - base_score (float): - The base score is a function of the base - metric scores. - exploitability_score (float): - - impact_score (float): - - attack_vector (grafeas.grafeas_v1.types.CVSS.AttackVector): - Base Metrics - Represents the intrinsic characteristics of a - vulnerability that are constant over time and - across user environments. - attack_complexity (grafeas.grafeas_v1.types.CVSS.AttackComplexity): - - authentication (grafeas.grafeas_v1.types.CVSS.Authentication): - - privileges_required (grafeas.grafeas_v1.types.CVSS.PrivilegesRequired): - - user_interaction (grafeas.grafeas_v1.types.CVSS.UserInteraction): - - scope (grafeas.grafeas_v1.types.CVSS.Scope): - - confidentiality_impact (grafeas.grafeas_v1.types.CVSS.Impact): - - integrity_impact (grafeas.grafeas_v1.types.CVSS.Impact): - - availability_impact (grafeas.grafeas_v1.types.CVSS.Impact): - - """ - class AttackVector(proto.Enum): - r""" - - Values: - ATTACK_VECTOR_UNSPECIFIED (0): - No description available. - ATTACK_VECTOR_NETWORK (1): - No description available. - ATTACK_VECTOR_ADJACENT (2): - No description available. - ATTACK_VECTOR_LOCAL (3): - No description available. - ATTACK_VECTOR_PHYSICAL (4): - No description available. - """ - ATTACK_VECTOR_UNSPECIFIED = 0 - ATTACK_VECTOR_NETWORK = 1 - ATTACK_VECTOR_ADJACENT = 2 - ATTACK_VECTOR_LOCAL = 3 - ATTACK_VECTOR_PHYSICAL = 4 - - class AttackComplexity(proto.Enum): - r""" - - Values: - ATTACK_COMPLEXITY_UNSPECIFIED (0): - No description available. - ATTACK_COMPLEXITY_LOW (1): - No description available. - ATTACK_COMPLEXITY_HIGH (2): - No description available. - ATTACK_COMPLEXITY_MEDIUM (3): - No description available. - """ - ATTACK_COMPLEXITY_UNSPECIFIED = 0 - ATTACK_COMPLEXITY_LOW = 1 - ATTACK_COMPLEXITY_HIGH = 2 - ATTACK_COMPLEXITY_MEDIUM = 3 - - class Authentication(proto.Enum): - r""" - - Values: - AUTHENTICATION_UNSPECIFIED (0): - No description available. - AUTHENTICATION_MULTIPLE (1): - No description available. - AUTHENTICATION_SINGLE (2): - No description available. - AUTHENTICATION_NONE (3): - No description available. - """ - AUTHENTICATION_UNSPECIFIED = 0 - AUTHENTICATION_MULTIPLE = 1 - AUTHENTICATION_SINGLE = 2 - AUTHENTICATION_NONE = 3 - - class PrivilegesRequired(proto.Enum): - r""" - - Values: - PRIVILEGES_REQUIRED_UNSPECIFIED (0): - No description available. - PRIVILEGES_REQUIRED_NONE (1): - No description available. - PRIVILEGES_REQUIRED_LOW (2): - No description available. - PRIVILEGES_REQUIRED_HIGH (3): - No description available. - """ - PRIVILEGES_REQUIRED_UNSPECIFIED = 0 - PRIVILEGES_REQUIRED_NONE = 1 - PRIVILEGES_REQUIRED_LOW = 2 - PRIVILEGES_REQUIRED_HIGH = 3 - - class UserInteraction(proto.Enum): - r""" - - Values: - USER_INTERACTION_UNSPECIFIED (0): - No description available. - USER_INTERACTION_NONE (1): - No description available. - USER_INTERACTION_REQUIRED (2): - No description available. - """ - USER_INTERACTION_UNSPECIFIED = 0 - USER_INTERACTION_NONE = 1 - USER_INTERACTION_REQUIRED = 2 - - class Scope(proto.Enum): - r""" - - Values: - SCOPE_UNSPECIFIED (0): - No description available. - SCOPE_UNCHANGED (1): - No description available. - SCOPE_CHANGED (2): - No description available. - """ - SCOPE_UNSPECIFIED = 0 - SCOPE_UNCHANGED = 1 - SCOPE_CHANGED = 2 - - class Impact(proto.Enum): - r""" - - Values: - IMPACT_UNSPECIFIED (0): - No description available. - IMPACT_HIGH (1): - No description available. - IMPACT_LOW (2): - No description available. - IMPACT_NONE (3): - No description available. - IMPACT_PARTIAL (4): - No description available. - IMPACT_COMPLETE (5): - No description available. - """ - IMPACT_UNSPECIFIED = 0 - IMPACT_HIGH = 1 - IMPACT_LOW = 2 - IMPACT_NONE = 3 - IMPACT_PARTIAL = 4 - IMPACT_COMPLETE = 5 - - base_score: float = proto.Field( - proto.FLOAT, - number=1, - ) - exploitability_score: float = proto.Field( - proto.FLOAT, - number=2, - ) - impact_score: float = proto.Field( - proto.FLOAT, - number=3, - ) - attack_vector: AttackVector = proto.Field( - proto.ENUM, - number=4, - enum=AttackVector, - ) - attack_complexity: AttackComplexity = proto.Field( - proto.ENUM, - number=5, - enum=AttackComplexity, - ) - authentication: Authentication = proto.Field( - proto.ENUM, - number=6, - enum=Authentication, - ) - privileges_required: PrivilegesRequired = proto.Field( - proto.ENUM, - number=7, - enum=PrivilegesRequired, - ) - user_interaction: UserInteraction = proto.Field( - proto.ENUM, - number=8, - enum=UserInteraction, - ) - scope: Scope = proto.Field( - proto.ENUM, - number=9, - enum=Scope, - ) - confidentiality_impact: Impact = proto.Field( - proto.ENUM, - number=10, - enum=Impact, - ) - integrity_impact: Impact = proto.Field( - proto.ENUM, - number=11, - enum=Impact, - ) - availability_impact: Impact = proto.Field( - proto.ENUM, - number=12, - enum=Impact, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/deployment.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/deployment.py deleted file mode 100644 index d22e451c7744..000000000000 --- a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/deployment.py +++ /dev/null @@ -1,125 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='grafeas.v1', - manifest={ - 'DeploymentNote', - 'DeploymentOccurrence', - }, -) - - -class DeploymentNote(proto.Message): - r"""An artifact that can be deployed in some runtime. - - Attributes: - resource_uri (MutableSequence[str]): - Required. Resource URI for the artifact being - deployed. - """ - - resource_uri: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - - -class DeploymentOccurrence(proto.Message): - r"""The period during which some deployable was active in a - runtime. - - Attributes: - user_email (str): - Identity of the user that triggered this - deployment. - deploy_time (google.protobuf.timestamp_pb2.Timestamp): - Required. Beginning of the lifetime of this - deployment. - undeploy_time (google.protobuf.timestamp_pb2.Timestamp): - End of the lifetime of this deployment. - config (str): - Configuration used to create this deployment. - address (str): - Address of the runtime element hosting this - deployment. - resource_uri (MutableSequence[str]): - Output only. Resource URI for the artifact - being deployed taken from the deployable field - with the same name. - platform (grafeas.grafeas_v1.types.DeploymentOccurrence.Platform): - Platform hosting this deployment. - """ - class Platform(proto.Enum): - r"""Types of platforms. - - Values: - PLATFORM_UNSPECIFIED (0): - Unknown. - GKE (1): - Google Container Engine. - FLEX (2): - Google App Engine: Flexible Environment. - CUSTOM (3): - Custom user-defined platform. - """ - PLATFORM_UNSPECIFIED = 0 - GKE = 1 - FLEX = 2 - CUSTOM = 3 - - user_email: str = proto.Field( - proto.STRING, - number=1, - ) - deploy_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - undeploy_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - config: str = proto.Field( - proto.STRING, - number=4, - ) - address: str = proto.Field( - proto.STRING, - number=5, - ) - resource_uri: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=6, - ) - platform: Platform = proto.Field( - proto.ENUM, - number=7, - enum=Platform, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/discovery.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/discovery.py deleted file mode 100644 index 627ab994ae06..000000000000 --- a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/discovery.py +++ /dev/null @@ -1,281 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from grafeas.grafeas_v1.types import common - - -__protobuf__ = proto.module( - package='grafeas.v1', - manifest={ - 'DiscoveryNote', - 'DiscoveryOccurrence', - }, -) - - -class DiscoveryNote(proto.Message): - r"""A note that indicates a type of analysis a provider would perform. - This note exists in a provider's project. A ``Discovery`` occurrence - is created in a consumer's project at the start of analysis. - - Attributes: - analysis_kind (grafeas.grafeas_v1.types.NoteKind): - Required. Immutable. The kind of analysis - that is handled by this discovery. - """ - - analysis_kind: common.NoteKind = proto.Field( - proto.ENUM, - number=1, - enum=common.NoteKind, - ) - - -class DiscoveryOccurrence(proto.Message): - r"""Provides information about the analysis status of a - discovered resource. - - Attributes: - continuous_analysis (grafeas.grafeas_v1.types.DiscoveryOccurrence.ContinuousAnalysis): - Whether the resource is continuously - analyzed. - analysis_status (grafeas.grafeas_v1.types.DiscoveryOccurrence.AnalysisStatus): - The status of discovery for the resource. - analysis_completed (grafeas.grafeas_v1.types.DiscoveryOccurrence.AnalysisCompleted): - - analysis_error (MutableSequence[google.rpc.status_pb2.Status]): - Indicates any errors encountered during - analysis of a resource. There could be 0 or more - of these errors. - analysis_status_error (google.rpc.status_pb2.Status): - When an error is encountered this will - contain a LocalizedMessage under details to show - to the user. The LocalizedMessage is output only - and populated by the API. - cpe (str): - The CPE of the resource being scanned. - last_scan_time (google.protobuf.timestamp_pb2.Timestamp): - The last time this resource was scanned. - archive_time (google.protobuf.timestamp_pb2.Timestamp): - The time occurrences related to this - discovery occurrence were archived. - sbom_status (grafeas.grafeas_v1.types.DiscoveryOccurrence.SBOMStatus): - The status of an SBOM generation. - vulnerability_attestation (grafeas.grafeas_v1.types.DiscoveryOccurrence.VulnerabilityAttestation): - The status of an vulnerability attestation - generation. - """ - class ContinuousAnalysis(proto.Enum): - r"""Whether the resource is continuously analyzed. - - Values: - CONTINUOUS_ANALYSIS_UNSPECIFIED (0): - Unknown. - ACTIVE (1): - The resource is continuously analyzed. - INACTIVE (2): - The resource is ignored for continuous - analysis. - """ - CONTINUOUS_ANALYSIS_UNSPECIFIED = 0 - ACTIVE = 1 - INACTIVE = 2 - - class AnalysisStatus(proto.Enum): - r"""Analysis status for a resource. Currently for initial - analysis only (not updated in continuous analysis). - - Values: - ANALYSIS_STATUS_UNSPECIFIED (0): - Unknown. - PENDING (1): - Resource is known but no action has been - taken yet. - SCANNING (2): - Resource is being analyzed. - FINISHED_SUCCESS (3): - Analysis has finished successfully. - COMPLETE (3): - Analysis has completed. - FINISHED_FAILED (4): - Analysis has finished unsuccessfully, the - analysis itself is in a bad state. - FINISHED_UNSUPPORTED (5): - The resource is known not to be supported. - """ - _pb_options = {'allow_alias': True} - ANALYSIS_STATUS_UNSPECIFIED = 0 - PENDING = 1 - SCANNING = 2 - FINISHED_SUCCESS = 3 - COMPLETE = 3 - FINISHED_FAILED = 4 - FINISHED_UNSUPPORTED = 5 - - class AnalysisCompleted(proto.Message): - r"""Indicates which analysis completed successfully. Multiple - types of analysis can be performed on a single resource. - - Attributes: - analysis_type (MutableSequence[str]): - - """ - - analysis_type: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - - class SBOMStatus(proto.Message): - r"""The status of an SBOM generation. - - Attributes: - sbom_state (grafeas.grafeas_v1.types.DiscoveryOccurrence.SBOMStatus.SBOMState): - The progress of the SBOM generation. - error (str): - If there was an error generating an SBOM, - this will indicate what that error was. - """ - class SBOMState(proto.Enum): - r"""An enum indicating the progress of the SBOM generation. - - Values: - SBOM_STATE_UNSPECIFIED (0): - Default unknown state. - PENDING (1): - SBOM scanning is pending. - COMPLETE (2): - SBOM scanning has completed. - """ - SBOM_STATE_UNSPECIFIED = 0 - PENDING = 1 - COMPLETE = 2 - - sbom_state: 'DiscoveryOccurrence.SBOMStatus.SBOMState' = proto.Field( - proto.ENUM, - number=1, - enum='DiscoveryOccurrence.SBOMStatus.SBOMState', - ) - error: str = proto.Field( - proto.STRING, - number=2, - ) - - class VulnerabilityAttestation(proto.Message): - r"""The status of an vulnerability attestation generation. - - Attributes: - last_attempt_time (google.protobuf.timestamp_pb2.Timestamp): - The last time we attempted to generate an - attestation. - state (grafeas.grafeas_v1.types.DiscoveryOccurrence.VulnerabilityAttestation.VulnerabilityAttestationState): - The success/failure state of the latest - attestation attempt. - error (str): - If failure, the error reason for why the - attestation generation failed. - """ - class VulnerabilityAttestationState(proto.Enum): - r"""An enum indicating the state of the attestation generation. - - Values: - VULNERABILITY_ATTESTATION_STATE_UNSPECIFIED (0): - Default unknown state. - SUCCESS (1): - Attestation was successfully generated and - stored. - FAILURE (2): - Attestation was unsuccessfully generated and - stored. - """ - VULNERABILITY_ATTESTATION_STATE_UNSPECIFIED = 0 - SUCCESS = 1 - FAILURE = 2 - - last_attempt_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - state: 'DiscoveryOccurrence.VulnerabilityAttestation.VulnerabilityAttestationState' = proto.Field( - proto.ENUM, - number=2, - enum='DiscoveryOccurrence.VulnerabilityAttestation.VulnerabilityAttestationState', - ) - error: str = proto.Field( - proto.STRING, - number=3, - ) - - continuous_analysis: ContinuousAnalysis = proto.Field( - proto.ENUM, - number=1, - enum=ContinuousAnalysis, - ) - analysis_status: AnalysisStatus = proto.Field( - proto.ENUM, - number=2, - enum=AnalysisStatus, - ) - analysis_completed: AnalysisCompleted = proto.Field( - proto.MESSAGE, - number=7, - message=AnalysisCompleted, - ) - analysis_error: MutableSequence[status_pb2.Status] = proto.RepeatedField( - proto.MESSAGE, - number=8, - message=status_pb2.Status, - ) - analysis_status_error: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=3, - message=status_pb2.Status, - ) - cpe: str = proto.Field( - proto.STRING, - number=4, - ) - last_scan_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - archive_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - sbom_status: SBOMStatus = proto.Field( - proto.MESSAGE, - number=9, - message=SBOMStatus, - ) - vulnerability_attestation: VulnerabilityAttestation = proto.Field( - proto.MESSAGE, - number=10, - message=VulnerabilityAttestation, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/dsse_attestation.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/dsse_attestation.py deleted file mode 100644 index afc3dc412306..000000000000 --- a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/dsse_attestation.py +++ /dev/null @@ -1,102 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 grafeas.grafeas_v1.types import common -from grafeas.grafeas_v1.types import intoto_statement - - -__protobuf__ = proto.module( - package='grafeas.v1', - manifest={ - 'DSSEAttestationNote', - 'DSSEAttestationOccurrence', - }, -) - - -class DSSEAttestationNote(proto.Message): - r""" - - Attributes: - hint (grafeas.grafeas_v1.types.DSSEAttestationNote.DSSEHint): - DSSEHint hints at the purpose of the - attestation authority. - """ - - class DSSEHint(proto.Message): - r"""This submessage provides human-readable hints about the - purpose of the authority. Because the name of a note acts as its - resource reference, it is important to disambiguate the - canonical name of the Note (which might be a UUID for security - purposes) from "readable" names more suitable for debug output. - Note that these hints should not be used to look up authorities - in security sensitive contexts, such as when looking up - attestations to verify. - - Attributes: - human_readable_name (str): - Required. The human readable name of this - attestation authority, for example - "cloudbuild-prod". - """ - - human_readable_name: str = proto.Field( - proto.STRING, - number=1, - ) - - hint: DSSEHint = proto.Field( - proto.MESSAGE, - number=1, - message=DSSEHint, - ) - - -class DSSEAttestationOccurrence(proto.Message): - r"""Deprecated. Prefer to use a regular Occurrence, and populate - the Envelope at the top level of the Occurrence. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - envelope (grafeas.grafeas_v1.types.Envelope): - If doing something security critical, make - sure to verify the signatures in this metadata. - statement (grafeas.grafeas_v1.types.InTotoStatement): - - This field is a member of `oneof`_ ``decoded_payload``. - """ - - envelope: common.Envelope = proto.Field( - proto.MESSAGE, - number=1, - message=common.Envelope, - ) - statement: intoto_statement.InTotoStatement = proto.Field( - proto.MESSAGE, - number=2, - oneof='decoded_payload', - message=intoto_statement.InTotoStatement, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/grafeas.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/grafeas.py deleted file mode 100644 index b98b55887b0c..000000000000 --- a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/grafeas.py +++ /dev/null @@ -1,921 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 timestamp_pb2 # type: ignore -from grafeas.grafeas_v1.types import attestation as g_attestation -from grafeas.grafeas_v1.types import build as g_build -from grafeas.grafeas_v1.types import common -from grafeas.grafeas_v1.types import compliance as g_compliance -from grafeas.grafeas_v1.types import deployment as g_deployment -from grafeas.grafeas_v1.types import discovery as g_discovery -from grafeas.grafeas_v1.types import dsse_attestation as g_dsse_attestation -from grafeas.grafeas_v1.types import image as g_image -from grafeas.grafeas_v1.types import package as g_package -from grafeas.grafeas_v1.types import sbom -from grafeas.grafeas_v1.types import upgrade as g_upgrade -from grafeas.grafeas_v1.types import vex -from grafeas.grafeas_v1.types import vulnerability as g_vulnerability - - -__protobuf__ = proto.module( - package='grafeas.v1', - manifest={ - 'Occurrence', - 'Note', - 'GetOccurrenceRequest', - 'ListOccurrencesRequest', - 'ListOccurrencesResponse', - 'DeleteOccurrenceRequest', - 'CreateOccurrenceRequest', - 'UpdateOccurrenceRequest', - 'GetNoteRequest', - 'GetOccurrenceNoteRequest', - 'ListNotesRequest', - 'ListNotesResponse', - 'DeleteNoteRequest', - 'CreateNoteRequest', - 'UpdateNoteRequest', - 'ListNoteOccurrencesRequest', - 'ListNoteOccurrencesResponse', - 'BatchCreateNotesRequest', - 'BatchCreateNotesResponse', - 'BatchCreateOccurrencesRequest', - 'BatchCreateOccurrencesResponse', - }, -) - - -class Occurrence(proto.Message): - r"""An instance of an analysis type that has been found on a - resource. - - 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: - name (str): - Output only. The name of the occurrence in the form of - ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. - resource_uri (str): - Required. Immutable. A URI that represents the resource for - which the occurrence applies. For example, - ``https://gcr.io/project/image@sha256:123abc`` for a Docker - image. - note_name (str): - Required. Immutable. The analysis note associated with this - occurrence, in the form of - ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. This field can - be used as a filter in list requests. - kind (grafeas.grafeas_v1.types.NoteKind): - Output only. This explicitly denotes which of - the occurrence details are specified. This field - can be used as a filter in list requests. - remediation (str): - A description of actions that can be taken to - remedy the note. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time this occurrence was - created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time this occurrence was - last updated. - vulnerability (grafeas.grafeas_v1.types.VulnerabilityOccurrence): - Describes a security vulnerability. - - This field is a member of `oneof`_ ``details``. - build (grafeas.grafeas_v1.types.BuildOccurrence): - Describes a verifiable build. - - This field is a member of `oneof`_ ``details``. - image (grafeas.grafeas_v1.types.ImageOccurrence): - Describes how this resource derives from the - basis in the associated note. - - This field is a member of `oneof`_ ``details``. - package (grafeas.grafeas_v1.types.PackageOccurrence): - Describes the installation of a package on - the linked resource. - - This field is a member of `oneof`_ ``details``. - deployment (grafeas.grafeas_v1.types.DeploymentOccurrence): - Describes the deployment of an artifact on a - runtime. - - This field is a member of `oneof`_ ``details``. - discovery (grafeas.grafeas_v1.types.DiscoveryOccurrence): - Describes when a resource was discovered. - - This field is a member of `oneof`_ ``details``. - attestation (grafeas.grafeas_v1.types.AttestationOccurrence): - Describes an attestation of an artifact. - - This field is a member of `oneof`_ ``details``. - upgrade (grafeas.grafeas_v1.types.UpgradeOccurrence): - Describes an available package upgrade on the - linked resource. - - This field is a member of `oneof`_ ``details``. - compliance (grafeas.grafeas_v1.types.ComplianceOccurrence): - Describes a compliance violation on a linked - resource. - - This field is a member of `oneof`_ ``details``. - dsse_attestation (grafeas.grafeas_v1.types.DSSEAttestationOccurrence): - Describes an attestation of an artifact using - dsse. - - This field is a member of `oneof`_ ``details``. - sbom_reference (grafeas.grafeas_v1.types.SBOMReferenceOccurrence): - Describes a specific SBOM reference - occurrences. - - This field is a member of `oneof`_ ``details``. - envelope (grafeas.grafeas_v1.types.Envelope): - https://github.com/secure-systems-lab/dsse - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - resource_uri: str = proto.Field( - proto.STRING, - number=2, - ) - note_name: str = proto.Field( - proto.STRING, - number=3, - ) - kind: common.NoteKind = proto.Field( - proto.ENUM, - number=4, - enum=common.NoteKind, - ) - remediation: str = proto.Field( - proto.STRING, - number=5, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - vulnerability: g_vulnerability.VulnerabilityOccurrence = proto.Field( - proto.MESSAGE, - number=8, - oneof='details', - message=g_vulnerability.VulnerabilityOccurrence, - ) - build: g_build.BuildOccurrence = proto.Field( - proto.MESSAGE, - number=9, - oneof='details', - message=g_build.BuildOccurrence, - ) - image: g_image.ImageOccurrence = proto.Field( - proto.MESSAGE, - number=10, - oneof='details', - message=g_image.ImageOccurrence, - ) - package: g_package.PackageOccurrence = proto.Field( - proto.MESSAGE, - number=11, - oneof='details', - message=g_package.PackageOccurrence, - ) - deployment: g_deployment.DeploymentOccurrence = proto.Field( - proto.MESSAGE, - number=12, - oneof='details', - message=g_deployment.DeploymentOccurrence, - ) - discovery: g_discovery.DiscoveryOccurrence = proto.Field( - proto.MESSAGE, - number=13, - oneof='details', - message=g_discovery.DiscoveryOccurrence, - ) - attestation: g_attestation.AttestationOccurrence = proto.Field( - proto.MESSAGE, - number=14, - oneof='details', - message=g_attestation.AttestationOccurrence, - ) - upgrade: g_upgrade.UpgradeOccurrence = proto.Field( - proto.MESSAGE, - number=15, - oneof='details', - message=g_upgrade.UpgradeOccurrence, - ) - compliance: g_compliance.ComplianceOccurrence = proto.Field( - proto.MESSAGE, - number=16, - oneof='details', - message=g_compliance.ComplianceOccurrence, - ) - dsse_attestation: g_dsse_attestation.DSSEAttestationOccurrence = proto.Field( - proto.MESSAGE, - number=17, - oneof='details', - message=g_dsse_attestation.DSSEAttestationOccurrence, - ) - sbom_reference: sbom.SBOMReferenceOccurrence = proto.Field( - proto.MESSAGE, - number=19, - oneof='details', - message=sbom.SBOMReferenceOccurrence, - ) - envelope: common.Envelope = proto.Field( - proto.MESSAGE, - number=18, - message=common.Envelope, - ) - - -class Note(proto.Message): - r"""A type of analysis that can be done for a resource. - - 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: - name (str): - Output only. The name of the note in the form of - ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. - short_description (str): - A one sentence description of this note. - long_description (str): - A detailed description of this note. - kind (grafeas.grafeas_v1.types.NoteKind): - Output only. The type of analysis. This field - can be used as a filter in list requests. - related_url (MutableSequence[grafeas.grafeas_v1.types.RelatedUrl]): - URLs associated with this note. - expiration_time (google.protobuf.timestamp_pb2.Timestamp): - Time of expiration for this note. Empty if - note does not expire. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time this note was created. - This field can be used as a filter in list - requests. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time this note was last - updated. This field can be used as a filter in - list requests. - related_note_names (MutableSequence[str]): - Other notes related to this note. - vulnerability (grafeas.grafeas_v1.types.VulnerabilityNote): - A note describing a package vulnerability. - - This field is a member of `oneof`_ ``type``. - build (grafeas.grafeas_v1.types.BuildNote): - A note describing build provenance for a - verifiable build. - - This field is a member of `oneof`_ ``type``. - image (grafeas.grafeas_v1.types.ImageNote): - A note describing a base image. - - This field is a member of `oneof`_ ``type``. - package (grafeas.grafeas_v1.types.PackageNote): - A note describing a package hosted by various - package managers. - - This field is a member of `oneof`_ ``type``. - deployment (grafeas.grafeas_v1.types.DeploymentNote): - A note describing something that can be - deployed. - - This field is a member of `oneof`_ ``type``. - discovery (grafeas.grafeas_v1.types.DiscoveryNote): - A note describing the initial analysis of a - resource. - - This field is a member of `oneof`_ ``type``. - attestation (grafeas.grafeas_v1.types.AttestationNote): - A note describing an attestation role. - - This field is a member of `oneof`_ ``type``. - upgrade (grafeas.grafeas_v1.types.UpgradeNote): - A note describing available package upgrades. - - This field is a member of `oneof`_ ``type``. - compliance (grafeas.grafeas_v1.types.ComplianceNote): - A note describing a compliance check. - - This field is a member of `oneof`_ ``type``. - dsse_attestation (grafeas.grafeas_v1.types.DSSEAttestationNote): - A note describing a dsse attestation note. - - This field is a member of `oneof`_ ``type``. - vulnerability_assessment (grafeas.grafeas_v1.types.VulnerabilityAssessmentNote): - A note describing a vulnerability assessment. - - This field is a member of `oneof`_ ``type``. - sbom_reference (grafeas.grafeas_v1.types.SBOMReferenceNote): - A note describing an SBOM reference. - - This field is a member of `oneof`_ ``type``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - short_description: str = proto.Field( - proto.STRING, - number=2, - ) - long_description: str = proto.Field( - proto.STRING, - number=3, - ) - kind: common.NoteKind = proto.Field( - proto.ENUM, - number=4, - enum=common.NoteKind, - ) - related_url: MutableSequence[common.RelatedUrl] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=common.RelatedUrl, - ) - expiration_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=8, - message=timestamp_pb2.Timestamp, - ) - related_note_names: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=9, - ) - vulnerability: g_vulnerability.VulnerabilityNote = proto.Field( - proto.MESSAGE, - number=10, - oneof='type', - message=g_vulnerability.VulnerabilityNote, - ) - build: g_build.BuildNote = proto.Field( - proto.MESSAGE, - number=11, - oneof='type', - message=g_build.BuildNote, - ) - image: g_image.ImageNote = proto.Field( - proto.MESSAGE, - number=12, - oneof='type', - message=g_image.ImageNote, - ) - package: g_package.PackageNote = proto.Field( - proto.MESSAGE, - number=13, - oneof='type', - message=g_package.PackageNote, - ) - deployment: g_deployment.DeploymentNote = proto.Field( - proto.MESSAGE, - number=14, - oneof='type', - message=g_deployment.DeploymentNote, - ) - discovery: g_discovery.DiscoveryNote = proto.Field( - proto.MESSAGE, - number=15, - oneof='type', - message=g_discovery.DiscoveryNote, - ) - attestation: g_attestation.AttestationNote = proto.Field( - proto.MESSAGE, - number=16, - oneof='type', - message=g_attestation.AttestationNote, - ) - upgrade: g_upgrade.UpgradeNote = proto.Field( - proto.MESSAGE, - number=17, - oneof='type', - message=g_upgrade.UpgradeNote, - ) - compliance: g_compliance.ComplianceNote = proto.Field( - proto.MESSAGE, - number=18, - oneof='type', - message=g_compliance.ComplianceNote, - ) - dsse_attestation: g_dsse_attestation.DSSEAttestationNote = proto.Field( - proto.MESSAGE, - number=19, - oneof='type', - message=g_dsse_attestation.DSSEAttestationNote, - ) - vulnerability_assessment: vex.VulnerabilityAssessmentNote = proto.Field( - proto.MESSAGE, - number=20, - oneof='type', - message=vex.VulnerabilityAssessmentNote, - ) - sbom_reference: sbom.SBOMReferenceNote = proto.Field( - proto.MESSAGE, - number=21, - oneof='type', - message=sbom.SBOMReferenceNote, - ) - - -class GetOccurrenceRequest(proto.Message): - r"""Request to get an occurrence. - - Attributes: - name (str): - The name of the occurrence in the form of - ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListOccurrencesRequest(proto.Message): - r"""Request to list occurrences. - - Attributes: - parent (str): - The name of the project to list occurrences for in the form - of ``projects/[PROJECT_ID]``. - filter (str): - The filter expression. - page_size (int): - Number of occurrences to return in the list. - Must be positive. Max allowed page size is 1000. - If not specified, page size defaults to 20. - page_token (str): - Token to provide to skip to a particular spot - in the list. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - page_size: int = proto.Field( - proto.INT32, - number=3, - ) - page_token: str = proto.Field( - proto.STRING, - number=4, - ) - - -class ListOccurrencesResponse(proto.Message): - r"""Response for listing occurrences. - - Attributes: - occurrences (MutableSequence[grafeas.grafeas_v1.types.Occurrence]): - The occurrences requested. - next_page_token (str): - The next pagination token in the list response. It should be - used as ``page_token`` for the following request. An empty - value means no more results. - """ - - @property - def raw_page(self): - return self - - occurrences: MutableSequence['Occurrence'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Occurrence', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class DeleteOccurrenceRequest(proto.Message): - r"""Request to delete an occurrence. - - Attributes: - name (str): - The name of the occurrence in the form of - ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateOccurrenceRequest(proto.Message): - r"""Request to create a new occurrence. - - Attributes: - parent (str): - The name of the project in the form of - ``projects/[PROJECT_ID]``, under which the occurrence is to - be created. - occurrence (grafeas.grafeas_v1.types.Occurrence): - The occurrence to create. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - occurrence: 'Occurrence' = proto.Field( - proto.MESSAGE, - number=2, - message='Occurrence', - ) - - -class UpdateOccurrenceRequest(proto.Message): - r"""Request to update an occurrence. - - Attributes: - name (str): - The name of the occurrence in the form of - ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. - occurrence (grafeas.grafeas_v1.types.Occurrence): - The updated occurrence. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The fields to update. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - occurrence: 'Occurrence' = proto.Field( - proto.MESSAGE, - number=2, - message='Occurrence', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=3, - message=field_mask_pb2.FieldMask, - ) - - -class GetNoteRequest(proto.Message): - r"""Request to get a note. - - Attributes: - name (str): - The name of the note in the form of - ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetOccurrenceNoteRequest(proto.Message): - r"""Request to get the note to which the specified occurrence is - attached. - - Attributes: - name (str): - The name of the occurrence in the form of - ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListNotesRequest(proto.Message): - r"""Request to list notes. - - Attributes: - parent (str): - The name of the project to list notes for in the form of - ``projects/[PROJECT_ID]``. - filter (str): - The filter expression. - page_size (int): - Number of notes to return in the list. Must - be positive. Max allowed page size is 1000. If - not specified, page size defaults to 20. - page_token (str): - Token to provide to skip to a particular spot - in the list. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - page_size: int = proto.Field( - proto.INT32, - number=3, - ) - page_token: str = proto.Field( - proto.STRING, - number=4, - ) - - -class ListNotesResponse(proto.Message): - r"""Response for listing notes. - - Attributes: - notes (MutableSequence[grafeas.grafeas_v1.types.Note]): - The notes requested. - next_page_token (str): - The next pagination token in the list response. It should be - used as ``page_token`` for the following request. An empty - value means no more results. - """ - - @property - def raw_page(self): - return self - - notes: MutableSequence['Note'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Note', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class DeleteNoteRequest(proto.Message): - r"""Request to delete a note. - - Attributes: - name (str): - The name of the note in the form of - ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateNoteRequest(proto.Message): - r"""Request to create a new note. - - Attributes: - parent (str): - The name of the project in the form of - ``projects/[PROJECT_ID]``, under which the note is to be - created. - note_id (str): - The ID to use for this note. - note (grafeas.grafeas_v1.types.Note): - The note to create. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - note_id: str = proto.Field( - proto.STRING, - number=2, - ) - note: 'Note' = proto.Field( - proto.MESSAGE, - number=3, - message='Note', - ) - - -class UpdateNoteRequest(proto.Message): - r"""Request to update a note. - - Attributes: - name (str): - The name of the note in the form of - ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. - note (grafeas.grafeas_v1.types.Note): - The updated note. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The fields to update. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - note: 'Note' = proto.Field( - proto.MESSAGE, - number=2, - message='Note', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=3, - message=field_mask_pb2.FieldMask, - ) - - -class ListNoteOccurrencesRequest(proto.Message): - r"""Request to list occurrences for a note. - - Attributes: - name (str): - The name of the note to list occurrences for in the form of - ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. - filter (str): - The filter expression. - page_size (int): - Number of occurrences to return in the list. - page_token (str): - Token to provide to skip to a particular spot - in the list. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - page_size: int = proto.Field( - proto.INT32, - number=3, - ) - page_token: str = proto.Field( - proto.STRING, - number=4, - ) - - -class ListNoteOccurrencesResponse(proto.Message): - r"""Response for listing occurrences for a note. - - Attributes: - occurrences (MutableSequence[grafeas.grafeas_v1.types.Occurrence]): - The occurrences attached to the specified - note. - next_page_token (str): - Token to provide to skip to a particular spot - in the list. - """ - - @property - def raw_page(self): - return self - - occurrences: MutableSequence['Occurrence'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Occurrence', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class BatchCreateNotesRequest(proto.Message): - r"""Request to create notes in batch. - - Attributes: - parent (str): - The name of the project in the form of - ``projects/[PROJECT_ID]``, under which the notes are to be - created. - notes (MutableMapping[str, grafeas.grafeas_v1.types.Note]): - The notes to create. Max allowed length is - 1000. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - notes: MutableMapping[str, 'Note'] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=2, - message='Note', - ) - - -class BatchCreateNotesResponse(proto.Message): - r"""Response for creating notes in batch. - - Attributes: - notes (MutableSequence[grafeas.grafeas_v1.types.Note]): - The notes that were created. - """ - - notes: MutableSequence['Note'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Note', - ) - - -class BatchCreateOccurrencesRequest(proto.Message): - r"""Request to create occurrences in batch. - - Attributes: - parent (str): - The name of the project in the form of - ``projects/[PROJECT_ID]``, under which the occurrences are - to be created. - occurrences (MutableSequence[grafeas.grafeas_v1.types.Occurrence]): - The occurrences to create. Max allowed length - is 1000. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - occurrences: MutableSequence['Occurrence'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Occurrence', - ) - - -class BatchCreateOccurrencesResponse(proto.Message): - r"""Response for creating occurrences in batch. - - Attributes: - occurrences (MutableSequence[grafeas.grafeas_v1.types.Occurrence]): - The occurrences that were created. - """ - - occurrences: MutableSequence['Occurrence'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Occurrence', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/image.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/image.py deleted file mode 100644 index 9fde99b85808..000000000000 --- a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/image.py +++ /dev/null @@ -1,158 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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='grafeas.v1', - manifest={ - 'Layer', - 'Fingerprint', - 'ImageNote', - 'ImageOccurrence', - }, -) - - -class Layer(proto.Message): - r"""Layer holds metadata specific to a layer of a Docker image. - - Attributes: - directive (str): - Required. The recovered Dockerfile directive - used to construct this layer. See - https://docs.docker.com/engine/reference/builder/ - for more information. - arguments (str): - The recovered arguments to the Dockerfile - directive. - """ - - directive: str = proto.Field( - proto.STRING, - number=1, - ) - arguments: str = proto.Field( - proto.STRING, - number=2, - ) - - -class Fingerprint(proto.Message): - r"""A set of properties that uniquely identify a given Docker - image. - - Attributes: - v1_name (str): - Required. The layer ID of the final layer in - the Docker image's v1 representation. - v2_blob (MutableSequence[str]): - Required. The ordered list of v2 blobs that - represent a given image. - v2_name (str): - Output only. The name of the image's v2 blobs computed via: - [bottom] := v2_blob[bottom] [N] := sha256(v2_blob[N] + " " + - v2_name[N+1]) Only the name of the final blob is kept. - """ - - v1_name: str = proto.Field( - proto.STRING, - number=1, - ) - v2_blob: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - v2_name: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ImageNote(proto.Message): - r"""Basis describes the base image portion (Note) of the DockerImage - relationship. Linked occurrences are derived from this or an - equivalent image via: FROM Or an equivalent - reference, e.g., a tag of the resource_url. - - Attributes: - resource_url (str): - Required. Immutable. The resource_url for the resource - representing the basis of associated occurrence images. - fingerprint (grafeas.grafeas_v1.types.Fingerprint): - Required. Immutable. The fingerprint of the - base image. - """ - - resource_url: str = proto.Field( - proto.STRING, - number=1, - ) - fingerprint: 'Fingerprint' = proto.Field( - proto.MESSAGE, - number=2, - message='Fingerprint', - ) - - -class ImageOccurrence(proto.Message): - r"""Details of the derived image portion of the DockerImage - relationship. This image would be produced from a Dockerfile - with FROM . - - Attributes: - fingerprint (grafeas.grafeas_v1.types.Fingerprint): - Required. The fingerprint of the derived - image. - distance (int): - Output only. The number of layers by which - this image differs from the associated image - basis. - layer_info (MutableSequence[grafeas.grafeas_v1.types.Layer]): - This contains layer-specific metadata, if populated it has - length "distance" and is ordered with [distance] being the - layer immediately following the base image and [1] being the - final layer. - base_resource_url (str): - Output only. This contains the base image URL - for the derived image occurrence. - """ - - fingerprint: 'Fingerprint' = proto.Field( - proto.MESSAGE, - number=1, - message='Fingerprint', - ) - distance: int = proto.Field( - proto.INT32, - number=2, - ) - layer_info: MutableSequence['Layer'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Layer', - ) - base_resource_url: str = proto.Field( - proto.STRING, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/intoto_provenance.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/intoto_provenance.py deleted file mode 100644 index 940bd414da8f..000000000000 --- a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/intoto_provenance.py +++ /dev/null @@ -1,248 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 any_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='grafeas.v1', - manifest={ - 'Recipe', - 'Completeness', - 'Metadata', - 'BuilderConfig', - 'InTotoProvenance', - }, -) - - -class Recipe(proto.Message): - r"""Steps taken to build the artifact. - For a TaskRun, typically each container corresponds to one step - in the recipe. - - Attributes: - type_ (str): - URI indicating what type of recipe was - performed. It determines the meaning of - recipe.entryPoint, recipe.arguments, - recipe.environment, and materials. - defined_in_material (int): - Index in materials containing the recipe - steps that are not implied by recipe.type. For - example, if the recipe type were "make", then - this would point to the source containing the - Makefile, not the make program itself. Set to -1 - if the recipe doesn't come from a material, as - zero is default unset value for int64. - entry_point (str): - String identifying the entry point into the - build. This is often a path to a configuration - file and/or a target label within that file. The - syntax and meaning are defined by recipe.type. - For example, if the recipe type were "make", - then this would reference the directory in which - to run make as well as which target to use. - arguments (MutableSequence[google.protobuf.any_pb2.Any]): - Collection of all external inputs that - influenced the build on top of - recipe.definedInMaterial and recipe.entryPoint. - For example, if the recipe type were "make", - then this might be the flags passed to make - aside from the target, which is captured in - recipe.entryPoint. Since the arguments field can - greatly vary in structure, depending on the - builder and recipe type, this is of form "Any". - environment (MutableSequence[google.protobuf.any_pb2.Any]): - Any other builder-controlled inputs necessary - for correctly evaluating the recipe. Usually - only needed for reproducing the build but not - evaluated as part of policy. Since the - environment field can greatly vary in structure, - depending on the builder and recipe type, this - is of form "Any". - """ - - type_: str = proto.Field( - proto.STRING, - number=1, - ) - defined_in_material: int = proto.Field( - proto.INT64, - number=2, - ) - entry_point: str = proto.Field( - proto.STRING, - number=3, - ) - arguments: MutableSequence[any_pb2.Any] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=any_pb2.Any, - ) - environment: MutableSequence[any_pb2.Any] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=any_pb2.Any, - ) - - -class Completeness(proto.Message): - r"""Indicates that the builder claims certain fields in this - message to be complete. - - Attributes: - arguments (bool): - If true, the builder claims that - recipe.arguments is complete, meaning that all - external inputs are properly captured in the - recipe. - environment (bool): - If true, the builder claims that - recipe.environment is claimed to be complete. - materials (bool): - If true, the builder claims that materials - are complete, usually through some controls to - prevent network access. Sometimes called - "hermetic". - """ - - arguments: bool = proto.Field( - proto.BOOL, - number=1, - ) - environment: bool = proto.Field( - proto.BOOL, - number=2, - ) - materials: bool = proto.Field( - proto.BOOL, - number=3, - ) - - -class Metadata(proto.Message): - r"""Other properties of the build. - - Attributes: - build_invocation_id (str): - Identifies the particular build invocation, - which can be useful for finding associated logs - or other ad-hoc analysis. The value SHOULD be - globally unique, per in-toto Provenance spec. - build_started_on (google.protobuf.timestamp_pb2.Timestamp): - The timestamp of when the build started. - build_finished_on (google.protobuf.timestamp_pb2.Timestamp): - The timestamp of when the build completed. - completeness (grafeas.grafeas_v1.types.Completeness): - Indicates that the builder claims certain - fields in this message to be complete. - reproducible (bool): - If true, the builder claims that running the - recipe on materials will produce bit-for-bit - identical output. - """ - - build_invocation_id: str = proto.Field( - proto.STRING, - number=1, - ) - build_started_on: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - build_finished_on: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - completeness: 'Completeness' = proto.Field( - proto.MESSAGE, - number=4, - message='Completeness', - ) - reproducible: bool = proto.Field( - proto.BOOL, - number=5, - ) - - -class BuilderConfig(proto.Message): - r""" - - Attributes: - id (str): - - """ - - id: str = proto.Field( - proto.STRING, - number=1, - ) - - -class InTotoProvenance(proto.Message): - r""" - - Attributes: - builder_config (grafeas.grafeas_v1.types.BuilderConfig): - required - recipe (grafeas.grafeas_v1.types.Recipe): - Identifies the configuration used for the - build. When combined with materials, this SHOULD - fully describe the build, such that re-running - this recipe results in bit-for-bit identical - output (if the build is reproducible). - metadata (grafeas.grafeas_v1.types.Metadata): - - materials (MutableSequence[str]): - The collection of artifacts that influenced - the build including sources, dependencies, build - tools, base images, and so on. This is - considered to be incomplete unless - metadata.completeness.materials is true. Unset - or null is equivalent to empty. - """ - - builder_config: 'BuilderConfig' = proto.Field( - proto.MESSAGE, - number=1, - message='BuilderConfig', - ) - recipe: 'Recipe' = proto.Field( - proto.MESSAGE, - number=2, - message='Recipe', - ) - metadata: 'Metadata' = proto.Field( - proto.MESSAGE, - number=3, - message='Metadata', - ) - materials: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/intoto_statement.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/intoto_statement.py deleted file mode 100644 index d42bddb2cdf9..000000000000 --- a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/intoto_statement.py +++ /dev/null @@ -1,353 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from grafeas.grafeas_v1.types import intoto_provenance -from grafeas.grafeas_v1.types import slsa_provenance as g_slsa_provenance -from grafeas.grafeas_v1.types import slsa_provenance_zero_two as g_slsa_provenance_zero_two - - -__protobuf__ = proto.module( - package='grafeas.v1', - manifest={ - 'InTotoStatement', - 'Subject', - 'InTotoSlsaProvenanceV1', - }, -) - - -class InTotoStatement(proto.Message): - r"""Spec defined at - https://github.com/in-toto/attestation/tree/main/spec#statement - The serialized InTotoStatement will be stored as - Envelope.payload. Envelope.payloadType is always - "application/vnd.in-toto+json". - - 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: - type_ (str): - Always ``https://in-toto.io/Statement/v0.1``. - subject (MutableSequence[grafeas.grafeas_v1.types.Subject]): - - predicate_type (str): - ``https://slsa.dev/provenance/v0.1`` for SlsaProvenance. - provenance (grafeas.grafeas_v1.types.InTotoProvenance): - - This field is a member of `oneof`_ ``predicate``. - slsa_provenance (grafeas.grafeas_v1.types.SlsaProvenance): - - This field is a member of `oneof`_ ``predicate``. - slsa_provenance_zero_two (grafeas.grafeas_v1.types.SlsaProvenanceZeroTwo): - - This field is a member of `oneof`_ ``predicate``. - """ - - type_: str = proto.Field( - proto.STRING, - number=1, - ) - subject: MutableSequence['Subject'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Subject', - ) - predicate_type: str = proto.Field( - proto.STRING, - number=3, - ) - provenance: intoto_provenance.InTotoProvenance = proto.Field( - proto.MESSAGE, - number=4, - oneof='predicate', - message=intoto_provenance.InTotoProvenance, - ) - slsa_provenance: g_slsa_provenance.SlsaProvenance = proto.Field( - proto.MESSAGE, - number=5, - oneof='predicate', - message=g_slsa_provenance.SlsaProvenance, - ) - slsa_provenance_zero_two: g_slsa_provenance_zero_two.SlsaProvenanceZeroTwo = proto.Field( - proto.MESSAGE, - number=6, - oneof='predicate', - message=g_slsa_provenance_zero_two.SlsaProvenanceZeroTwo, - ) - - -class Subject(proto.Message): - r""" - - Attributes: - name (str): - - digest (MutableMapping[str, str]): - ``"": ""`` Algorithms can be e.g. - sha256, sha512 See - https://github.com/in-toto/attestation/blob/main/spec/field_types.md#DigestSet - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - digest: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=2, - ) - - -class InTotoSlsaProvenanceV1(proto.Message): - r""" - - Attributes: - type_ (str): - InToto spec defined at - https://github.com/in-toto/attestation/tree/main/spec#statement - subject (MutableSequence[grafeas.grafeas_v1.types.Subject]): - - predicate_type (str): - - predicate (grafeas.grafeas_v1.types.InTotoSlsaProvenanceV1.SlsaProvenanceV1): - - """ - - class SlsaProvenanceV1(proto.Message): - r"""Keep in sync with schema at - https://github.com/slsa-framework/slsa/blob/main/docs/provenance/schema/v1/provenance.proto - Builder renamed to ProvenanceBuilder because of Java conflicts. - - Attributes: - build_definition (grafeas.grafeas_v1.types.InTotoSlsaProvenanceV1.BuildDefinition): - - run_details (grafeas.grafeas_v1.types.InTotoSlsaProvenanceV1.RunDetails): - - """ - - build_definition: 'InTotoSlsaProvenanceV1.BuildDefinition' = proto.Field( - proto.MESSAGE, - number=1, - message='InTotoSlsaProvenanceV1.BuildDefinition', - ) - run_details: 'InTotoSlsaProvenanceV1.RunDetails' = proto.Field( - proto.MESSAGE, - number=2, - message='InTotoSlsaProvenanceV1.RunDetails', - ) - - class BuildDefinition(proto.Message): - r""" - - Attributes: - build_type (str): - - external_parameters (google.protobuf.struct_pb2.Struct): - - internal_parameters (google.protobuf.struct_pb2.Struct): - - resolved_dependencies (MutableSequence[grafeas.grafeas_v1.types.InTotoSlsaProvenanceV1.ResourceDescriptor]): - - """ - - build_type: str = proto.Field( - proto.STRING, - number=1, - ) - external_parameters: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=2, - message=struct_pb2.Struct, - ) - internal_parameters: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=3, - message=struct_pb2.Struct, - ) - resolved_dependencies: MutableSequence['InTotoSlsaProvenanceV1.ResourceDescriptor'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='InTotoSlsaProvenanceV1.ResourceDescriptor', - ) - - class ResourceDescriptor(proto.Message): - r""" - - Attributes: - name (str): - - uri (str): - - digest (MutableMapping[str, str]): - - content (bytes): - - download_location (str): - - media_type (str): - - annotations (MutableMapping[str, google.protobuf.struct_pb2.Value]): - - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - ) - digest: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=3, - ) - content: bytes = proto.Field( - proto.BYTES, - number=4, - ) - download_location: str = proto.Field( - proto.STRING, - number=5, - ) - media_type: str = proto.Field( - proto.STRING, - number=6, - ) - annotations: MutableMapping[str, struct_pb2.Value] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=7, - message=struct_pb2.Value, - ) - - class RunDetails(proto.Message): - r""" - - Attributes: - builder (grafeas.grafeas_v1.types.InTotoSlsaProvenanceV1.ProvenanceBuilder): - - metadata (grafeas.grafeas_v1.types.InTotoSlsaProvenanceV1.BuildMetadata): - - byproducts (MutableSequence[grafeas.grafeas_v1.types.InTotoSlsaProvenanceV1.ResourceDescriptor]): - - """ - - builder: 'InTotoSlsaProvenanceV1.ProvenanceBuilder' = proto.Field( - proto.MESSAGE, - number=1, - message='InTotoSlsaProvenanceV1.ProvenanceBuilder', - ) - metadata: 'InTotoSlsaProvenanceV1.BuildMetadata' = proto.Field( - proto.MESSAGE, - number=2, - message='InTotoSlsaProvenanceV1.BuildMetadata', - ) - byproducts: MutableSequence['InTotoSlsaProvenanceV1.ResourceDescriptor'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='InTotoSlsaProvenanceV1.ResourceDescriptor', - ) - - class ProvenanceBuilder(proto.Message): - r""" - - Attributes: - id (str): - - version (MutableMapping[str, str]): - - builder_dependencies (MutableSequence[grafeas.grafeas_v1.types.InTotoSlsaProvenanceV1.ResourceDescriptor]): - - """ - - id: str = proto.Field( - proto.STRING, - number=1, - ) - version: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=2, - ) - builder_dependencies: MutableSequence['InTotoSlsaProvenanceV1.ResourceDescriptor'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='InTotoSlsaProvenanceV1.ResourceDescriptor', - ) - - class BuildMetadata(proto.Message): - r""" - - Attributes: - invocation_id (str): - - started_on (google.protobuf.timestamp_pb2.Timestamp): - - finished_on (google.protobuf.timestamp_pb2.Timestamp): - - """ - - invocation_id: str = proto.Field( - proto.STRING, - number=1, - ) - started_on: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - finished_on: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - type_: str = proto.Field( - proto.STRING, - number=1, - ) - subject: MutableSequence['Subject'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Subject', - ) - predicate_type: str = proto.Field( - proto.STRING, - number=3, - ) - predicate: SlsaProvenanceV1 = proto.Field( - proto.MESSAGE, - number=4, - message=SlsaProvenanceV1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/package.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/package.py deleted file mode 100644 index d2402a958a94..000000000000 --- a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/package.py +++ /dev/null @@ -1,378 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 grafeas.grafeas_v1.types import common - - -__protobuf__ = proto.module( - package='grafeas.v1', - manifest={ - 'Architecture', - 'Distribution', - 'Location', - 'PackageNote', - 'PackageOccurrence', - 'Version', - }, -) - - -class Architecture(proto.Enum): - r"""Instruction set architectures supported by various package - managers. - - Values: - ARCHITECTURE_UNSPECIFIED (0): - Unknown architecture. - X86 (1): - X86 architecture. - X64 (2): - X64 architecture. - """ - ARCHITECTURE_UNSPECIFIED = 0 - X86 = 1 - X64 = 2 - - -class Distribution(proto.Message): - r"""This represents a particular channel of distribution for a - given package. E.g., Debian's jessie-backports dpkg mirror. - - Attributes: - cpe_uri (str): - The cpe_uri in `CPE - format `__ denoting - the package manager version distributing a package. - architecture (grafeas.grafeas_v1.types.Architecture): - The CPU architecture for which packages in - this distribution channel were built. - latest_version (grafeas.grafeas_v1.types.Version): - The latest available version of this package - in this distribution channel. - maintainer (str): - A freeform string denoting the maintainer of - this package. - url (str): - The distribution channel-specific homepage - for this package. - description (str): - The distribution channel-specific description - of this package. - """ - - cpe_uri: str = proto.Field( - proto.STRING, - number=1, - ) - architecture: 'Architecture' = proto.Field( - proto.ENUM, - number=2, - enum='Architecture', - ) - latest_version: 'Version' = proto.Field( - proto.MESSAGE, - number=3, - message='Version', - ) - maintainer: str = proto.Field( - proto.STRING, - number=4, - ) - url: str = proto.Field( - proto.STRING, - number=5, - ) - description: str = proto.Field( - proto.STRING, - number=6, - ) - - -class Location(proto.Message): - r"""An occurrence of a particular package installation found within a - system's filesystem. E.g., glibc was found in - ``/var/lib/dpkg/status``. - - Attributes: - cpe_uri (str): - Deprecated. The CPE URI in `CPE - format `__ - version (grafeas.grafeas_v1.types.Version): - Deprecated. - The version installed at this location. - path (str): - The path from which we gathered that this - package/version is installed. - """ - - cpe_uri: str = proto.Field( - proto.STRING, - number=1, - ) - version: 'Version' = proto.Field( - proto.MESSAGE, - number=2, - message='Version', - ) - path: str = proto.Field( - proto.STRING, - number=3, - ) - - -class PackageNote(proto.Message): - r"""PackageNote represents a particular package version. - - Attributes: - name (str): - The name of the package. - distribution (MutableSequence[grafeas.grafeas_v1.types.Distribution]): - Deprecated. - The various channels by which a package is - distributed. - package_type (str): - The type of package; whether native or non - native (e.g., ruby gems, node.js packages, - etc.). - cpe_uri (str): - The cpe_uri in `CPE - format `__ denoting - the package manager version distributing a package. The - cpe_uri will be blank for language packages. - architecture (grafeas.grafeas_v1.types.Architecture): - The CPU architecture for which packages in - this distribution channel were built. - Architecture will be blank for language - packages. - version (grafeas.grafeas_v1.types.Version): - The version of the package. - maintainer (str): - A freeform text denoting the maintainer of - this package. - url (str): - The homepage for this package. - description (str): - The description of this package. - license_ (grafeas.grafeas_v1.types.License): - Licenses that have been declared by the - authors of the package. - digest (MutableSequence[grafeas.grafeas_v1.types.Digest]): - Hash value, typically a file digest, that - allows unique identification a specific package. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - distribution: MutableSequence['Distribution'] = proto.RepeatedField( - proto.MESSAGE, - number=10, - message='Distribution', - ) - package_type: str = proto.Field( - proto.STRING, - number=11, - ) - cpe_uri: str = proto.Field( - proto.STRING, - number=12, - ) - architecture: 'Architecture' = proto.Field( - proto.ENUM, - number=13, - enum='Architecture', - ) - version: 'Version' = proto.Field( - proto.MESSAGE, - number=14, - message='Version', - ) - maintainer: str = proto.Field( - proto.STRING, - number=15, - ) - url: str = proto.Field( - proto.STRING, - number=16, - ) - description: str = proto.Field( - proto.STRING, - number=17, - ) - license_: common.License = proto.Field( - proto.MESSAGE, - number=18, - message=common.License, - ) - digest: MutableSequence[common.Digest] = proto.RepeatedField( - proto.MESSAGE, - number=19, - message=common.Digest, - ) - - -class PackageOccurrence(proto.Message): - r"""Details on how a particular software package was installed on - a system. - - Attributes: - name (str): - The name of the installed package. - location (MutableSequence[grafeas.grafeas_v1.types.Location]): - All of the places within the filesystem - versions of this package have been found. - package_type (str): - The type of package; whether native or non - native (e.g., ruby gems, node.js packages, - etc.). - cpe_uri (str): - The cpe_uri in `CPE - format `__ denoting - the package manager version distributing a package. The - cpe_uri will be blank for language packages. - architecture (grafeas.grafeas_v1.types.Architecture): - The CPU architecture for which packages in - this distribution channel were built. - Architecture will be blank for language - packages. - license_ (grafeas.grafeas_v1.types.License): - Licenses that have been declared by the - authors of the package. - version (grafeas.grafeas_v1.types.Version): - The version of the package. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - location: MutableSequence['Location'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Location', - ) - package_type: str = proto.Field( - proto.STRING, - number=3, - ) - cpe_uri: str = proto.Field( - proto.STRING, - number=4, - ) - architecture: 'Architecture' = proto.Field( - proto.ENUM, - number=5, - enum='Architecture', - ) - license_: common.License = proto.Field( - proto.MESSAGE, - number=6, - message=common.License, - ) - version: 'Version' = proto.Field( - proto.MESSAGE, - number=7, - message='Version', - ) - - -class Version(proto.Message): - r"""Version contains structured information about the version of - a package. - - Attributes: - epoch (int): - Used to correct mistakes in the version - numbering scheme. - name (str): - Required only when version kind is NORMAL. - The main part of the version name. - revision (str): - The iteration of the package build from the - above version. - inclusive (bool): - Whether this version is specifying part of an - inclusive range. Grafeas does not have the - capability to specify version ranges; instead we - have fields that specify start version and end - versions. At times this is insufficient - we - also need to specify whether the version is - included in the range or is excluded from the - range. This boolean is expected to be set to - true when the version is included in a range. - kind (grafeas.grafeas_v1.types.Version.VersionKind): - Required. Distinguishes between sentinel - MIN/MAX versions and normal versions. - full_name (str): - Human readable version string. This string is - of the form :- and is - only set when kind is NORMAL. - """ - class VersionKind(proto.Enum): - r"""Whether this is an ordinary package version or a sentinel - MIN/MAX version. - - Values: - VERSION_KIND_UNSPECIFIED (0): - Unknown. - NORMAL (1): - A standard package version. - MINIMUM (2): - A special version representing negative - infinity. - MAXIMUM (3): - A special version representing positive - infinity. - """ - VERSION_KIND_UNSPECIFIED = 0 - NORMAL = 1 - MINIMUM = 2 - MAXIMUM = 3 - - epoch: int = proto.Field( - proto.INT32, - number=1, - ) - name: str = proto.Field( - proto.STRING, - number=2, - ) - revision: str = proto.Field( - proto.STRING, - number=3, - ) - inclusive: bool = proto.Field( - proto.BOOL, - number=6, - ) - kind: VersionKind = proto.Field( - proto.ENUM, - number=4, - enum=VersionKind, - ) - full_name: str = proto.Field( - proto.STRING, - number=5, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/provenance.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/provenance.py deleted file mode 100644 index b09cbad6cbdd..000000000000 --- a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/provenance.py +++ /dev/null @@ -1,597 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='grafeas.v1', - manifest={ - 'BuildProvenance', - 'Source', - 'FileHashes', - 'Hash', - 'Command', - 'Artifact', - 'SourceContext', - 'AliasContext', - 'CloudRepoSourceContext', - 'GerritSourceContext', - 'GitSourceContext', - 'RepoId', - 'ProjectRepoId', - }, -) - - -class BuildProvenance(proto.Message): - r"""Provenance of a build. Contains all information needed to - verify the full details about the build from source to - completion. - - Attributes: - id (str): - Required. Unique identifier of the build. - project_id (str): - ID of the project. - commands (MutableSequence[grafeas.grafeas_v1.types.Command]): - Commands requested by the build. - built_artifacts (MutableSequence[grafeas.grafeas_v1.types.Artifact]): - Output of the build. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Time at which the build was created. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Time at which execution of the build was - started. - end_time (google.protobuf.timestamp_pb2.Timestamp): - Time at which execution of the build was - finished. - creator (str): - E-mail address of the user who initiated this - build. Note that this was the user's e-mail - address at the time the build was initiated; - this address may not represent the same end-user - for all time. - logs_uri (str): - URI where any logs for this provenance were - written. - source_provenance (grafeas.grafeas_v1.types.Source): - Details of the Source input to the build. - trigger_id (str): - Trigger identifier if the build was triggered - automatically; empty if not. - build_options (MutableMapping[str, str]): - Special options applied to this build. This - is a catch-all field where build providers can - enter any desired additional details. - builder_version (str): - Version string of the builder at the time - this build was executed. - """ - - id: str = proto.Field( - proto.STRING, - number=1, - ) - project_id: str = proto.Field( - proto.STRING, - number=2, - ) - commands: MutableSequence['Command'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Command', - ) - built_artifacts: MutableSequence['Artifact'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Artifact', - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - end_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - creator: str = proto.Field( - proto.STRING, - number=8, - ) - logs_uri: str = proto.Field( - proto.STRING, - number=9, - ) - source_provenance: 'Source' = proto.Field( - proto.MESSAGE, - number=10, - message='Source', - ) - trigger_id: str = proto.Field( - proto.STRING, - number=11, - ) - build_options: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=12, - ) - builder_version: str = proto.Field( - proto.STRING, - number=13, - ) - - -class Source(proto.Message): - r"""Source describes the location of the source used for the - build. - - Attributes: - artifact_storage_source_uri (str): - If provided, the input binary artifacts for - the build came from this location. - file_hashes (MutableMapping[str, grafeas.grafeas_v1.types.FileHashes]): - Hash(es) of the build source, which can be - used to verify that the original source - integrity was maintained in the build. - - The keys to this map are file paths used as - build source and the values contain the hash - values for those files. - - If the build source came in a single package - such as a gzipped tarfile (.tar.gz), the - FileHash will be for the single path to that - file. - context (grafeas.grafeas_v1.types.SourceContext): - If provided, the source code used for the - build came from this location. - additional_contexts (MutableSequence[grafeas.grafeas_v1.types.SourceContext]): - If provided, some of the source code used for - the build may be found in these locations, in - the case where the source repository had - multiple remotes or submodules. This list will - not include the context specified in the context - field. - """ - - artifact_storage_source_uri: str = proto.Field( - proto.STRING, - number=1, - ) - file_hashes: MutableMapping[str, 'FileHashes'] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=2, - message='FileHashes', - ) - context: 'SourceContext' = proto.Field( - proto.MESSAGE, - number=3, - message='SourceContext', - ) - additional_contexts: MutableSequence['SourceContext'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='SourceContext', - ) - - -class FileHashes(proto.Message): - r"""Container message for hashes of byte content of files, used - in source messages to verify integrity of source input to the - build. - - Attributes: - file_hash (MutableSequence[grafeas.grafeas_v1.types.Hash]): - Required. Collection of file hashes. - """ - - file_hash: MutableSequence['Hash'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Hash', - ) - - -class Hash(proto.Message): - r"""Container message for hash values. - - Attributes: - type_ (str): - Required. The type of hash that was - performed, e.g. "SHA-256". - value (bytes): - Required. The hash value. - """ - - type_: str = proto.Field( - proto.STRING, - number=1, - ) - value: bytes = proto.Field( - proto.BYTES, - number=2, - ) - - -class Command(proto.Message): - r"""Command describes a step performed as part of the build - pipeline. - - Attributes: - name (str): - Required. Name of the command, as presented on the command - line, or if the command is packaged as a Docker container, - as presented to ``docker pull``. - env (MutableSequence[str]): - Environment variables set before running this - command. - args (MutableSequence[str]): - Command-line arguments used when executing - this command. - dir_ (str): - Working directory (relative to project source - root) used when running this command. - id (str): - Optional unique identifier for this command, used in - wait_for to reference this command as a dependency. - wait_for (MutableSequence[str]): - The ID(s) of the command(s) that this command - depends on. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - env: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - args: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - dir_: str = proto.Field( - proto.STRING, - number=4, - ) - id: str = proto.Field( - proto.STRING, - number=5, - ) - wait_for: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=6, - ) - - -class Artifact(proto.Message): - r"""Artifact describes a build product. - - Attributes: - checksum (str): - Hash or checksum value of a binary, or Docker - Registry 2.0 digest of a container. - id (str): - Artifact ID, if any; for container images, this will be a - URL by digest like - ``gcr.io/projectID/imagename@sha256:123456``. - names (MutableSequence[str]): - Related artifact names. This may be the path to a binary or - jar file, or in the case of a container build, the name used - to push the container image to Google Container Registry, as - presented to ``docker push``. Note that a single Artifact ID - can have multiple names, for example if two tags are applied - to one image. - """ - - checksum: str = proto.Field( - proto.STRING, - number=1, - ) - id: str = proto.Field( - proto.STRING, - number=2, - ) - names: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class SourceContext(proto.Message): - r"""A SourceContext is a reference to a tree of files. A - SourceContext together with a path point to a unique revision of - a single file or directory. - - 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: - cloud_repo (grafeas.grafeas_v1.types.CloudRepoSourceContext): - A SourceContext referring to a revision in a - Google Cloud Source Repo. - - This field is a member of `oneof`_ ``context``. - gerrit (grafeas.grafeas_v1.types.GerritSourceContext): - A SourceContext referring to a Gerrit - project. - - This field is a member of `oneof`_ ``context``. - git (grafeas.grafeas_v1.types.GitSourceContext): - A SourceContext referring to any third party - Git repo (e.g., GitHub). - - This field is a member of `oneof`_ ``context``. - labels (MutableMapping[str, str]): - Labels with user defined metadata. - """ - - cloud_repo: 'CloudRepoSourceContext' = proto.Field( - proto.MESSAGE, - number=1, - oneof='context', - message='CloudRepoSourceContext', - ) - gerrit: 'GerritSourceContext' = proto.Field( - proto.MESSAGE, - number=2, - oneof='context', - message='GerritSourceContext', - ) - git: 'GitSourceContext' = proto.Field( - proto.MESSAGE, - number=3, - oneof='context', - message='GitSourceContext', - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=4, - ) - - -class AliasContext(proto.Message): - r"""An alias to a repo revision. - - Attributes: - kind (grafeas.grafeas_v1.types.AliasContext.Kind): - The alias kind. - name (str): - The alias name. - """ - class Kind(proto.Enum): - r"""The type of an alias. - - Values: - KIND_UNSPECIFIED (0): - Unknown. - FIXED (1): - Git tag. - MOVABLE (2): - Git branch. - OTHER (4): - Used to specify non-standard aliases. For - example, if a Git repo has a ref named - "refs/foo/bar". - """ - KIND_UNSPECIFIED = 0 - FIXED = 1 - MOVABLE = 2 - OTHER = 4 - - kind: Kind = proto.Field( - proto.ENUM, - number=1, - enum=Kind, - ) - name: str = proto.Field( - proto.STRING, - number=2, - ) - - -class CloudRepoSourceContext(proto.Message): - r"""A CloudRepoSourceContext denotes a particular revision in a - Google Cloud Source Repo. - - 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: - repo_id (grafeas.grafeas_v1.types.RepoId): - The ID of the repo. - revision_id (str): - A revision ID. - - This field is a member of `oneof`_ ``revision``. - alias_context (grafeas.grafeas_v1.types.AliasContext): - An alias, which may be a branch or tag. - - This field is a member of `oneof`_ ``revision``. - """ - - repo_id: 'RepoId' = proto.Field( - proto.MESSAGE, - number=1, - message='RepoId', - ) - revision_id: str = proto.Field( - proto.STRING, - number=2, - oneof='revision', - ) - alias_context: 'AliasContext' = proto.Field( - proto.MESSAGE, - number=3, - oneof='revision', - message='AliasContext', - ) - - -class GerritSourceContext(proto.Message): - r"""A SourceContext referring to a Gerrit project. - - 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: - host_uri (str): - The URI of a running Gerrit instance. - gerrit_project (str): - The full project name within the host. - Projects may be nested, so "project/subproject" - is a valid project name. The "repo name" is the - hostURI/project. - revision_id (str): - A revision (commit) ID. - - This field is a member of `oneof`_ ``revision``. - alias_context (grafeas.grafeas_v1.types.AliasContext): - An alias, which may be a branch or tag. - - This field is a member of `oneof`_ ``revision``. - """ - - host_uri: str = proto.Field( - proto.STRING, - number=1, - ) - gerrit_project: str = proto.Field( - proto.STRING, - number=2, - ) - revision_id: str = proto.Field( - proto.STRING, - number=3, - oneof='revision', - ) - alias_context: 'AliasContext' = proto.Field( - proto.MESSAGE, - number=4, - oneof='revision', - message='AliasContext', - ) - - -class GitSourceContext(proto.Message): - r"""A GitSourceContext denotes a particular revision in a third - party Git repository (e.g., GitHub). - - Attributes: - url (str): - Git repository URL. - revision_id (str): - Git commit hash. - """ - - url: str = proto.Field( - proto.STRING, - number=1, - ) - revision_id: str = proto.Field( - proto.STRING, - number=2, - ) - - -class RepoId(proto.Message): - r"""A unique identifier for a Cloud Repo. - - 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: - project_repo_id (grafeas.grafeas_v1.types.ProjectRepoId): - A combination of a project ID and a repo - name. - - This field is a member of `oneof`_ ``id``. - uid (str): - A server-assigned, globally unique - identifier. - - This field is a member of `oneof`_ ``id``. - """ - - project_repo_id: 'ProjectRepoId' = proto.Field( - proto.MESSAGE, - number=1, - oneof='id', - message='ProjectRepoId', - ) - uid: str = proto.Field( - proto.STRING, - number=2, - oneof='id', - ) - - -class ProjectRepoId(proto.Message): - r"""Selects a repo using a Google Cloud Platform project ID - (e.g., winged-cargo-31) and a repo name within that project. - - Attributes: - project_id (str): - The ID of the project. - repo_name (str): - The name of the repo. Leave empty for the - default repo. - """ - - project_id: str = proto.Field( - proto.STRING, - number=1, - ) - repo_name: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/sbom.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/sbom.py deleted file mode 100644 index e4e85214f8c7..000000000000 --- a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/sbom.py +++ /dev/null @@ -1,171 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 grafeas.grafeas_v1.types import common -from grafeas.grafeas_v1.types import intoto_statement - - -__protobuf__ = proto.module( - package='grafeas.v1', - manifest={ - 'SBOMReferenceNote', - 'SBOMReferenceOccurrence', - 'SbomReferenceIntotoPayload', - 'SbomReferenceIntotoPredicate', - }, -) - - -class SBOMReferenceNote(proto.Message): - r"""The note representing an SBOM reference. - - Attributes: - format_ (str): - The format that SBOM takes. E.g. may be spdx, - cyclonedx, etc... - version (str): - The version of the format that the SBOM - takes. E.g. if the format is spdx, the version - may be 2.3. - """ - - format_: str = proto.Field( - proto.STRING, - number=1, - ) - version: str = proto.Field( - proto.STRING, - number=2, - ) - - -class SBOMReferenceOccurrence(proto.Message): - r"""The occurrence representing an SBOM reference as applied to a - specific resource. The occurrence follows the DSSE - specification. See - https://github.com/secure-systems-lab/dsse/blob/master/envelope.md - for more details. - - Attributes: - payload (grafeas.grafeas_v1.types.SbomReferenceIntotoPayload): - The actual payload that contains the SBOM - reference data. - payload_type (str): - The kind of payload that - SbomReferenceIntotoPayload takes. Since it's in - the intoto format, this value is expected to be - 'application/vnd.in-toto+json'. - signatures (MutableSequence[grafeas.grafeas_v1.types.EnvelopeSignature]): - The signatures over the payload. - """ - - payload: 'SbomReferenceIntotoPayload' = proto.Field( - proto.MESSAGE, - number=1, - message='SbomReferenceIntotoPayload', - ) - payload_type: str = proto.Field( - proto.STRING, - number=2, - ) - signatures: MutableSequence[common.EnvelopeSignature] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=common.EnvelopeSignature, - ) - - -class SbomReferenceIntotoPayload(proto.Message): - r"""The actual payload that contains the SBOM Reference data. - The payload follows the intoto statement specification. See - https://github.com/in-toto/attestation/blob/main/spec/v1.0/statement.md - for more details. - - Attributes: - type_ (str): - Identifier for the schema of the Statement. - predicate_type (str): - URI identifying the type of the Predicate. - subject (MutableSequence[grafeas.grafeas_v1.types.Subject]): - Set of software artifacts that the - attestation applies to. Each element represents - a single software artifact. - predicate (grafeas.grafeas_v1.types.SbomReferenceIntotoPredicate): - Additional parameters of the Predicate. - Includes the actual data about the SBOM. - """ - - type_: str = proto.Field( - proto.STRING, - number=1, - ) - predicate_type: str = proto.Field( - proto.STRING, - number=2, - ) - subject: MutableSequence[intoto_statement.Subject] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=intoto_statement.Subject, - ) - predicate: 'SbomReferenceIntotoPredicate' = proto.Field( - proto.MESSAGE, - number=4, - message='SbomReferenceIntotoPredicate', - ) - - -class SbomReferenceIntotoPredicate(proto.Message): - r"""A predicate which describes the SBOM being referenced. - - Attributes: - referrer_id (str): - The person or system referring this predicate - to the consumer. - location (str): - The location of the SBOM. - mime_type (str): - The mime type of the SBOM. - digest (MutableMapping[str, str]): - A map of algorithm to digest of the contents - of the SBOM. - """ - - referrer_id: str = proto.Field( - proto.STRING, - number=1, - ) - location: str = proto.Field( - proto.STRING, - number=2, - ) - mime_type: str = proto.Field( - proto.STRING, - number=3, - ) - digest: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/severity.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/severity.py deleted file mode 100644 index cee526950a5c..000000000000 --- a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/severity.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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='grafeas.v1', - manifest={ - 'Severity', - }, -) - - -class Severity(proto.Enum): - r"""Note provider assigned severity/impact ranking. - - Values: - SEVERITY_UNSPECIFIED (0): - Unknown. - MINIMAL (1): - Minimal severity. - LOW (2): - Low severity. - MEDIUM (3): - Medium severity. - HIGH (4): - High severity. - CRITICAL (5): - Critical severity. - """ - SEVERITY_UNSPECIFIED = 0 - MINIMAL = 1 - LOW = 2 - MEDIUM = 3 - HIGH = 4 - CRITICAL = 5 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/slsa_provenance.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/slsa_provenance.py deleted file mode 100644 index 9284bfed9ae0..000000000000 --- a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/slsa_provenance.py +++ /dev/null @@ -1,258 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 any_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='grafeas.v1', - manifest={ - 'SlsaProvenance', - }, -) - - -class SlsaProvenance(proto.Message): - r""" - - Attributes: - builder (grafeas.grafeas_v1.types.SlsaProvenance.SlsaBuilder): - required - recipe (grafeas.grafeas_v1.types.SlsaProvenance.SlsaRecipe): - Identifies the configuration used for the - build. When combined with materials, this SHOULD - fully describe the build, such that re-running - this recipe results in bit-for-bit identical - output (if the build is reproducible). - metadata (grafeas.grafeas_v1.types.SlsaProvenance.SlsaMetadata): - - materials (MutableSequence[grafeas.grafeas_v1.types.SlsaProvenance.Material]): - The collection of artifacts that influenced - the build including sources, dependencies, build - tools, base images, and so on. This is - considered to be incomplete unless - metadata.completeness.materials is true. Unset - or null is equivalent to empty. - """ - - class SlsaRecipe(proto.Message): - r"""Steps taken to build the artifact. - For a TaskRun, typically each container corresponds to one step - in the recipe. - - Attributes: - type_ (str): - URI indicating what type of recipe was - performed. It determines the meaning of - recipe.entryPoint, recipe.arguments, - recipe.environment, and materials. - defined_in_material (int): - Index in materials containing the recipe - steps that are not implied by recipe.type. For - example, if the recipe type were "make", then - this would point to the source containing the - Makefile, not the make program itself. Set to -1 - if the recipe doesn't come from a material, as - zero is default unset value for int64. - entry_point (str): - String identifying the entry point into the - build. This is often a path to a configuration - file and/or a target label within that file. The - syntax and meaning are defined by recipe.type. - For example, if the recipe type were "make", - then this would reference the directory in which - to run make as well as which target to use. - arguments (google.protobuf.any_pb2.Any): - Collection of all external inputs that - influenced the build on top of - recipe.definedInMaterial and recipe.entryPoint. - For example, if the recipe type were "make", - then this might be the flags passed to make - aside from the target, which is captured in - recipe.entryPoint. Depending on the recipe Type, - the structure may be different. - environment (google.protobuf.any_pb2.Any): - Any other builder-controlled inputs necessary - for correctly evaluating the recipe. Usually - only needed for reproducing the build but not - evaluated as part of policy. Depending on the - recipe Type, the structure may be different. - """ - - type_: str = proto.Field( - proto.STRING, - number=1, - ) - defined_in_material: int = proto.Field( - proto.INT64, - number=2, - ) - entry_point: str = proto.Field( - proto.STRING, - number=3, - ) - arguments: any_pb2.Any = proto.Field( - proto.MESSAGE, - number=4, - message=any_pb2.Any, - ) - environment: any_pb2.Any = proto.Field( - proto.MESSAGE, - number=5, - message=any_pb2.Any, - ) - - class SlsaCompleteness(proto.Message): - r"""Indicates that the builder claims certain fields in this - message to be complete. - - Attributes: - arguments (bool): - If true, the builder claims that - recipe.arguments is complete, meaning that all - external inputs are properly captured in the - recipe. - environment (bool): - If true, the builder claims that - recipe.environment is claimed to be complete. - materials (bool): - If true, the builder claims that materials - are complete, usually through some controls to - prevent network access. Sometimes called - "hermetic". - """ - - arguments: bool = proto.Field( - proto.BOOL, - number=1, - ) - environment: bool = proto.Field( - proto.BOOL, - number=2, - ) - materials: bool = proto.Field( - proto.BOOL, - number=3, - ) - - class SlsaMetadata(proto.Message): - r"""Other properties of the build. - - Attributes: - build_invocation_id (str): - Identifies the particular build invocation, - which can be useful for finding associated logs - or other ad-hoc analysis. The value SHOULD be - globally unique, per in-toto Provenance spec. - build_started_on (google.protobuf.timestamp_pb2.Timestamp): - The timestamp of when the build started. - build_finished_on (google.protobuf.timestamp_pb2.Timestamp): - The timestamp of when the build completed. - completeness (grafeas.grafeas_v1.types.SlsaProvenance.SlsaCompleteness): - Indicates that the builder claims certain - fields in this message to be complete. - reproducible (bool): - If true, the builder claims that running the - recipe on materials will produce bit-for-bit - identical output. - """ - - build_invocation_id: str = proto.Field( - proto.STRING, - number=1, - ) - build_started_on: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - build_finished_on: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - completeness: 'SlsaProvenance.SlsaCompleteness' = proto.Field( - proto.MESSAGE, - number=4, - message='SlsaProvenance.SlsaCompleteness', - ) - reproducible: bool = proto.Field( - proto.BOOL, - number=5, - ) - - class SlsaBuilder(proto.Message): - r""" - - Attributes: - id (str): - - """ - - id: str = proto.Field( - proto.STRING, - number=1, - ) - - class Material(proto.Message): - r""" - - Attributes: - uri (str): - - digest (MutableMapping[str, str]): - - """ - - uri: str = proto.Field( - proto.STRING, - number=1, - ) - digest: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=2, - ) - - builder: SlsaBuilder = proto.Field( - proto.MESSAGE, - number=1, - message=SlsaBuilder, - ) - recipe: SlsaRecipe = proto.Field( - proto.MESSAGE, - number=2, - message=SlsaRecipe, - ) - metadata: SlsaMetadata = proto.Field( - proto.MESSAGE, - number=3, - message=SlsaMetadata, - ) - materials: MutableSequence[Material] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=Material, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/slsa_provenance_zero_two.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/slsa_provenance_zero_two.py deleted file mode 100644 index c7bb72971913..000000000000 --- a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/slsa_provenance_zero_two.py +++ /dev/null @@ -1,242 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='grafeas.v1', - manifest={ - 'SlsaProvenanceZeroTwo', - }, -) - - -class SlsaProvenanceZeroTwo(proto.Message): - r"""See full explanation of fields at slsa.dev/provenance/v0.2. - - Attributes: - builder (grafeas.grafeas_v1.types.SlsaProvenanceZeroTwo.SlsaBuilder): - - build_type (str): - - invocation (grafeas.grafeas_v1.types.SlsaProvenanceZeroTwo.SlsaInvocation): - - build_config (google.protobuf.struct_pb2.Struct): - - metadata (grafeas.grafeas_v1.types.SlsaProvenanceZeroTwo.SlsaMetadata): - - materials (MutableSequence[grafeas.grafeas_v1.types.SlsaProvenanceZeroTwo.SlsaMaterial]): - - """ - - class SlsaBuilder(proto.Message): - r"""Identifies the entity that executed the recipe, which is - trusted to have correctly performed the operation and populated - this provenance. - - Attributes: - id (str): - - """ - - id: str = proto.Field( - proto.STRING, - number=1, - ) - - class SlsaMaterial(proto.Message): - r"""The collection of artifacts that influenced the build - including sources, dependencies, build tools, base images, and - so on. - - Attributes: - uri (str): - - digest (MutableMapping[str, str]): - - """ - - uri: str = proto.Field( - proto.STRING, - number=1, - ) - digest: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=2, - ) - - class SlsaInvocation(proto.Message): - r"""Identifies the event that kicked off the build. - - Attributes: - config_source (grafeas.grafeas_v1.types.SlsaProvenanceZeroTwo.SlsaConfigSource): - - parameters (google.protobuf.struct_pb2.Struct): - - environment (google.protobuf.struct_pb2.Struct): - - """ - - config_source: 'SlsaProvenanceZeroTwo.SlsaConfigSource' = proto.Field( - proto.MESSAGE, - number=1, - message='SlsaProvenanceZeroTwo.SlsaConfigSource', - ) - parameters: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=2, - message=struct_pb2.Struct, - ) - environment: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=3, - message=struct_pb2.Struct, - ) - - class SlsaConfigSource(proto.Message): - r"""Describes where the config file that kicked off the build - came from. This is effectively a pointer to the source where - buildConfig came from. - - Attributes: - uri (str): - - digest (MutableMapping[str, str]): - - entry_point (str): - - """ - - uri: str = proto.Field( - proto.STRING, - number=1, - ) - digest: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=2, - ) - entry_point: str = proto.Field( - proto.STRING, - number=3, - ) - - class SlsaMetadata(proto.Message): - r"""Other properties of the build. - - Attributes: - build_invocation_id (str): - - build_started_on (google.protobuf.timestamp_pb2.Timestamp): - - build_finished_on (google.protobuf.timestamp_pb2.Timestamp): - - completeness (grafeas.grafeas_v1.types.SlsaProvenanceZeroTwo.SlsaCompleteness): - - reproducible (bool): - - """ - - build_invocation_id: str = proto.Field( - proto.STRING, - number=1, - ) - build_started_on: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - build_finished_on: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - completeness: 'SlsaProvenanceZeroTwo.SlsaCompleteness' = proto.Field( - proto.MESSAGE, - number=4, - message='SlsaProvenanceZeroTwo.SlsaCompleteness', - ) - reproducible: bool = proto.Field( - proto.BOOL, - number=5, - ) - - class SlsaCompleteness(proto.Message): - r"""Indicates that the builder claims certain fields in this - message to be complete. - - Attributes: - parameters (bool): - - environment (bool): - - materials (bool): - - """ - - parameters: bool = proto.Field( - proto.BOOL, - number=1, - ) - environment: bool = proto.Field( - proto.BOOL, - number=2, - ) - materials: bool = proto.Field( - proto.BOOL, - number=3, - ) - - builder: SlsaBuilder = proto.Field( - proto.MESSAGE, - number=1, - message=SlsaBuilder, - ) - build_type: str = proto.Field( - proto.STRING, - number=2, - ) - invocation: SlsaInvocation = proto.Field( - proto.MESSAGE, - number=3, - message=SlsaInvocation, - ) - build_config: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=4, - message=struct_pb2.Struct, - ) - metadata: SlsaMetadata = proto.Field( - proto.MESSAGE, - number=5, - message=SlsaMetadata, - ) - materials: MutableSequence[SlsaMaterial] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message=SlsaMaterial, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/upgrade.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/upgrade.py deleted file mode 100644 index a7181f7a083f..000000000000 --- a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/upgrade.py +++ /dev/null @@ -1,266 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 timestamp_pb2 # type: ignore -from grafeas.grafeas_v1.types import package as g_package - - -__protobuf__ = proto.module( - package='grafeas.v1', - manifest={ - 'UpgradeNote', - 'UpgradeDistribution', - 'WindowsUpdate', - 'UpgradeOccurrence', - }, -) - - -class UpgradeNote(proto.Message): - r"""An Upgrade Note represents a potential upgrade of a package to a - given version. For each package version combination (i.e. bash 4.0, - bash 4.1, bash 4.1.2), there will be an Upgrade Note. For Windows, - windows_update field represents the information related to the - update. - - Attributes: - package (str): - Required for non-Windows OS. The package this - Upgrade is for. - version (grafeas.grafeas_v1.types.Version): - Required for non-Windows OS. The version of - the package in machine + human readable form. - distributions (MutableSequence[grafeas.grafeas_v1.types.UpgradeDistribution]): - Metadata about the upgrade for each specific - operating system. - windows_update (grafeas.grafeas_v1.types.WindowsUpdate): - Required for Windows OS. Represents the - metadata about the Windows update. - """ - - package: str = proto.Field( - proto.STRING, - number=1, - ) - version: g_package.Version = proto.Field( - proto.MESSAGE, - number=2, - message=g_package.Version, - ) - distributions: MutableSequence['UpgradeDistribution'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='UpgradeDistribution', - ) - windows_update: 'WindowsUpdate' = proto.Field( - proto.MESSAGE, - number=4, - message='WindowsUpdate', - ) - - -class UpgradeDistribution(proto.Message): - r"""The Upgrade Distribution represents metadata about the - Upgrade for each operating system (CPE). Some distributions have - additional metadata around updates, classifying them into - various categories and severities. - - Attributes: - cpe_uri (str): - Required - The specific operating system this - metadata applies to. See - https://cpe.mitre.org/specification/. - classification (str): - The operating system classification of this Upgrade, as - specified by the upstream operating system upgrade feed. For - Windows the classification is one of the category_ids listed - at - https://docs.microsoft.com/en-us/previous-versions/windows/desktop/ff357803(v=vs.85) - severity (str): - The severity as specified by the upstream - operating system. - cve (MutableSequence[str]): - The cve tied to this Upgrade. - """ - - cpe_uri: str = proto.Field( - proto.STRING, - number=1, - ) - classification: str = proto.Field( - proto.STRING, - number=2, - ) - severity: str = proto.Field( - proto.STRING, - number=3, - ) - cve: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - - -class WindowsUpdate(proto.Message): - r"""Windows Update represents the metadata about the update for - the Windows operating system. The fields in this message come - from the Windows Update API documented at - https://docs.microsoft.com/en-us/windows/win32/api/wuapi/nn-wuapi-iupdate. - - Attributes: - identity (grafeas.grafeas_v1.types.WindowsUpdate.Identity): - Required - The unique identifier for the - update. - title (str): - The localized title of the update. - description (str): - The localized description of the update. - categories (MutableSequence[grafeas.grafeas_v1.types.WindowsUpdate.Category]): - The list of categories to which the update - belongs. - kb_article_ids (MutableSequence[str]): - The Microsoft Knowledge Base article IDs that - are associated with the update. - support_url (str): - The hyperlink to the support information for - the update. - last_published_timestamp (google.protobuf.timestamp_pb2.Timestamp): - The last published timestamp of the update. - """ - - class Identity(proto.Message): - r"""The unique identifier of the update. - - Attributes: - update_id (str): - The revision independent identifier of the - update. - revision (int): - The revision number of the update. - """ - - update_id: str = proto.Field( - proto.STRING, - number=1, - ) - revision: int = proto.Field( - proto.INT32, - number=2, - ) - - class Category(proto.Message): - r"""The category to which the update belongs. - - Attributes: - category_id (str): - The identifier of the category. - name (str): - The localized name of the category. - """ - - category_id: str = proto.Field( - proto.STRING, - number=1, - ) - name: str = proto.Field( - proto.STRING, - number=2, - ) - - identity: Identity = proto.Field( - proto.MESSAGE, - number=1, - message=Identity, - ) - title: str = proto.Field( - proto.STRING, - number=2, - ) - description: str = proto.Field( - proto.STRING, - number=3, - ) - categories: MutableSequence[Category] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=Category, - ) - kb_article_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - support_url: str = proto.Field( - proto.STRING, - number=6, - ) - last_published_timestamp: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - - -class UpgradeOccurrence(proto.Message): - r"""An Upgrade Occurrence represents that a specific resource_url could - install a specific upgrade. This presence is supplied via local - sources (i.e. it is present in the mirror and the running system has - noticed its availability). For Windows, both distribution and - windows_update contain information for the Windows update. - - Attributes: - package (str): - Required for non-Windows OS. The package this - Upgrade is for. - parsed_version (grafeas.grafeas_v1.types.Version): - Required for non-Windows OS. The version of - the package in a machine + human readable form. - distribution (grafeas.grafeas_v1.types.UpgradeDistribution): - Metadata about the upgrade for available for the specific - operating system for the resource_url. This allows efficient - filtering, as well as making it easier to use the - occurrence. - windows_update (grafeas.grafeas_v1.types.WindowsUpdate): - Required for Windows OS. Represents the - metadata about the Windows update. - """ - - package: str = proto.Field( - proto.STRING, - number=1, - ) - parsed_version: g_package.Version = proto.Field( - proto.MESSAGE, - number=3, - message=g_package.Version, - ) - distribution: 'UpgradeDistribution' = proto.Field( - proto.MESSAGE, - number=4, - message='UpgradeDistribution', - ) - windows_update: 'WindowsUpdate' = proto.Field( - proto.MESSAGE, - number=5, - message='WindowsUpdate', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/vex.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/vex.py deleted file mode 100644 index 813c1613f2b7..000000000000 --- a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/vex.py +++ /dev/null @@ -1,384 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 grafeas.grafeas_v1.types import common - - -__protobuf__ = proto.module( - package='grafeas.v1', - manifest={ - 'VulnerabilityAssessmentNote', - }, -) - - -class VulnerabilityAssessmentNote(proto.Message): - r"""A single VulnerabilityAssessmentNote represents - one particular product's vulnerability assessment for one CVE. - - Attributes: - title (str): - The title of the note. E.g. ``Vex-Debian-11.4`` - short_description (str): - A one sentence description of this Vex. - long_description (str): - A detailed description of this Vex. - language_code (str): - Identifies the language used by this - document, corresponding to IETF BCP 47 / RFC - 5646. - publisher (grafeas.grafeas_v1.types.VulnerabilityAssessmentNote.Publisher): - Publisher details of this Note. - product (grafeas.grafeas_v1.types.VulnerabilityAssessmentNote.Product): - The product affected by this vex. - assessment (grafeas.grafeas_v1.types.VulnerabilityAssessmentNote.Assessment): - Represents a vulnerability assessment for the - product. - """ - - class Publisher(proto.Message): - r"""Publisher contains information about the publisher of - this Note. - (-- api-linter: core::0123::resource-annotation=disabled - aip.dev/not-precedent: Publisher is not a separate resource. --) - - Attributes: - name (str): - Name of the publisher. - Examples: 'Google', 'Google Cloud Platform'. - issuing_authority (str): - Provides information about the authority of - the issuing party to release the document, in - particular, the party's constituency and - responsibilities or other obligations. - publisher_namespace (str): - The context or namespace. - Contains a URL which is under control of the - issuing party and can be used as a globally - unique identifier for that issuing party. - Example: https://csaf.io - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - issuing_authority: str = proto.Field( - proto.STRING, - number=2, - ) - publisher_namespace: str = proto.Field( - proto.STRING, - number=3, - ) - - class Product(proto.Message): - r"""Product contains information about a product and how to - uniquely identify it. - (-- api-linter: core::0123::resource-annotation=disabled - aip.dev/not-precedent: Product is not a separate resource. --) - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - Name of the product. - id (str): - Token that identifies a product so that it - can be referred to from other parts in the - document. There is no predefined format as long - as it uniquely identifies a group in the context - of the current document. - generic_uri (str): - Contains a URI which is vendor-specific. - Example: The artifact repository URL of an - image. - - This field is a member of `oneof`_ ``identifier``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - id: str = proto.Field( - proto.STRING, - number=2, - ) - generic_uri: str = proto.Field( - proto.STRING, - number=3, - oneof='identifier', - ) - - class Assessment(proto.Message): - r"""Assessment provides all information that is related to a - single vulnerability for this product. - - Attributes: - cve (str): - Holds the MITRE standard Common Vulnerabilities and - Exposures (CVE) tracking number for the vulnerability. - Deprecated: Use vulnerability_id instead to denote CVEs. - vulnerability_id (str): - The vulnerability identifier for this - Assessment. Will hold one of common identifiers - e.g. CVE, GHSA etc. - short_description (str): - A one sentence description of this Vex. - long_description (str): - A detailed description of this Vex. - related_uris (MutableSequence[grafeas.grafeas_v1.types.RelatedUrl]): - Holds a list of references associated with - this vulnerability item and assessment. These - uris have additional information about the - vulnerability and the assessment itself. E.g. - Link to a document which details how this - assessment concluded the state of this - vulnerability. - state (grafeas.grafeas_v1.types.VulnerabilityAssessmentNote.Assessment.State): - Provides the state of this Vulnerability - assessment. - impacts (MutableSequence[str]): - Contains information about the impact of this - vulnerability, this will change with time. - justification (grafeas.grafeas_v1.types.VulnerabilityAssessmentNote.Assessment.Justification): - Justification provides the justification when the state of - the assessment if NOT_AFFECTED. - remediations (MutableSequence[grafeas.grafeas_v1.types.VulnerabilityAssessmentNote.Assessment.Remediation]): - Specifies details on how to handle (and - presumably, fix) a vulnerability. - """ - class State(proto.Enum): - r"""Provides the state of this Vulnerability assessment. - - Values: - STATE_UNSPECIFIED (0): - No state is specified. - AFFECTED (1): - This product is known to be affected by this - vulnerability. - NOT_AFFECTED (2): - This product is known to be not affected by - this vulnerability. - FIXED (3): - This product contains a fix for this - vulnerability. - UNDER_INVESTIGATION (4): - It is not known yet whether these versions - are or are not affected by the vulnerability. - However, it is still under investigation. - """ - STATE_UNSPECIFIED = 0 - AFFECTED = 1 - NOT_AFFECTED = 2 - FIXED = 3 - UNDER_INVESTIGATION = 4 - - class Justification(proto.Message): - r"""Justification provides the justification when the state of the - assessment if NOT_AFFECTED. - - Attributes: - justification_type (grafeas.grafeas_v1.types.VulnerabilityAssessmentNote.Assessment.Justification.JustificationType): - The justification type for this - vulnerability. - details (str): - Additional details on why this justification - was chosen. - """ - class JustificationType(proto.Enum): - r"""Provides the type of justification. - - Values: - JUSTIFICATION_TYPE_UNSPECIFIED (0): - JUSTIFICATION_TYPE_UNSPECIFIED. - COMPONENT_NOT_PRESENT (1): - The vulnerable component is not present in - the product. - VULNERABLE_CODE_NOT_PRESENT (2): - The vulnerable code is not present. Typically - this case occurs when source code is configured - or built in a way that excludes the vulnerable - code. - VULNERABLE_CODE_NOT_IN_EXECUTE_PATH (3): - The vulnerable code can not be executed. - Typically this case occurs when the product - includes the vulnerable code but does not call - or use the vulnerable code. - VULNERABLE_CODE_CANNOT_BE_CONTROLLED_BY_ADVERSARY (4): - The vulnerable code cannot be controlled by - an attacker to exploit the vulnerability. - INLINE_MITIGATIONS_ALREADY_EXIST (5): - The product includes built-in protections or - features that prevent exploitation of the - vulnerability. These built-in protections cannot - be subverted by the attacker and cannot be - configured or disabled by the user. These - mitigations completely prevent exploitation - based on known attack vectors. - """ - JUSTIFICATION_TYPE_UNSPECIFIED = 0 - COMPONENT_NOT_PRESENT = 1 - VULNERABLE_CODE_NOT_PRESENT = 2 - VULNERABLE_CODE_NOT_IN_EXECUTE_PATH = 3 - VULNERABLE_CODE_CANNOT_BE_CONTROLLED_BY_ADVERSARY = 4 - INLINE_MITIGATIONS_ALREADY_EXIST = 5 - - justification_type: 'VulnerabilityAssessmentNote.Assessment.Justification.JustificationType' = proto.Field( - proto.ENUM, - number=1, - enum='VulnerabilityAssessmentNote.Assessment.Justification.JustificationType', - ) - details: str = proto.Field( - proto.STRING, - number=2, - ) - - class Remediation(proto.Message): - r"""Specifies details on how to handle (and presumably, fix) a - vulnerability. - - Attributes: - remediation_type (grafeas.grafeas_v1.types.VulnerabilityAssessmentNote.Assessment.Remediation.RemediationType): - The type of remediation that can be applied. - details (str): - Contains a comprehensive human-readable - discussion of the remediation. - remediation_uri (grafeas.grafeas_v1.types.RelatedUrl): - Contains the URL where to obtain the - remediation. - """ - class RemediationType(proto.Enum): - r"""The type of remediation that can be applied. - - Values: - REMEDIATION_TYPE_UNSPECIFIED (0): - No remediation type specified. - MITIGATION (1): - A MITIGATION is available. - NO_FIX_PLANNED (2): - No fix is planned. - NONE_AVAILABLE (3): - Not available. - VENDOR_FIX (4): - A vendor fix is available. - WORKAROUND (5): - A workaround is available. - """ - REMEDIATION_TYPE_UNSPECIFIED = 0 - MITIGATION = 1 - NO_FIX_PLANNED = 2 - NONE_AVAILABLE = 3 - VENDOR_FIX = 4 - WORKAROUND = 5 - - remediation_type: 'VulnerabilityAssessmentNote.Assessment.Remediation.RemediationType' = proto.Field( - proto.ENUM, - number=1, - enum='VulnerabilityAssessmentNote.Assessment.Remediation.RemediationType', - ) - details: str = proto.Field( - proto.STRING, - number=2, - ) - remediation_uri: common.RelatedUrl = proto.Field( - proto.MESSAGE, - number=3, - message=common.RelatedUrl, - ) - - cve: str = proto.Field( - proto.STRING, - number=1, - ) - vulnerability_id: str = proto.Field( - proto.STRING, - number=9, - ) - short_description: str = proto.Field( - proto.STRING, - number=2, - ) - long_description: str = proto.Field( - proto.STRING, - number=3, - ) - related_uris: MutableSequence[common.RelatedUrl] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=common.RelatedUrl, - ) - state: 'VulnerabilityAssessmentNote.Assessment.State' = proto.Field( - proto.ENUM, - number=5, - enum='VulnerabilityAssessmentNote.Assessment.State', - ) - impacts: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=6, - ) - justification: 'VulnerabilityAssessmentNote.Assessment.Justification' = proto.Field( - proto.MESSAGE, - number=7, - message='VulnerabilityAssessmentNote.Assessment.Justification', - ) - remediations: MutableSequence['VulnerabilityAssessmentNote.Assessment.Remediation'] = proto.RepeatedField( - proto.MESSAGE, - number=8, - message='VulnerabilityAssessmentNote.Assessment.Remediation', - ) - - title: str = proto.Field( - proto.STRING, - number=1, - ) - short_description: str = proto.Field( - proto.STRING, - number=2, - ) - long_description: str = proto.Field( - proto.STRING, - number=3, - ) - language_code: str = proto.Field( - proto.STRING, - number=4, - ) - publisher: Publisher = proto.Field( - proto.MESSAGE, - number=5, - message=Publisher, - ) - product: Product = proto.Field( - proto.MESSAGE, - number=6, - message=Product, - ) - assessment: Assessment = proto.Field( - proto.MESSAGE, - number=7, - message=Assessment, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/vulnerability.py b/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/vulnerability.py deleted file mode 100644 index 97000d7d501b..000000000000 --- a/owl-bot-staging/grafeas/v1/grafeas/grafeas_v1/types/vulnerability.py +++ /dev/null @@ -1,594 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 timestamp_pb2 # type: ignore -from grafeas.grafeas_v1.types import common -from grafeas.grafeas_v1.types import cvss -from grafeas.grafeas_v1.types import package -from grafeas.grafeas_v1.types import severity as g_severity -from grafeas.grafeas_v1.types import vex - - -__protobuf__ = proto.module( - package='grafeas.v1', - manifest={ - 'VulnerabilityNote', - 'VulnerabilityOccurrence', - }, -) - - -class VulnerabilityNote(proto.Message): - r"""A security vulnerability that can be found in resources. - - Attributes: - cvss_score (float): - The CVSS score of this vulnerability. CVSS - score is on a scale of 0 - 10 where 0 indicates - low severity and 10 indicates high severity. - severity (grafeas.grafeas_v1.types.Severity): - The note provider assigned severity of this - vulnerability. - details (MutableSequence[grafeas.grafeas_v1.types.VulnerabilityNote.Detail]): - Details of all known distros and packages - affected by this vulnerability. - cvss_v3 (grafeas.grafeas_v1.types.CVSSv3): - The full description of the CVSSv3 for this - vulnerability. - windows_details (MutableSequence[grafeas.grafeas_v1.types.VulnerabilityNote.WindowsDetail]): - Windows details get their own format because - the information format and model don't match a - normal detail. Specifically Windows updates are - done as patches, thus Windows vulnerabilities - really are a missing package, rather than a - package being at an incorrect version. - source_update_time (google.protobuf.timestamp_pb2.Timestamp): - The time this information was last changed at - the source. This is an upstream timestamp from - the underlying information source - e.g. Ubuntu - security tracker. - cvss_version (grafeas.grafeas_v1.types.CVSSVersion): - CVSS version used to populate cvss_score and severity. - cvss_v2 (grafeas.grafeas_v1.types.CVSS): - The full description of the v2 CVSS for this - vulnerability. - """ - - class Detail(proto.Message): - r"""A detail for a distro and package affected by this - vulnerability and its associated fix (if one is available). - - Attributes: - severity_name (str): - The distro assigned severity of this - vulnerability. - description (str): - A vendor-specific description of this - vulnerability. - package_type (str): - The type of package; whether native or non - native (e.g., ruby gems, node.js packages, - etc.). - affected_cpe_uri (str): - Required. The `CPE - URI `__ this - vulnerability affects. - affected_package (str): - Required. The package this vulnerability - affects. - affected_version_start (grafeas.grafeas_v1.types.Version): - The version number at the start of an interval in which this - vulnerability exists. A vulnerability can affect a package - between version numbers that are disjoint sets of intervals - (example: [1.0.0-1.1.0], [2.4.6-2.4.8] and [4.5.6-4.6.8]) - each of which will be represented in its own Detail. If a - specific affected version is provided by a vulnerability - database, affected_version_start and affected_version_end - will be the same in that Detail. - affected_version_end (grafeas.grafeas_v1.types.Version): - The version number at the end of an interval in which this - vulnerability exists. A vulnerability can affect a package - between version numbers that are disjoint sets of intervals - (example: [1.0.0-1.1.0], [2.4.6-2.4.8] and [4.5.6-4.6.8]) - each of which will be represented in its own Detail. If a - specific affected version is provided by a vulnerability - database, affected_version_start and affected_version_end - will be the same in that Detail. - fixed_cpe_uri (str): - The distro recommended `CPE - URI `__ to update to - that contains a fix for this vulnerability. It is possible - for this to be different from the affected_cpe_uri. - fixed_package (str): - The distro recommended package to update to that contains a - fix for this vulnerability. It is possible for this to be - different from the affected_package. - fixed_version (grafeas.grafeas_v1.types.Version): - The distro recommended version to update to - that contains a fix for this vulnerability. - Setting this to VersionKind.MAXIMUM means no - such version is yet available. - is_obsolete (bool): - Whether this detail is obsolete. Occurrences - are expected not to point to obsolete details. - source_update_time (google.protobuf.timestamp_pb2.Timestamp): - The time this information was last changed at - the source. This is an upstream timestamp from - the underlying information source - e.g. Ubuntu - security tracker. - source (str): - The source from which the information in this - Detail was obtained. - vendor (str): - The name of the vendor of the product. - """ - - severity_name: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - package_type: str = proto.Field( - proto.STRING, - number=3, - ) - affected_cpe_uri: str = proto.Field( - proto.STRING, - number=4, - ) - affected_package: str = proto.Field( - proto.STRING, - number=5, - ) - affected_version_start: package.Version = proto.Field( - proto.MESSAGE, - number=6, - message=package.Version, - ) - affected_version_end: package.Version = proto.Field( - proto.MESSAGE, - number=7, - message=package.Version, - ) - fixed_cpe_uri: str = proto.Field( - proto.STRING, - number=8, - ) - fixed_package: str = proto.Field( - proto.STRING, - number=9, - ) - fixed_version: package.Version = proto.Field( - proto.MESSAGE, - number=10, - message=package.Version, - ) - is_obsolete: bool = proto.Field( - proto.BOOL, - number=11, - ) - source_update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=12, - message=timestamp_pb2.Timestamp, - ) - source: str = proto.Field( - proto.STRING, - number=13, - ) - vendor: str = proto.Field( - proto.STRING, - number=14, - ) - - class WindowsDetail(proto.Message): - r""" - - Attributes: - cpe_uri (str): - Required. The `CPE - URI `__ this - vulnerability affects. - name (str): - Required. The name of this vulnerability. - description (str): - The description of this vulnerability. - fixing_kbs (MutableSequence[grafeas.grafeas_v1.types.VulnerabilityNote.WindowsDetail.KnowledgeBase]): - Required. The names of the KBs which have - hotfixes to mitigate this vulnerability. Note - that there may be multiple hotfixes (and thus - multiple KBs) that mitigate a given - vulnerability. Currently any listed KBs presence - is considered a fix. - """ - - class KnowledgeBase(proto.Message): - r""" - - Attributes: - name (str): - The KB name (generally of the form KB[0-9]+ (e.g., - KB123456)). - url (str): - A link to the KB in the [Windows update catalog] - (https://www.catalog.update.microsoft.com/). - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - url: str = proto.Field( - proto.STRING, - number=2, - ) - - cpe_uri: str = proto.Field( - proto.STRING, - number=1, - ) - name: str = proto.Field( - proto.STRING, - number=2, - ) - description: str = proto.Field( - proto.STRING, - number=3, - ) - fixing_kbs: MutableSequence['VulnerabilityNote.WindowsDetail.KnowledgeBase'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='VulnerabilityNote.WindowsDetail.KnowledgeBase', - ) - - cvss_score: float = proto.Field( - proto.FLOAT, - number=1, - ) - severity: g_severity.Severity = proto.Field( - proto.ENUM, - number=2, - enum=g_severity.Severity, - ) - details: MutableSequence[Detail] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=Detail, - ) - cvss_v3: cvss.CVSSv3 = proto.Field( - proto.MESSAGE, - number=4, - message=cvss.CVSSv3, - ) - windows_details: MutableSequence[WindowsDetail] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=WindowsDetail, - ) - source_update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - cvss_version: cvss.CVSSVersion = proto.Field( - proto.ENUM, - number=7, - enum=cvss.CVSSVersion, - ) - cvss_v2: cvss.CVSS = proto.Field( - proto.MESSAGE, - number=8, - message=cvss.CVSS, - ) - - -class VulnerabilityOccurrence(proto.Message): - r"""An occurrence of a severity vulnerability on a resource. - - Attributes: - type_ (str): - The type of package; whether native or non - native (e.g., ruby gems, node.js packages, - etc.). - severity (grafeas.grafeas_v1.types.Severity): - Output only. The note provider assigned - severity of this vulnerability. - cvss_score (float): - Output only. The CVSS score of this - vulnerability. CVSS score is on a scale of 0 - - 10 where 0 indicates low severity and 10 - indicates high severity. - cvssv3 (grafeas.grafeas_v1.types.CVSS): - The cvss v3 score for the vulnerability. - package_issue (MutableSequence[grafeas.grafeas_v1.types.VulnerabilityOccurrence.PackageIssue]): - Required. The set of affected locations and - their fixes (if available) within the associated - resource. - short_description (str): - Output only. A one sentence description of - this vulnerability. - long_description (str): - Output only. A detailed description of this - vulnerability. - related_urls (MutableSequence[grafeas.grafeas_v1.types.RelatedUrl]): - Output only. URLs related to this - vulnerability. - effective_severity (grafeas.grafeas_v1.types.Severity): - The distro assigned severity for this - vulnerability when it is available, otherwise - this is the note provider assigned severity. - - When there are multiple PackageIssues for this - vulnerability, they can have different effective - severities because some might be provided by the - distro while others are provided by the language - ecosystem for a language pack. For this reason, - it is advised to use the effective severity on - the PackageIssue level. In the case where - multiple PackageIssues have differing effective - severities, this field should be the highest - severity for any of the PackageIssues. - fix_available (bool): - Output only. Whether at least one of the - affected packages has a fix available. - cvss_version (grafeas.grafeas_v1.types.CVSSVersion): - Output only. CVSS version used to populate cvss_score and - severity. - cvss_v2 (grafeas.grafeas_v1.types.CVSS): - The cvss v2 score for the vulnerability. - vex_assessment (grafeas.grafeas_v1.types.VulnerabilityOccurrence.VexAssessment): - - extra_details (str): - Occurrence-specific extra details about the - vulnerability. - """ - - class PackageIssue(proto.Message): - r"""A detail for a distro and package this vulnerability - occurrence was found in and its associated fix (if one is - available). - - Attributes: - affected_cpe_uri (str): - Required. The `CPE - URI `__ this - vulnerability was found in. - affected_package (str): - Required. The package this vulnerability was - found in. - affected_version (grafeas.grafeas_v1.types.Version): - Required. The version of the package that is - installed on the resource affected by this - vulnerability. - fixed_cpe_uri (str): - The `CPE URI `__ this - vulnerability was fixed in. It is possible for this to be - different from the affected_cpe_uri. - fixed_package (str): - The package this vulnerability was fixed in. It is possible - for this to be different from the affected_package. - fixed_version (grafeas.grafeas_v1.types.Version): - Required. The version of the package this - vulnerability was fixed in. Setting this to - VersionKind.MAXIMUM means no fix is yet - available. - fix_available (bool): - Output only. Whether a fix is available for - this package. - package_type (str): - The type of package (e.g. OS, MAVEN, GO). - effective_severity (grafeas.grafeas_v1.types.Severity): - The distro or language system assigned - severity for this vulnerability when that is - available and note provider assigned severity - when it is not available. - file_location (MutableSequence[grafeas.grafeas_v1.types.FileLocation]): - The location at which this package was found. - """ - - affected_cpe_uri: str = proto.Field( - proto.STRING, - number=1, - ) - affected_package: str = proto.Field( - proto.STRING, - number=2, - ) - affected_version: package.Version = proto.Field( - proto.MESSAGE, - number=3, - message=package.Version, - ) - fixed_cpe_uri: str = proto.Field( - proto.STRING, - number=4, - ) - fixed_package: str = proto.Field( - proto.STRING, - number=5, - ) - fixed_version: package.Version = proto.Field( - proto.MESSAGE, - number=6, - message=package.Version, - ) - fix_available: bool = proto.Field( - proto.BOOL, - number=7, - ) - package_type: str = proto.Field( - proto.STRING, - number=8, - ) - effective_severity: g_severity.Severity = proto.Field( - proto.ENUM, - number=9, - enum=g_severity.Severity, - ) - file_location: MutableSequence[common.FileLocation] = proto.RepeatedField( - proto.MESSAGE, - number=10, - message=common.FileLocation, - ) - - class VexAssessment(proto.Message): - r"""VexAssessment provides all publisher provided Vex information - that is related to this vulnerability. - - Attributes: - cve (str): - Holds the MITRE standard Common Vulnerabilities and - Exposures (CVE) tracking number for the vulnerability. - Deprecated: Use vulnerability_id instead to denote CVEs. - vulnerability_id (str): - The vulnerability identifier for this - Assessment. Will hold one of common identifiers - e.g. CVE, GHSA etc. - related_uris (MutableSequence[grafeas.grafeas_v1.types.RelatedUrl]): - Holds a list of references associated with - this vulnerability item and assessment. - note_name (str): - The VulnerabilityAssessment note from which this - VexAssessment was generated. This will be of the form: - ``projects/[PROJECT_ID]/notes/[NOTE_ID]``. (-- api-linter: - core::0122::name-suffix=disabled aip.dev/not-precedent: The - suffix is kept for consistency. --) - state (grafeas.grafeas_v1.types.VulnerabilityAssessmentNote.Assessment.State): - Provides the state of this Vulnerability - assessment. - impacts (MutableSequence[str]): - Contains information about the impact of this - vulnerability, this will change with time. - remediations (MutableSequence[grafeas.grafeas_v1.types.VulnerabilityAssessmentNote.Assessment.Remediation]): - Specifies details on how to handle (and - presumably, fix) a vulnerability. - justification (grafeas.grafeas_v1.types.VulnerabilityAssessmentNote.Assessment.Justification): - Justification provides the justification when the state of - the assessment if NOT_AFFECTED. - """ - - cve: str = proto.Field( - proto.STRING, - number=1, - ) - vulnerability_id: str = proto.Field( - proto.STRING, - number=8, - ) - related_uris: MutableSequence[common.RelatedUrl] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=common.RelatedUrl, - ) - note_name: str = proto.Field( - proto.STRING, - number=3, - ) - state: vex.VulnerabilityAssessmentNote.Assessment.State = proto.Field( - proto.ENUM, - number=4, - enum=vex.VulnerabilityAssessmentNote.Assessment.State, - ) - impacts: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - remediations: MutableSequence[vex.VulnerabilityAssessmentNote.Assessment.Remediation] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message=vex.VulnerabilityAssessmentNote.Assessment.Remediation, - ) - justification: vex.VulnerabilityAssessmentNote.Assessment.Justification = proto.Field( - proto.MESSAGE, - number=7, - message=vex.VulnerabilityAssessmentNote.Assessment.Justification, - ) - - type_: str = proto.Field( - proto.STRING, - number=1, - ) - severity: g_severity.Severity = proto.Field( - proto.ENUM, - number=2, - enum=g_severity.Severity, - ) - cvss_score: float = proto.Field( - proto.FLOAT, - number=3, - ) - cvssv3: cvss.CVSS = proto.Field( - proto.MESSAGE, - number=10, - message=cvss.CVSS, - ) - package_issue: MutableSequence[PackageIssue] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=PackageIssue, - ) - short_description: str = proto.Field( - proto.STRING, - number=5, - ) - long_description: str = proto.Field( - proto.STRING, - number=6, - ) - related_urls: MutableSequence[common.RelatedUrl] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message=common.RelatedUrl, - ) - effective_severity: g_severity.Severity = proto.Field( - proto.ENUM, - number=8, - enum=g_severity.Severity, - ) - fix_available: bool = proto.Field( - proto.BOOL, - number=9, - ) - cvss_version: cvss.CVSSVersion = proto.Field( - proto.ENUM, - number=11, - enum=cvss.CVSSVersion, - ) - cvss_v2: cvss.CVSS = proto.Field( - proto.MESSAGE, - number=12, - message=cvss.CVSS, - ) - vex_assessment: VexAssessment = proto.Field( - proto.MESSAGE, - number=13, - message=VexAssessment, - ) - extra_details: str = proto.Field( - proto.STRING, - number=14, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/grafeas/v1/mypy.ini b/owl-bot-staging/grafeas/v1/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/grafeas/v1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/grafeas/v1/noxfile.py b/owl-bot-staging/grafeas/v1/noxfile.py deleted file mode 100644 index 72c4db956057..000000000000 --- a/owl-bot-staging/grafeas/v1/noxfile.py +++ /dev/null @@ -1,280 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", - "3.12", - "3.13", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = 'grafeas' - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.13" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "prerelease_deps", -] - -@nox.session(python=ALL_PYTHON) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def unit(session, protobuf_implementation): - """Run the unit test suite.""" - - 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+") - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") - - # 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") - - session.run( - 'py.test', - '--quiet', - '--cov=grafeas/grafeas_v1/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - -@nox.session(python=ALL_PYTHON[-1]) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def prerelease_deps(session, protobuf_implementation): - """Run the unit test suite against pre-release versions of dependencies.""" - - 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 test environment dependencies - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - - # Install the package without dependencies - session.install('-e', '.', '--no-deps') - - # We test the minimum dependency versions using the minimum Python - # version so the lowest python runtime that we test has a corresponding constraints - # file, located at `testing/constraints--.txt`, which contains all of the - # 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 - ) - ] - - session.install(*constraints_deps) - - prerel_deps = [ - "googleapis-common-protos", - "google-api-core", - "google-auth", - # Exclude grpcio!=1.67.0rc1 which does not support python 3.13 - "grpcio!=1.67.0rc1", - "grpcio-status", - "protobuf", - "proto-plus", - ] - - for dep in prerel_deps: - session.install("--pre", "--no-deps", "--upgrade", dep) - - # Remaining dependencies - other_deps = [ - "requests", - ] - session.install(*other_deps) - - # Print out prerelease package versions - - session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") - session.run("python", "-c", "import google.auth; print(google.auth.__version__)") - session.run("python", "-c", "import grpc; print(grpc.__version__)") - session.run( - "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" - ) - session.run( - "python", "-c", "import proto; print(proto.__version__)" - ) - - session.run( - 'py.test', - '--quiet', - '--cov=grafeas/grafeas_v1/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - - -@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=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install( - 'mypy', - 'types-requests', - 'types-protobuf' - ) - session.install('.') - session.run( - 'mypy', - '-p', - 'grafeas', - ) - - -@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 docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==7.0.1", "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=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", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_notes_async.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_notes_async.py deleted file mode 100644 index 9ed3ef3bae74..000000000000 --- a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_notes_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchCreateNotes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_BatchCreateNotes_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 grafeas import grafeas_v1 - - -async def sample_batch_create_notes(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.BatchCreateNotesRequest( - parent="parent_value", - ) - - # Make the request - response = await client.batch_create_notes(request=request) - - # Handle the response - print(response) - -# [END containeranalysis_v1_generated_Grafeas_BatchCreateNotes_async] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_notes_sync.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_notes_sync.py deleted file mode 100644 index 096f01fd138e..000000000000 --- a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_notes_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchCreateNotes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_BatchCreateNotes_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 grafeas import grafeas_v1 - - -def sample_batch_create_notes(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.BatchCreateNotesRequest( - parent="parent_value", - ) - - # Make the request - response = client.batch_create_notes(request=request) - - # Handle the response - print(response) - -# [END containeranalysis_v1_generated_Grafeas_BatchCreateNotes_sync] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_occurrences_async.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_occurrences_async.py deleted file mode 100644 index 10d0a30d5906..000000000000 --- a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_occurrences_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchCreateOccurrences -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_BatchCreateOccurrences_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 grafeas import grafeas_v1 - - -async def sample_batch_create_occurrences(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.BatchCreateOccurrencesRequest( - parent="parent_value", - ) - - # Make the request - response = await client.batch_create_occurrences(request=request) - - # Handle the response - print(response) - -# [END containeranalysis_v1_generated_Grafeas_BatchCreateOccurrences_async] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_occurrences_sync.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_occurrences_sync.py deleted file mode 100644 index 8f3350d81758..000000000000 --- a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_occurrences_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchCreateOccurrences -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_BatchCreateOccurrences_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 grafeas import grafeas_v1 - - -def sample_batch_create_occurrences(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.BatchCreateOccurrencesRequest( - parent="parent_value", - ) - - # Make the request - response = client.batch_create_occurrences(request=request) - - # Handle the response - print(response) - -# [END containeranalysis_v1_generated_Grafeas_BatchCreateOccurrences_sync] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_note_async.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_note_async.py deleted file mode 100644 index 22163012ecf9..000000000000 --- a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_note_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateNote -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_CreateNote_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 grafeas import grafeas_v1 - - -async def sample_create_note(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.CreateNoteRequest( - parent="parent_value", - note_id="note_id_value", - ) - - # Make the request - response = await client.create_note(request=request) - - # Handle the response - print(response) - -# [END containeranalysis_v1_generated_Grafeas_CreateNote_async] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_note_sync.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_note_sync.py deleted file mode 100644 index 45d9b8827182..000000000000 --- a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_note_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateNote -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_CreateNote_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 grafeas import grafeas_v1 - - -def sample_create_note(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.CreateNoteRequest( - parent="parent_value", - note_id="note_id_value", - ) - - # Make the request - response = client.create_note(request=request) - - # Handle the response - print(response) - -# [END containeranalysis_v1_generated_Grafeas_CreateNote_sync] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_occurrence_async.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_occurrence_async.py deleted file mode 100644 index 55ad3999e351..000000000000 --- a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_occurrence_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateOccurrence -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_CreateOccurrence_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 grafeas import grafeas_v1 - - -async def sample_create_occurrence(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.CreateOccurrenceRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_occurrence(request=request) - - # Handle the response - print(response) - -# [END containeranalysis_v1_generated_Grafeas_CreateOccurrence_async] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_occurrence_sync.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_occurrence_sync.py deleted file mode 100644 index fbb4fd13a857..000000000000 --- a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_occurrence_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateOccurrence -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_CreateOccurrence_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 grafeas import grafeas_v1 - - -def sample_create_occurrence(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.CreateOccurrenceRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_occurrence(request=request) - - # Handle the response - print(response) - -# [END containeranalysis_v1_generated_Grafeas_CreateOccurrence_sync] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_note_async.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_note_async.py deleted file mode 100644 index c128ae0f2a90..000000000000 --- a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_note_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteNote -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_DeleteNote_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 grafeas import grafeas_v1 - - -async def sample_delete_note(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.DeleteNoteRequest( - name="name_value", - ) - - # Make the request - await client.delete_note(request=request) - - -# [END containeranalysis_v1_generated_Grafeas_DeleteNote_async] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_note_sync.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_note_sync.py deleted file mode 100644 index 8311e5af56c1..000000000000 --- a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_note_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteNote -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_DeleteNote_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 grafeas import grafeas_v1 - - -def sample_delete_note(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.DeleteNoteRequest( - name="name_value", - ) - - # Make the request - client.delete_note(request=request) - - -# [END containeranalysis_v1_generated_Grafeas_DeleteNote_sync] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_occurrence_async.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_occurrence_async.py deleted file mode 100644 index eb53c4ac9f81..000000000000 --- a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_occurrence_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteOccurrence -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_DeleteOccurrence_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 grafeas import grafeas_v1 - - -async def sample_delete_occurrence(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.DeleteOccurrenceRequest( - name="name_value", - ) - - # Make the request - await client.delete_occurrence(request=request) - - -# [END containeranalysis_v1_generated_Grafeas_DeleteOccurrence_async] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_occurrence_sync.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_occurrence_sync.py deleted file mode 100644 index 1d3df488a391..000000000000 --- a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_occurrence_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteOccurrence -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_DeleteOccurrence_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 grafeas import grafeas_v1 - - -def sample_delete_occurrence(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.DeleteOccurrenceRequest( - name="name_value", - ) - - # Make the request - client.delete_occurrence(request=request) - - -# [END containeranalysis_v1_generated_Grafeas_DeleteOccurrence_sync] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_note_async.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_note_async.py deleted file mode 100644 index eb74332119ed..000000000000 --- a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_note_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetNote -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_GetNote_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 grafeas import grafeas_v1 - - -async def sample_get_note(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.GetNoteRequest( - name="name_value", - ) - - # Make the request - response = await client.get_note(request=request) - - # Handle the response - print(response) - -# [END containeranalysis_v1_generated_Grafeas_GetNote_async] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_note_sync.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_note_sync.py deleted file mode 100644 index 4026633cc025..000000000000 --- a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_note_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetNote -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_GetNote_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 grafeas import grafeas_v1 - - -def sample_get_note(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.GetNoteRequest( - name="name_value", - ) - - # Make the request - response = client.get_note(request=request) - - # Handle the response - print(response) - -# [END containeranalysis_v1_generated_Grafeas_GetNote_sync] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_async.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_async.py deleted file mode 100644 index cedafd39e047..000000000000 --- a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetOccurrence -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_GetOccurrence_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 grafeas import grafeas_v1 - - -async def sample_get_occurrence(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.GetOccurrenceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_occurrence(request=request) - - # Handle the response - print(response) - -# [END containeranalysis_v1_generated_Grafeas_GetOccurrence_async] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_note_async.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_note_async.py deleted file mode 100644 index 28817551ddf3..000000000000 --- a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_note_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetOccurrenceNote -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_GetOccurrenceNote_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 grafeas import grafeas_v1 - - -async def sample_get_occurrence_note(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.GetOccurrenceNoteRequest( - name="name_value", - ) - - # Make the request - response = await client.get_occurrence_note(request=request) - - # Handle the response - print(response) - -# [END containeranalysis_v1_generated_Grafeas_GetOccurrenceNote_async] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_note_sync.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_note_sync.py deleted file mode 100644 index 7bf9619cccaf..000000000000 --- a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_note_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetOccurrenceNote -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_GetOccurrenceNote_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 grafeas import grafeas_v1 - - -def sample_get_occurrence_note(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.GetOccurrenceNoteRequest( - name="name_value", - ) - - # Make the request - response = client.get_occurrence_note(request=request) - - # Handle the response - print(response) - -# [END containeranalysis_v1_generated_Grafeas_GetOccurrenceNote_sync] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_sync.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_sync.py deleted file mode 100644 index 644d7b6f2049..000000000000 --- a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetOccurrence -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_GetOccurrence_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 grafeas import grafeas_v1 - - -def sample_get_occurrence(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.GetOccurrenceRequest( - name="name_value", - ) - - # Make the request - response = client.get_occurrence(request=request) - - # Handle the response - print(response) - -# [END containeranalysis_v1_generated_Grafeas_GetOccurrence_sync] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_note_occurrences_async.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_note_occurrences_async.py deleted file mode 100644 index ea4829680ae4..000000000000 --- a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_note_occurrences_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListNoteOccurrences -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_ListNoteOccurrences_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 grafeas import grafeas_v1 - - -async def sample_list_note_occurrences(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.ListNoteOccurrencesRequest( - name="name_value", - ) - - # Make the request - page_result = client.list_note_occurrences(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END containeranalysis_v1_generated_Grafeas_ListNoteOccurrences_async] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_note_occurrences_sync.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_note_occurrences_sync.py deleted file mode 100644 index 789dcba080e8..000000000000 --- a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_note_occurrences_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListNoteOccurrences -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_ListNoteOccurrences_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 grafeas import grafeas_v1 - - -def sample_list_note_occurrences(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.ListNoteOccurrencesRequest( - name="name_value", - ) - - # Make the request - page_result = client.list_note_occurrences(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END containeranalysis_v1_generated_Grafeas_ListNoteOccurrences_sync] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_notes_async.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_notes_async.py deleted file mode 100644 index 488eb4dad8aa..000000000000 --- a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_notes_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListNotes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_ListNotes_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 grafeas import grafeas_v1 - - -async def sample_list_notes(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.ListNotesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_notes(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END containeranalysis_v1_generated_Grafeas_ListNotes_async] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_notes_sync.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_notes_sync.py deleted file mode 100644 index d1ce09fe5d61..000000000000 --- a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_notes_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListNotes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_ListNotes_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 grafeas import grafeas_v1 - - -def sample_list_notes(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.ListNotesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_notes(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END containeranalysis_v1_generated_Grafeas_ListNotes_sync] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_occurrences_async.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_occurrences_async.py deleted file mode 100644 index 007d4ef85574..000000000000 --- a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_occurrences_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListOccurrences -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_ListOccurrences_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 grafeas import grafeas_v1 - - -async def sample_list_occurrences(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.ListOccurrencesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_occurrences(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END containeranalysis_v1_generated_Grafeas_ListOccurrences_async] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_occurrences_sync.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_occurrences_sync.py deleted file mode 100644 index d960929c9388..000000000000 --- a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_occurrences_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListOccurrences -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_ListOccurrences_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 grafeas import grafeas_v1 - - -def sample_list_occurrences(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.ListOccurrencesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_occurrences(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END containeranalysis_v1_generated_Grafeas_ListOccurrences_sync] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_note_async.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_note_async.py deleted file mode 100644 index 5a15196348e3..000000000000 --- a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_note_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateNote -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_UpdateNote_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 grafeas import grafeas_v1 - - -async def sample_update_note(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.UpdateNoteRequest( - name="name_value", - ) - - # Make the request - response = await client.update_note(request=request) - - # Handle the response - print(response) - -# [END containeranalysis_v1_generated_Grafeas_UpdateNote_async] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_note_sync.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_note_sync.py deleted file mode 100644 index ea0db334ebc1..000000000000 --- a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_note_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateNote -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_UpdateNote_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 grafeas import grafeas_v1 - - -def sample_update_note(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.UpdateNoteRequest( - name="name_value", - ) - - # Make the request - response = client.update_note(request=request) - - # Handle the response - print(response) - -# [END containeranalysis_v1_generated_Grafeas_UpdateNote_sync] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_occurrence_async.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_occurrence_async.py deleted file mode 100644 index 38d13497f807..000000000000 --- a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_occurrence_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateOccurrence -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_UpdateOccurrence_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 grafeas import grafeas_v1 - - -async def sample_update_occurrence(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.UpdateOccurrenceRequest( - name="name_value", - ) - - # Make the request - response = await client.update_occurrence(request=request) - - # Handle the response - print(response) - -# [END containeranalysis_v1_generated_Grafeas_UpdateOccurrence_async] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_occurrence_sync.py b/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_occurrence_sync.py deleted file mode 100644 index af456757fbb8..000000000000 --- a/owl-bot-staging/grafeas/v1/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_occurrence_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateOccurrence -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_UpdateOccurrence_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 grafeas import grafeas_v1 - - -def sample_update_occurrence(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.UpdateOccurrenceRequest( - name="name_value", - ) - - # Make the request - response = client.update_occurrence(request=request) - - # Handle the response - print(response) - -# [END containeranalysis_v1_generated_Grafeas_UpdateOccurrence_sync] diff --git a/owl-bot-staging/grafeas/v1/samples/generated_samples/snippet_metadata_grafeas.v1.json b/owl-bot-staging/grafeas/v1/samples/generated_samples/snippet_metadata_grafeas.v1.json deleted file mode 100644 index 290215d3171d..000000000000 --- a/owl-bot-staging/grafeas/v1/samples/generated_samples/snippet_metadata_grafeas.v1.json +++ /dev/null @@ -1,2353 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "grafeas.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "grafeas", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", - "shortName": "GrafeasAsyncClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.batch_create_notes", - "method": { - "fullName": "grafeas.v1.Grafeas.BatchCreateNotes", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "BatchCreateNotes" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.BatchCreateNotesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "notes", - "type": "MutableMapping[str, grafeas.grafeas_v1.types.Note]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "grafeas.grafeas_v1.types.BatchCreateNotesResponse", - "shortName": "batch_create_notes" - }, - "description": "Sample for BatchCreateNotes", - "file": "containeranalysis_v1_generated_grafeas_batch_create_notes_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_BatchCreateNotes_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": "containeranalysis_v1_generated_grafeas_batch_create_notes_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasClient", - "shortName": "GrafeasClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasClient.batch_create_notes", - "method": { - "fullName": "grafeas.v1.Grafeas.BatchCreateNotes", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "BatchCreateNotes" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.BatchCreateNotesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "notes", - "type": "MutableMapping[str, grafeas.grafeas_v1.types.Note]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "grafeas.grafeas_v1.types.BatchCreateNotesResponse", - "shortName": "batch_create_notes" - }, - "description": "Sample for BatchCreateNotes", - "file": "containeranalysis_v1_generated_grafeas_batch_create_notes_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_BatchCreateNotes_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": "containeranalysis_v1_generated_grafeas_batch_create_notes_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", - "shortName": "GrafeasAsyncClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.batch_create_occurrences", - "method": { - "fullName": "grafeas.v1.Grafeas.BatchCreateOccurrences", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "BatchCreateOccurrences" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.BatchCreateOccurrencesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "occurrences", - "type": "MutableSequence[grafeas.grafeas_v1.types.Occurrence]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "grafeas.grafeas_v1.types.BatchCreateOccurrencesResponse", - "shortName": "batch_create_occurrences" - }, - "description": "Sample for BatchCreateOccurrences", - "file": "containeranalysis_v1_generated_grafeas_batch_create_occurrences_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_BatchCreateOccurrences_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": "containeranalysis_v1_generated_grafeas_batch_create_occurrences_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasClient", - "shortName": "GrafeasClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasClient.batch_create_occurrences", - "method": { - "fullName": "grafeas.v1.Grafeas.BatchCreateOccurrences", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "BatchCreateOccurrences" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.BatchCreateOccurrencesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "occurrences", - "type": "MutableSequence[grafeas.grafeas_v1.types.Occurrence]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "grafeas.grafeas_v1.types.BatchCreateOccurrencesResponse", - "shortName": "batch_create_occurrences" - }, - "description": "Sample for BatchCreateOccurrences", - "file": "containeranalysis_v1_generated_grafeas_batch_create_occurrences_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_BatchCreateOccurrences_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": "containeranalysis_v1_generated_grafeas_batch_create_occurrences_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", - "shortName": "GrafeasAsyncClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.create_note", - "method": { - "fullName": "grafeas.v1.Grafeas.CreateNote", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "CreateNote" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.CreateNoteRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "note_id", - "type": "str" - }, - { - "name": "note", - "type": "grafeas.grafeas_v1.types.Note" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "grafeas.grafeas_v1.types.Note", - "shortName": "create_note" - }, - "description": "Sample for CreateNote", - "file": "containeranalysis_v1_generated_grafeas_create_note_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_CreateNote_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": "containeranalysis_v1_generated_grafeas_create_note_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasClient", - "shortName": "GrafeasClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasClient.create_note", - "method": { - "fullName": "grafeas.v1.Grafeas.CreateNote", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "CreateNote" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.CreateNoteRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "note_id", - "type": "str" - }, - { - "name": "note", - "type": "grafeas.grafeas_v1.types.Note" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "grafeas.grafeas_v1.types.Note", - "shortName": "create_note" - }, - "description": "Sample for CreateNote", - "file": "containeranalysis_v1_generated_grafeas_create_note_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_CreateNote_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": "containeranalysis_v1_generated_grafeas_create_note_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", - "shortName": "GrafeasAsyncClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.create_occurrence", - "method": { - "fullName": "grafeas.v1.Grafeas.CreateOccurrence", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "CreateOccurrence" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.CreateOccurrenceRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "occurrence", - "type": "grafeas.grafeas_v1.types.Occurrence" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "grafeas.grafeas_v1.types.Occurrence", - "shortName": "create_occurrence" - }, - "description": "Sample for CreateOccurrence", - "file": "containeranalysis_v1_generated_grafeas_create_occurrence_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_CreateOccurrence_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": "containeranalysis_v1_generated_grafeas_create_occurrence_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasClient", - "shortName": "GrafeasClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasClient.create_occurrence", - "method": { - "fullName": "grafeas.v1.Grafeas.CreateOccurrence", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "CreateOccurrence" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.CreateOccurrenceRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "occurrence", - "type": "grafeas.grafeas_v1.types.Occurrence" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "grafeas.grafeas_v1.types.Occurrence", - "shortName": "create_occurrence" - }, - "description": "Sample for CreateOccurrence", - "file": "containeranalysis_v1_generated_grafeas_create_occurrence_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_CreateOccurrence_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": "containeranalysis_v1_generated_grafeas_create_occurrence_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", - "shortName": "GrafeasAsyncClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.delete_note", - "method": { - "fullName": "grafeas.v1.Grafeas.DeleteNote", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "DeleteNote" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.DeleteNoteRequest" - }, - { - "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_note" - }, - "description": "Sample for DeleteNote", - "file": "containeranalysis_v1_generated_grafeas_delete_note_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_DeleteNote_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": "containeranalysis_v1_generated_grafeas_delete_note_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasClient", - "shortName": "GrafeasClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasClient.delete_note", - "method": { - "fullName": "grafeas.v1.Grafeas.DeleteNote", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "DeleteNote" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.DeleteNoteRequest" - }, - { - "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_note" - }, - "description": "Sample for DeleteNote", - "file": "containeranalysis_v1_generated_grafeas_delete_note_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_DeleteNote_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": "containeranalysis_v1_generated_grafeas_delete_note_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", - "shortName": "GrafeasAsyncClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.delete_occurrence", - "method": { - "fullName": "grafeas.v1.Grafeas.DeleteOccurrence", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "DeleteOccurrence" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.DeleteOccurrenceRequest" - }, - { - "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_occurrence" - }, - "description": "Sample for DeleteOccurrence", - "file": "containeranalysis_v1_generated_grafeas_delete_occurrence_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_DeleteOccurrence_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": "containeranalysis_v1_generated_grafeas_delete_occurrence_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasClient", - "shortName": "GrafeasClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasClient.delete_occurrence", - "method": { - "fullName": "grafeas.v1.Grafeas.DeleteOccurrence", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "DeleteOccurrence" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.DeleteOccurrenceRequest" - }, - { - "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_occurrence" - }, - "description": "Sample for DeleteOccurrence", - "file": "containeranalysis_v1_generated_grafeas_delete_occurrence_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_DeleteOccurrence_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": "containeranalysis_v1_generated_grafeas_delete_occurrence_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", - "shortName": "GrafeasAsyncClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.get_note", - "method": { - "fullName": "grafeas.v1.Grafeas.GetNote", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "GetNote" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.GetNoteRequest" - }, - { - "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": "grafeas.grafeas_v1.types.Note", - "shortName": "get_note" - }, - "description": "Sample for GetNote", - "file": "containeranalysis_v1_generated_grafeas_get_note_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_GetNote_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": "containeranalysis_v1_generated_grafeas_get_note_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasClient", - "shortName": "GrafeasClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasClient.get_note", - "method": { - "fullName": "grafeas.v1.Grafeas.GetNote", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "GetNote" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.GetNoteRequest" - }, - { - "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": "grafeas.grafeas_v1.types.Note", - "shortName": "get_note" - }, - "description": "Sample for GetNote", - "file": "containeranalysis_v1_generated_grafeas_get_note_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_GetNote_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": "containeranalysis_v1_generated_grafeas_get_note_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", - "shortName": "GrafeasAsyncClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.get_occurrence_note", - "method": { - "fullName": "grafeas.v1.Grafeas.GetOccurrenceNote", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "GetOccurrenceNote" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.GetOccurrenceNoteRequest" - }, - { - "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": "grafeas.grafeas_v1.types.Note", - "shortName": "get_occurrence_note" - }, - "description": "Sample for GetOccurrenceNote", - "file": "containeranalysis_v1_generated_grafeas_get_occurrence_note_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_GetOccurrenceNote_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": "containeranalysis_v1_generated_grafeas_get_occurrence_note_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasClient", - "shortName": "GrafeasClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasClient.get_occurrence_note", - "method": { - "fullName": "grafeas.v1.Grafeas.GetOccurrenceNote", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "GetOccurrenceNote" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.GetOccurrenceNoteRequest" - }, - { - "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": "grafeas.grafeas_v1.types.Note", - "shortName": "get_occurrence_note" - }, - "description": "Sample for GetOccurrenceNote", - "file": "containeranalysis_v1_generated_grafeas_get_occurrence_note_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_GetOccurrenceNote_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": "containeranalysis_v1_generated_grafeas_get_occurrence_note_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", - "shortName": "GrafeasAsyncClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.get_occurrence", - "method": { - "fullName": "grafeas.v1.Grafeas.GetOccurrence", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "GetOccurrence" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.GetOccurrenceRequest" - }, - { - "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": "grafeas.grafeas_v1.types.Occurrence", - "shortName": "get_occurrence" - }, - "description": "Sample for GetOccurrence", - "file": "containeranalysis_v1_generated_grafeas_get_occurrence_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_GetOccurrence_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": "containeranalysis_v1_generated_grafeas_get_occurrence_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasClient", - "shortName": "GrafeasClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasClient.get_occurrence", - "method": { - "fullName": "grafeas.v1.Grafeas.GetOccurrence", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "GetOccurrence" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.GetOccurrenceRequest" - }, - { - "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": "grafeas.grafeas_v1.types.Occurrence", - "shortName": "get_occurrence" - }, - "description": "Sample for GetOccurrence", - "file": "containeranalysis_v1_generated_grafeas_get_occurrence_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_GetOccurrence_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": "containeranalysis_v1_generated_grafeas_get_occurrence_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", - "shortName": "GrafeasAsyncClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.list_note_occurrences", - "method": { - "fullName": "grafeas.v1.Grafeas.ListNoteOccurrences", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "ListNoteOccurrences" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.ListNoteOccurrencesRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "filter", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "grafeas.grafeas_v1.services.grafeas.pagers.ListNoteOccurrencesAsyncPager", - "shortName": "list_note_occurrences" - }, - "description": "Sample for ListNoteOccurrences", - "file": "containeranalysis_v1_generated_grafeas_list_note_occurrences_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_ListNoteOccurrences_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": "containeranalysis_v1_generated_grafeas_list_note_occurrences_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasClient", - "shortName": "GrafeasClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasClient.list_note_occurrences", - "method": { - "fullName": "grafeas.v1.Grafeas.ListNoteOccurrences", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "ListNoteOccurrences" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.ListNoteOccurrencesRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "filter", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "grafeas.grafeas_v1.services.grafeas.pagers.ListNoteOccurrencesPager", - "shortName": "list_note_occurrences" - }, - "description": "Sample for ListNoteOccurrences", - "file": "containeranalysis_v1_generated_grafeas_list_note_occurrences_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_ListNoteOccurrences_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": "containeranalysis_v1_generated_grafeas_list_note_occurrences_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", - "shortName": "GrafeasAsyncClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.list_notes", - "method": { - "fullName": "grafeas.v1.Grafeas.ListNotes", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "ListNotes" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.ListNotesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "filter", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "grafeas.grafeas_v1.services.grafeas.pagers.ListNotesAsyncPager", - "shortName": "list_notes" - }, - "description": "Sample for ListNotes", - "file": "containeranalysis_v1_generated_grafeas_list_notes_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_ListNotes_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": "containeranalysis_v1_generated_grafeas_list_notes_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasClient", - "shortName": "GrafeasClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasClient.list_notes", - "method": { - "fullName": "grafeas.v1.Grafeas.ListNotes", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "ListNotes" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.ListNotesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "filter", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "grafeas.grafeas_v1.services.grafeas.pagers.ListNotesPager", - "shortName": "list_notes" - }, - "description": "Sample for ListNotes", - "file": "containeranalysis_v1_generated_grafeas_list_notes_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_ListNotes_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": "containeranalysis_v1_generated_grafeas_list_notes_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", - "shortName": "GrafeasAsyncClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.list_occurrences", - "method": { - "fullName": "grafeas.v1.Grafeas.ListOccurrences", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "ListOccurrences" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.ListOccurrencesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "filter", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "grafeas.grafeas_v1.services.grafeas.pagers.ListOccurrencesAsyncPager", - "shortName": "list_occurrences" - }, - "description": "Sample for ListOccurrences", - "file": "containeranalysis_v1_generated_grafeas_list_occurrences_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_ListOccurrences_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": "containeranalysis_v1_generated_grafeas_list_occurrences_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasClient", - "shortName": "GrafeasClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasClient.list_occurrences", - "method": { - "fullName": "grafeas.v1.Grafeas.ListOccurrences", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "ListOccurrences" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.ListOccurrencesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "filter", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "grafeas.grafeas_v1.services.grafeas.pagers.ListOccurrencesPager", - "shortName": "list_occurrences" - }, - "description": "Sample for ListOccurrences", - "file": "containeranalysis_v1_generated_grafeas_list_occurrences_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_ListOccurrences_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": "containeranalysis_v1_generated_grafeas_list_occurrences_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", - "shortName": "GrafeasAsyncClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.update_note", - "method": { - "fullName": "grafeas.v1.Grafeas.UpdateNote", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "UpdateNote" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.UpdateNoteRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "note", - "type": "grafeas.grafeas_v1.types.Note" - }, - { - "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": "grafeas.grafeas_v1.types.Note", - "shortName": "update_note" - }, - "description": "Sample for UpdateNote", - "file": "containeranalysis_v1_generated_grafeas_update_note_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_UpdateNote_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": "containeranalysis_v1_generated_grafeas_update_note_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasClient", - "shortName": "GrafeasClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasClient.update_note", - "method": { - "fullName": "grafeas.v1.Grafeas.UpdateNote", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "UpdateNote" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.UpdateNoteRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "note", - "type": "grafeas.grafeas_v1.types.Note" - }, - { - "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": "grafeas.grafeas_v1.types.Note", - "shortName": "update_note" - }, - "description": "Sample for UpdateNote", - "file": "containeranalysis_v1_generated_grafeas_update_note_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_UpdateNote_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": "containeranalysis_v1_generated_grafeas_update_note_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", - "shortName": "GrafeasAsyncClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.update_occurrence", - "method": { - "fullName": "grafeas.v1.Grafeas.UpdateOccurrence", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "UpdateOccurrence" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.UpdateOccurrenceRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "occurrence", - "type": "grafeas.grafeas_v1.types.Occurrence" - }, - { - "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": "grafeas.grafeas_v1.types.Occurrence", - "shortName": "update_occurrence" - }, - "description": "Sample for UpdateOccurrence", - "file": "containeranalysis_v1_generated_grafeas_update_occurrence_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_UpdateOccurrence_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": "containeranalysis_v1_generated_grafeas_update_occurrence_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasClient", - "shortName": "GrafeasClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasClient.update_occurrence", - "method": { - "fullName": "grafeas.v1.Grafeas.UpdateOccurrence", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "UpdateOccurrence" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.UpdateOccurrenceRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "occurrence", - "type": "grafeas.grafeas_v1.types.Occurrence" - }, - { - "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": "grafeas.grafeas_v1.types.Occurrence", - "shortName": "update_occurrence" - }, - "description": "Sample for UpdateOccurrence", - "file": "containeranalysis_v1_generated_grafeas_update_occurrence_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_UpdateOccurrence_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": "containeranalysis_v1_generated_grafeas_update_occurrence_sync.py" - } - ] -} diff --git a/owl-bot-staging/grafeas/v1/scripts/fixup_grafeas_v1_keywords.py b/owl-bot-staging/grafeas/v1/scripts/fixup_grafeas_v1_keywords.py deleted file mode 100644 index 78bae6683cc8..000000000000 --- a/owl-bot-staging/grafeas/v1/scripts/fixup_grafeas_v1_keywords.py +++ /dev/null @@ -1,189 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 grafeasCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'batch_create_notes': ('parent', 'notes', ), - 'batch_create_occurrences': ('parent', 'occurrences', ), - 'create_note': ('parent', 'note_id', 'note', ), - 'create_occurrence': ('parent', 'occurrence', ), - 'delete_note': ('name', ), - 'delete_occurrence': ('name', ), - 'get_note': ('name', ), - 'get_occurrence': ('name', ), - 'get_occurrence_note': ('name', ), - 'list_note_occurrences': ('name', 'filter', 'page_size', 'page_token', ), - 'list_notes': ('parent', 'filter', 'page_size', 'page_token', ), - 'list_occurrences': ('parent', 'filter', 'page_size', 'page_token', ), - 'update_note': ('name', 'note', 'update_mask', ), - 'update_occurrence': ('name', 'occurrence', '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=grafeasCallTransformer(), -): - """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 grafeas 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/grafeas/v1/setup.py b/owl-bot-staging/grafeas/v1/setup.py deleted file mode 100644 index 42545da2ab4f..000000000000 --- a/owl-bot-staging/grafeas/v1/setup.py +++ /dev/null @@ -1,98 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 = 'grafeas' - - -description = "Grafeas API client library" - -version = None - -with open(os.path.join(package_root, 'grafeas/grafeas/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.0dev,!=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.0dev,!=2.24.0,!=2.25.0", - "proto-plus >= 1.22.3, <2.0.0dev", - "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'", - "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", -] -extras = { -} -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/grafeas" - -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("grafeas") -] - -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/grafeas/v1/testing/constraints-3.10.txt b/owl-bot-staging/grafeas/v1/testing/constraints-3.10.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/grafeas/v1/testing/constraints-3.10.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/grafeas/v1/testing/constraints-3.11.txt b/owl-bot-staging/grafeas/v1/testing/constraints-3.11.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/grafeas/v1/testing/constraints-3.11.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/grafeas/v1/testing/constraints-3.12.txt b/owl-bot-staging/grafeas/v1/testing/constraints-3.12.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/grafeas/v1/testing/constraints-3.12.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/grafeas/v1/testing/constraints-3.13.txt b/owl-bot-staging/grafeas/v1/testing/constraints-3.13.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/grafeas/v1/testing/constraints-3.13.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/grafeas/v1/testing/constraints-3.7.txt b/owl-bot-staging/grafeas/v1/testing/constraints-3.7.txt deleted file mode 100644 index fc812592b0ee..000000000000 --- a/owl-bot-staging/grafeas/v1/testing/constraints-3.7.txt +++ /dev/null @@ -1,10 +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.0dev", -# 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 diff --git a/owl-bot-staging/grafeas/v1/testing/constraints-3.8.txt b/owl-bot-staging/grafeas/v1/testing/constraints-3.8.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/grafeas/v1/testing/constraints-3.8.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/grafeas/v1/testing/constraints-3.9.txt b/owl-bot-staging/grafeas/v1/testing/constraints-3.9.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/grafeas/v1/testing/constraints-3.9.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/grafeas/v1/tests/__init__.py b/owl-bot-staging/grafeas/v1/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/grafeas/v1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/grafeas/v1/tests/unit/__init__.py b/owl-bot-staging/grafeas/v1/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/grafeas/v1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/grafeas/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/grafeas/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/grafeas/v1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/grafeas/v1/tests/unit/gapic/grafeas_v1/__init__.py b/owl-bot-staging/grafeas/v1/tests/unit/gapic/grafeas_v1/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/grafeas/v1/tests/unit/gapic/grafeas_v1/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/grafeas/v1/tests/unit/gapic/grafeas_v1/test_grafeas.py b/owl-bot-staging/grafeas/v1/tests/unit/gapic/grafeas_v1/test_grafeas.py deleted file mode 100644 index d227ae4d2f80..000000000000 --- a/owl-bot-staging/grafeas/v1/tests/unit/gapic/grafeas_v1/test_grafeas.py +++ /dev/null @@ -1,11993 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 any_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from grafeas.grafeas_v1.services.grafeas import GrafeasAsyncClient -from grafeas.grafeas_v1.services.grafeas import GrafeasClient -from grafeas.grafeas_v1.services.grafeas import pagers -from grafeas.grafeas_v1.services.grafeas import transports -from grafeas.grafeas_v1.types import attestation -from grafeas.grafeas_v1.types import build -from grafeas.grafeas_v1.types import common -from grafeas.grafeas_v1.types import compliance -from grafeas.grafeas_v1.types import cvss -from grafeas.grafeas_v1.types import deployment -from grafeas.grafeas_v1.types import discovery -from grafeas.grafeas_v1.types import dsse_attestation -from grafeas.grafeas_v1.types import grafeas -from grafeas.grafeas_v1.types import image -from grafeas.grafeas_v1.types import intoto_provenance -from grafeas.grafeas_v1.types import intoto_statement -from grafeas.grafeas_v1.types import package -from grafeas.grafeas_v1.types import provenance -from grafeas.grafeas_v1.types import sbom -from grafeas.grafeas_v1.types import severity -from grafeas.grafeas_v1.types import slsa_provenance -from grafeas.grafeas_v1.types import slsa_provenance_zero_two -from grafeas.grafeas_v1.types import upgrade -from grafeas.grafeas_v1.types import vex -from grafeas.grafeas_v1.types import vulnerability -import google.auth - - -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 GrafeasClient._get_default_mtls_endpoint(None) is None - assert GrafeasClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert GrafeasClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert GrafeasClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert GrafeasClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert GrafeasClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert GrafeasClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert GrafeasClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert GrafeasClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - GrafeasClient._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 GrafeasClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert GrafeasClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert GrafeasClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - GrafeasClient._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 GrafeasClient._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 GrafeasClient._get_client_cert_source(None, False) is None - assert GrafeasClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert GrafeasClient._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 GrafeasClient._get_client_cert_source(None, True) is mock_default_cert_source - assert GrafeasClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(GrafeasClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GrafeasClient)) -@mock.patch.object(GrafeasAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GrafeasAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = GrafeasClient._DEFAULT_UNIVERSE - default_endpoint = GrafeasClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = GrafeasClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert GrafeasClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert GrafeasClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == GrafeasClient.DEFAULT_MTLS_ENDPOINT - assert GrafeasClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert GrafeasClient._get_api_endpoint(None, None, default_universe, "always") == GrafeasClient.DEFAULT_MTLS_ENDPOINT - assert GrafeasClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == GrafeasClient.DEFAULT_MTLS_ENDPOINT - assert GrafeasClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert GrafeasClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - GrafeasClient._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 GrafeasClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert GrafeasClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert GrafeasClient._get_universe_domain(None, None) == GrafeasClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - GrafeasClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - - -@pytest.mark.parametrize("client_class,transport_name", [ - (GrafeasClient, "grpc"), - (GrafeasAsyncClient, "grpc_asyncio"), - (GrafeasClient, "rest"), -]) -def test_grafeas_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 == ( - 'containeranalysis.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://containeranalysis.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.GrafeasGrpcTransport, "grpc"), - (transports.GrafeasGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.GrafeasRestTransport, "rest"), -]) -def test_grafeas_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", [ - (GrafeasClient, "grpc"), - (GrafeasAsyncClient, "grpc_asyncio"), - (GrafeasClient, "rest"), -]) -def test_grafeas_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 == ( - 'containeranalysis.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://containeranalysis.googleapis.com' - ) - - -def test_grafeas_client_get_transport_class(): - transport = GrafeasClient.get_transport_class() - available_transports = [ - transports.GrafeasGrpcTransport, - transports.GrafeasRestTransport, - ] - assert transport in available_transports - - transport = GrafeasClient.get_transport_class("grpc") - assert transport == transports.GrafeasGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (GrafeasClient, transports.GrafeasGrpcTransport, "grpc"), - (GrafeasAsyncClient, transports.GrafeasGrpcAsyncIOTransport, "grpc_asyncio"), - (GrafeasClient, transports.GrafeasRestTransport, "rest"), -]) -@mock.patch.object(GrafeasClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GrafeasClient)) -@mock.patch.object(GrafeasAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GrafeasAsyncClient)) -def test_grafeas_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(GrafeasClient, '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(GrafeasClient, '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", [ - (GrafeasClient, transports.GrafeasGrpcTransport, "grpc", "true"), - (GrafeasAsyncClient, transports.GrafeasGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (GrafeasClient, transports.GrafeasGrpcTransport, "grpc", "false"), - (GrafeasAsyncClient, transports.GrafeasGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (GrafeasClient, transports.GrafeasRestTransport, "rest", "true"), - (GrafeasClient, transports.GrafeasRestTransport, "rest", "false"), -]) -@mock.patch.object(GrafeasClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GrafeasClient)) -@mock.patch.object(GrafeasAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GrafeasAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_grafeas_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", [ - GrafeasClient, GrafeasAsyncClient -]) -@mock.patch.object(GrafeasClient, "DEFAULT_ENDPOINT", modify_default_endpoint(GrafeasClient)) -@mock.patch.object(GrafeasAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(GrafeasAsyncClient)) -def test_grafeas_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", [ - GrafeasClient, GrafeasAsyncClient -]) -@mock.patch.object(GrafeasClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GrafeasClient)) -@mock.patch.object(GrafeasAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GrafeasAsyncClient)) -def test_grafeas_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = GrafeasClient._DEFAULT_UNIVERSE - default_endpoint = GrafeasClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = GrafeasClient._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", [ - (GrafeasClient, transports.GrafeasGrpcTransport, "grpc"), - (GrafeasAsyncClient, transports.GrafeasGrpcAsyncIOTransport, "grpc_asyncio"), - (GrafeasClient, transports.GrafeasRestTransport, "rest"), -]) -def test_grafeas_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", [ - (GrafeasClient, transports.GrafeasGrpcTransport, "grpc", grpc_helpers), - (GrafeasAsyncClient, transports.GrafeasGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (GrafeasClient, transports.GrafeasRestTransport, "rest", None), -]) -def test_grafeas_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_grafeas_client_client_options_from_dict(): - with mock.patch('grafeas.grafeas_v1.services.grafeas.transports.GrafeasGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = GrafeasClient( - 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", [ - (GrafeasClient, transports.GrafeasGrpcTransport, "grpc", grpc_helpers), - (GrafeasAsyncClient, transports.GrafeasGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_grafeas_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( - "containeranalysis.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( -), - scopes=None, - default_host="containeranalysis.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - grafeas.GetOccurrenceRequest, - dict, -]) -def test_get_occurrence(request_type, transport: str = 'grpc'): - client = GrafeasClient( - 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_occurrence), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Occurrence( - name='name_value', - resource_uri='resource_uri_value', - note_name='note_name_value', - kind=common.NoteKind.VULNERABILITY, - remediation='remediation_value', - ) - response = client.get_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = grafeas.GetOccurrenceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Occurrence) - assert response.name == 'name_value' - assert response.resource_uri == 'resource_uri_value' - assert response.note_name == 'note_name_value' - assert response.kind == common.NoteKind.VULNERABILITY - assert response.remediation == 'remediation_value' - - -def test_get_occurrence_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 = GrafeasClient( - 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 = grafeas.GetOccurrenceRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_occurrence), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_occurrence(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.GetOccurrenceRequest( - name='name_value', - ) - -def test_get_occurrence_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GrafeasClient( - 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_occurrence in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_occurrence] = mock_rpc - request = {} - client.get_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_occurrence(request) - - # Establish that a new wrapper 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_occurrence_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = GrafeasAsyncClient( - 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_occurrence in client._client._transport._wrapped_methods - - # 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_occurrence] = mock_rpc - - request = {} - await client.get_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_occurrence(request) - - # Establish that a new wrapper 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_occurrence_async(transport: str = 'grpc_asyncio', request_type=grafeas.GetOccurrenceRequest): - client = GrafeasAsyncClient( - 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_occurrence), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence( - name='name_value', - resource_uri='resource_uri_value', - note_name='note_name_value', - kind=common.NoteKind.VULNERABILITY, - remediation='remediation_value', - )) - response = await client.get_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = grafeas.GetOccurrenceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Occurrence) - assert response.name == 'name_value' - assert response.resource_uri == 'resource_uri_value' - assert response.note_name == 'note_name_value' - assert response.kind == common.NoteKind.VULNERABILITY - assert response.remediation == 'remediation_value' - - -@pytest.mark.asyncio -async def test_get_occurrence_async_from_dict(): - await test_get_occurrence_async(request_type=dict) - -def test_get_occurrence_field_headers(): - client = GrafeasClient( - 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 = grafeas.GetOccurrenceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_occurrence), - '__call__') as call: - call.return_value = grafeas.Occurrence() - client.get_occurrence(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_occurrence_field_headers_async(): - client = GrafeasAsyncClient( - 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 = grafeas.GetOccurrenceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_occurrence), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence()) - await client.get_occurrence(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_occurrence_flattened(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_occurrence), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Occurrence() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_occurrence( - 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_occurrence_flattened_error(): - client = GrafeasClient( - 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_occurrence( - grafeas.GetOccurrenceRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_occurrence_flattened_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_occurrence), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Occurrence() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_occurrence( - 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_occurrence_flattened_error_async(): - client = GrafeasAsyncClient( - 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_occurrence( - grafeas.GetOccurrenceRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - grafeas.ListOccurrencesRequest, - dict, -]) -def test_list_occurrences(request_type, transport: str = 'grpc'): - client = GrafeasClient( - 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_occurrences), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.ListOccurrencesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_occurrences(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = grafeas.ListOccurrencesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListOccurrencesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_occurrences_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 = GrafeasClient( - 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 = grafeas.ListOccurrencesRequest( - parent='parent_value', - filter='filter_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_occurrences), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_occurrences(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.ListOccurrencesRequest( - parent='parent_value', - filter='filter_value', - page_token='page_token_value', - ) - -def test_list_occurrences_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GrafeasClient( - 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_occurrences in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_occurrences] = mock_rpc - request = {} - client.list_occurrences(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_occurrences(request) - - # Establish that a new wrapper 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_occurrences_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = GrafeasAsyncClient( - 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_occurrences in client._client._transport._wrapped_methods - - # 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_occurrences] = mock_rpc - - request = {} - await client.list_occurrences(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_occurrences(request) - - # Establish that a new wrapper 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_occurrences_async(transport: str = 'grpc_asyncio', request_type=grafeas.ListOccurrencesRequest): - client = GrafeasAsyncClient( - 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_occurrences), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.ListOccurrencesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_occurrences(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = grafeas.ListOccurrencesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListOccurrencesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_occurrences_async_from_dict(): - await test_list_occurrences_async(request_type=dict) - -def test_list_occurrences_field_headers(): - client = GrafeasClient( - 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 = grafeas.ListOccurrencesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_occurrences), - '__call__') as call: - call.return_value = grafeas.ListOccurrencesResponse() - client.list_occurrences(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_occurrences_field_headers_async(): - client = GrafeasAsyncClient( - 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 = grafeas.ListOccurrencesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_occurrences), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.ListOccurrencesResponse()) - await client.list_occurrences(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_occurrences_flattened(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_occurrences), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.ListOccurrencesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_occurrences( - parent='parent_value', - filter='filter_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].filter - mock_val = 'filter_value' - assert arg == mock_val - - -def test_list_occurrences_flattened_error(): - client = GrafeasClient( - 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_occurrences( - grafeas.ListOccurrencesRequest(), - parent='parent_value', - filter='filter_value', - ) - -@pytest.mark.asyncio -async def test_list_occurrences_flattened_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_occurrences), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.ListOccurrencesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.ListOccurrencesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_occurrences( - parent='parent_value', - filter='filter_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].filter - mock_val = 'filter_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_occurrences_flattened_error_async(): - client = GrafeasAsyncClient( - 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_occurrences( - grafeas.ListOccurrencesRequest(), - parent='parent_value', - filter='filter_value', - ) - - -def test_list_occurrences_pager(transport_name: str = "grpc"): - client = GrafeasClient( - 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_occurrences), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - grafeas.ListOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - next_page_token='abc', - ), - grafeas.ListOccurrencesResponse( - occurrences=[], - next_page_token='def', - ), - grafeas.ListOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - ], - next_page_token='ghi', - ), - grafeas.ListOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_occurrences(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, grafeas.Occurrence) - for i in results) -def test_list_occurrences_pages(transport_name: str = "grpc"): - client = GrafeasClient( - 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_occurrences), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - grafeas.ListOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - next_page_token='abc', - ), - grafeas.ListOccurrencesResponse( - occurrences=[], - next_page_token='def', - ), - grafeas.ListOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - ], - next_page_token='ghi', - ), - grafeas.ListOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - ), - RuntimeError, - ) - pages = list(client.list_occurrences(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_occurrences_async_pager(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_occurrences), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - grafeas.ListOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - next_page_token='abc', - ), - grafeas.ListOccurrencesResponse( - occurrences=[], - next_page_token='def', - ), - grafeas.ListOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - ], - next_page_token='ghi', - ), - grafeas.ListOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_occurrences(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, grafeas.Occurrence) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_occurrences_async_pages(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_occurrences), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - grafeas.ListOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - next_page_token='abc', - ), - grafeas.ListOccurrencesResponse( - occurrences=[], - next_page_token='def', - ), - grafeas.ListOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - ], - next_page_token='ghi', - ), - grafeas.ListOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - ), - 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_occurrences(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", [ - grafeas.DeleteOccurrenceRequest, - dict, -]) -def test_delete_occurrence(request_type, transport: str = 'grpc'): - client = GrafeasClient( - 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_occurrence), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = grafeas.DeleteOccurrenceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_occurrence_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 = GrafeasClient( - 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 = grafeas.DeleteOccurrenceRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_occurrence), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_occurrence(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.DeleteOccurrenceRequest( - name='name_value', - ) - -def test_delete_occurrence_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GrafeasClient( - 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_occurrence in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_occurrence] = mock_rpc - request = {} - client.delete_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_occurrence(request) - - # Establish that a new wrapper 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_occurrence_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = GrafeasAsyncClient( - 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_occurrence in client._client._transport._wrapped_methods - - # 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_occurrence] = mock_rpc - - request = {} - await client.delete_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.delete_occurrence(request) - - # Establish that a new wrapper 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_occurrence_async(transport: str = 'grpc_asyncio', request_type=grafeas.DeleteOccurrenceRequest): - client = GrafeasAsyncClient( - 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_occurrence), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = grafeas.DeleteOccurrenceRequest() - 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_occurrence_async_from_dict(): - await test_delete_occurrence_async(request_type=dict) - -def test_delete_occurrence_field_headers(): - client = GrafeasClient( - 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 = grafeas.DeleteOccurrenceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_occurrence), - '__call__') as call: - call.return_value = None - client.delete_occurrence(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_occurrence_field_headers_async(): - client = GrafeasAsyncClient( - 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 = grafeas.DeleteOccurrenceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_occurrence), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_occurrence(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_occurrence_flattened(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_occurrence), - '__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_occurrence( - 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_occurrence_flattened_error(): - client = GrafeasClient( - 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_occurrence( - grafeas.DeleteOccurrenceRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_occurrence_flattened_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_occurrence), - '__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_occurrence( - 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_occurrence_flattened_error_async(): - client = GrafeasAsyncClient( - 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_occurrence( - grafeas.DeleteOccurrenceRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - grafeas.CreateOccurrenceRequest, - dict, -]) -def test_create_occurrence(request_type, transport: str = 'grpc'): - client = GrafeasClient( - 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_occurrence), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Occurrence( - name='name_value', - resource_uri='resource_uri_value', - note_name='note_name_value', - kind=common.NoteKind.VULNERABILITY, - remediation='remediation_value', - ) - response = client.create_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = grafeas.CreateOccurrenceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Occurrence) - assert response.name == 'name_value' - assert response.resource_uri == 'resource_uri_value' - assert response.note_name == 'note_name_value' - assert response.kind == common.NoteKind.VULNERABILITY - assert response.remediation == 'remediation_value' - - -def test_create_occurrence_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 = GrafeasClient( - 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 = grafeas.CreateOccurrenceRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_occurrence), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_occurrence(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.CreateOccurrenceRequest( - parent='parent_value', - ) - -def test_create_occurrence_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GrafeasClient( - 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_occurrence in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_occurrence] = mock_rpc - request = {} - client.create_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_occurrence(request) - - # Establish that a new wrapper 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_occurrence_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = GrafeasAsyncClient( - 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_occurrence in client._client._transport._wrapped_methods - - # 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_occurrence] = mock_rpc - - request = {} - await client.create_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.create_occurrence(request) - - # Establish that a new wrapper 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_occurrence_async(transport: str = 'grpc_asyncio', request_type=grafeas.CreateOccurrenceRequest): - client = GrafeasAsyncClient( - 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_occurrence), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence( - name='name_value', - resource_uri='resource_uri_value', - note_name='note_name_value', - kind=common.NoteKind.VULNERABILITY, - remediation='remediation_value', - )) - response = await client.create_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = grafeas.CreateOccurrenceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Occurrence) - assert response.name == 'name_value' - assert response.resource_uri == 'resource_uri_value' - assert response.note_name == 'note_name_value' - assert response.kind == common.NoteKind.VULNERABILITY - assert response.remediation == 'remediation_value' - - -@pytest.mark.asyncio -async def test_create_occurrence_async_from_dict(): - await test_create_occurrence_async(request_type=dict) - -def test_create_occurrence_field_headers(): - client = GrafeasClient( - 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 = grafeas.CreateOccurrenceRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_occurrence), - '__call__') as call: - call.return_value = grafeas.Occurrence() - client.create_occurrence(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_occurrence_field_headers_async(): - client = GrafeasAsyncClient( - 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 = grafeas.CreateOccurrenceRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_occurrence), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence()) - await client.create_occurrence(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_occurrence_flattened(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_occurrence), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Occurrence() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_occurrence( - parent='parent_value', - occurrence=grafeas.Occurrence(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].occurrence - mock_val = grafeas.Occurrence(name='name_value') - assert arg == mock_val - - -def test_create_occurrence_flattened_error(): - client = GrafeasClient( - 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_occurrence( - grafeas.CreateOccurrenceRequest(), - parent='parent_value', - occurrence=grafeas.Occurrence(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_occurrence_flattened_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_occurrence), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Occurrence() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_occurrence( - parent='parent_value', - occurrence=grafeas.Occurrence(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].occurrence - mock_val = grafeas.Occurrence(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_occurrence_flattened_error_async(): - client = GrafeasAsyncClient( - 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_occurrence( - grafeas.CreateOccurrenceRequest(), - parent='parent_value', - occurrence=grafeas.Occurrence(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - grafeas.BatchCreateOccurrencesRequest, - dict, -]) -def test_batch_create_occurrences(request_type, transport: str = 'grpc'): - client = GrafeasClient( - 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.batch_create_occurrences), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.BatchCreateOccurrencesResponse( - ) - response = client.batch_create_occurrences(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = grafeas.BatchCreateOccurrencesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.BatchCreateOccurrencesResponse) - - -def test_batch_create_occurrences_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 = GrafeasClient( - 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 = grafeas.BatchCreateOccurrencesRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_occurrences), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.batch_create_occurrences(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.BatchCreateOccurrencesRequest( - parent='parent_value', - ) - -def test_batch_create_occurrences_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GrafeasClient( - 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.batch_create_occurrences in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.batch_create_occurrences] = mock_rpc - request = {} - client.batch_create_occurrences(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.batch_create_occurrences(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_batch_create_occurrences_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = GrafeasAsyncClient( - 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.batch_create_occurrences in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.batch_create_occurrences] = mock_rpc - - request = {} - await client.batch_create_occurrences(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.batch_create_occurrences(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_batch_create_occurrences_async(transport: str = 'grpc_asyncio', request_type=grafeas.BatchCreateOccurrencesRequest): - client = GrafeasAsyncClient( - 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.batch_create_occurrences), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.BatchCreateOccurrencesResponse( - )) - response = await client.batch_create_occurrences(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = grafeas.BatchCreateOccurrencesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.BatchCreateOccurrencesResponse) - - -@pytest.mark.asyncio -async def test_batch_create_occurrences_async_from_dict(): - await test_batch_create_occurrences_async(request_type=dict) - -def test_batch_create_occurrences_field_headers(): - client = GrafeasClient( - 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 = grafeas.BatchCreateOccurrencesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_occurrences), - '__call__') as call: - call.return_value = grafeas.BatchCreateOccurrencesResponse() - client.batch_create_occurrences(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_batch_create_occurrences_field_headers_async(): - client = GrafeasAsyncClient( - 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 = grafeas.BatchCreateOccurrencesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_occurrences), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.BatchCreateOccurrencesResponse()) - await client.batch_create_occurrences(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_batch_create_occurrences_flattened(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_occurrences), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.BatchCreateOccurrencesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.batch_create_occurrences( - parent='parent_value', - occurrences=[grafeas.Occurrence(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].occurrences - mock_val = [grafeas.Occurrence(name='name_value')] - assert arg == mock_val - - -def test_batch_create_occurrences_flattened_error(): - client = GrafeasClient( - 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.batch_create_occurrences( - grafeas.BatchCreateOccurrencesRequest(), - parent='parent_value', - occurrences=[grafeas.Occurrence(name='name_value')], - ) - -@pytest.mark.asyncio -async def test_batch_create_occurrences_flattened_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_occurrences), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.BatchCreateOccurrencesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.BatchCreateOccurrencesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.batch_create_occurrences( - parent='parent_value', - occurrences=[grafeas.Occurrence(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].occurrences - mock_val = [grafeas.Occurrence(name='name_value')] - assert arg == mock_val - -@pytest.mark.asyncio -async def test_batch_create_occurrences_flattened_error_async(): - client = GrafeasAsyncClient( - 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.batch_create_occurrences( - grafeas.BatchCreateOccurrencesRequest(), - parent='parent_value', - occurrences=[grafeas.Occurrence(name='name_value')], - ) - - -@pytest.mark.parametrize("request_type", [ - grafeas.UpdateOccurrenceRequest, - dict, -]) -def test_update_occurrence(request_type, transport: str = 'grpc'): - client = GrafeasClient( - 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_occurrence), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Occurrence( - name='name_value', - resource_uri='resource_uri_value', - note_name='note_name_value', - kind=common.NoteKind.VULNERABILITY, - remediation='remediation_value', - ) - response = client.update_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = grafeas.UpdateOccurrenceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Occurrence) - assert response.name == 'name_value' - assert response.resource_uri == 'resource_uri_value' - assert response.note_name == 'note_name_value' - assert response.kind == common.NoteKind.VULNERABILITY - assert response.remediation == 'remediation_value' - - -def test_update_occurrence_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 = GrafeasClient( - 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 = grafeas.UpdateOccurrenceRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_occurrence), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_occurrence(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.UpdateOccurrenceRequest( - name='name_value', - ) - -def test_update_occurrence_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GrafeasClient( - 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_occurrence in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_occurrence] = mock_rpc - request = {} - client.update_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_occurrence(request) - - # Establish that a new wrapper 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_occurrence_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = GrafeasAsyncClient( - 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_occurrence in client._client._transport._wrapped_methods - - # 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_occurrence] = mock_rpc - - request = {} - await client.update_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_occurrence(request) - - # Establish that a new wrapper 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_occurrence_async(transport: str = 'grpc_asyncio', request_type=grafeas.UpdateOccurrenceRequest): - client = GrafeasAsyncClient( - 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_occurrence), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence( - name='name_value', - resource_uri='resource_uri_value', - note_name='note_name_value', - kind=common.NoteKind.VULNERABILITY, - remediation='remediation_value', - )) - response = await client.update_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = grafeas.UpdateOccurrenceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Occurrence) - assert response.name == 'name_value' - assert response.resource_uri == 'resource_uri_value' - assert response.note_name == 'note_name_value' - assert response.kind == common.NoteKind.VULNERABILITY - assert response.remediation == 'remediation_value' - - -@pytest.mark.asyncio -async def test_update_occurrence_async_from_dict(): - await test_update_occurrence_async(request_type=dict) - -def test_update_occurrence_field_headers(): - client = GrafeasClient( - 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 = grafeas.UpdateOccurrenceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_occurrence), - '__call__') as call: - call.return_value = grafeas.Occurrence() - client.update_occurrence(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_update_occurrence_field_headers_async(): - client = GrafeasAsyncClient( - 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 = grafeas.UpdateOccurrenceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_occurrence), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence()) - await client.update_occurrence(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_update_occurrence_flattened(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_occurrence), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Occurrence() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_occurrence( - name='name_value', - occurrence=grafeas.Occurrence(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].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].occurrence - mock_val = grafeas.Occurrence(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_occurrence_flattened_error(): - client = GrafeasClient( - 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_occurrence( - grafeas.UpdateOccurrenceRequest(), - name='name_value', - occurrence=grafeas.Occurrence(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_occurrence_flattened_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_occurrence), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Occurrence() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_occurrence( - name='name_value', - occurrence=grafeas.Occurrence(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].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].occurrence - mock_val = grafeas.Occurrence(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_occurrence_flattened_error_async(): - client = GrafeasAsyncClient( - 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_occurrence( - grafeas.UpdateOccurrenceRequest(), - name='name_value', - occurrence=grafeas.Occurrence(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - grafeas.GetOccurrenceNoteRequest, - dict, -]) -def test_get_occurrence_note(request_type, transport: str = 'grpc'): - client = GrafeasClient( - 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_occurrence_note), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Note( - name='name_value', - short_description='short_description_value', - long_description='long_description_value', - kind=common.NoteKind.VULNERABILITY, - related_note_names=['related_note_names_value'], - ) - response = client.get_occurrence_note(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = grafeas.GetOccurrenceNoteRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Note) - assert response.name == 'name_value' - assert response.short_description == 'short_description_value' - assert response.long_description == 'long_description_value' - assert response.kind == common.NoteKind.VULNERABILITY - assert response.related_note_names == ['related_note_names_value'] - - -def test_get_occurrence_note_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 = GrafeasClient( - 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 = grafeas.GetOccurrenceNoteRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_occurrence_note), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_occurrence_note(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.GetOccurrenceNoteRequest( - name='name_value', - ) - -def test_get_occurrence_note_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GrafeasClient( - 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_occurrence_note in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_occurrence_note] = mock_rpc - request = {} - client.get_occurrence_note(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_occurrence_note(request) - - # Establish that a new wrapper 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_occurrence_note_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = GrafeasAsyncClient( - 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_occurrence_note in client._client._transport._wrapped_methods - - # 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_occurrence_note] = mock_rpc - - request = {} - await client.get_occurrence_note(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_occurrence_note(request) - - # Establish that a new wrapper 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_occurrence_note_async(transport: str = 'grpc_asyncio', request_type=grafeas.GetOccurrenceNoteRequest): - client = GrafeasAsyncClient( - 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_occurrence_note), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note( - name='name_value', - short_description='short_description_value', - long_description='long_description_value', - kind=common.NoteKind.VULNERABILITY, - related_note_names=['related_note_names_value'], - )) - response = await client.get_occurrence_note(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = grafeas.GetOccurrenceNoteRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Note) - assert response.name == 'name_value' - assert response.short_description == 'short_description_value' - assert response.long_description == 'long_description_value' - assert response.kind == common.NoteKind.VULNERABILITY - assert response.related_note_names == ['related_note_names_value'] - - -@pytest.mark.asyncio -async def test_get_occurrence_note_async_from_dict(): - await test_get_occurrence_note_async(request_type=dict) - -def test_get_occurrence_note_field_headers(): - client = GrafeasClient( - 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 = grafeas.GetOccurrenceNoteRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_occurrence_note), - '__call__') as call: - call.return_value = grafeas.Note() - client.get_occurrence_note(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_occurrence_note_field_headers_async(): - client = GrafeasAsyncClient( - 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 = grafeas.GetOccurrenceNoteRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_occurrence_note), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) - await client.get_occurrence_note(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_occurrence_note_flattened(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_occurrence_note), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Note() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_occurrence_note( - 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_occurrence_note_flattened_error(): - client = GrafeasClient( - 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_occurrence_note( - grafeas.GetOccurrenceNoteRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_occurrence_note_flattened_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_occurrence_note), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Note() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_occurrence_note( - 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_occurrence_note_flattened_error_async(): - client = GrafeasAsyncClient( - 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_occurrence_note( - grafeas.GetOccurrenceNoteRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - grafeas.GetNoteRequest, - dict, -]) -def test_get_note(request_type, transport: str = 'grpc'): - client = GrafeasClient( - 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_note), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Note( - name='name_value', - short_description='short_description_value', - long_description='long_description_value', - kind=common.NoteKind.VULNERABILITY, - related_note_names=['related_note_names_value'], - ) - response = client.get_note(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = grafeas.GetNoteRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Note) - assert response.name == 'name_value' - assert response.short_description == 'short_description_value' - assert response.long_description == 'long_description_value' - assert response.kind == common.NoteKind.VULNERABILITY - assert response.related_note_names == ['related_note_names_value'] - - -def test_get_note_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 = GrafeasClient( - 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 = grafeas.GetNoteRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_note), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_note(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.GetNoteRequest( - name='name_value', - ) - -def test_get_note_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GrafeasClient( - 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_note in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_note] = mock_rpc - request = {} - client.get_note(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_note(request) - - # Establish that a new wrapper 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_note_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = GrafeasAsyncClient( - 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_note in client._client._transport._wrapped_methods - - # 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_note] = mock_rpc - - request = {} - await client.get_note(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_note(request) - - # Establish that a new wrapper 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_note_async(transport: str = 'grpc_asyncio', request_type=grafeas.GetNoteRequest): - client = GrafeasAsyncClient( - 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_note), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note( - name='name_value', - short_description='short_description_value', - long_description='long_description_value', - kind=common.NoteKind.VULNERABILITY, - related_note_names=['related_note_names_value'], - )) - response = await client.get_note(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = grafeas.GetNoteRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Note) - assert response.name == 'name_value' - assert response.short_description == 'short_description_value' - assert response.long_description == 'long_description_value' - assert response.kind == common.NoteKind.VULNERABILITY - assert response.related_note_names == ['related_note_names_value'] - - -@pytest.mark.asyncio -async def test_get_note_async_from_dict(): - await test_get_note_async(request_type=dict) - -def test_get_note_field_headers(): - client = GrafeasClient( - 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 = grafeas.GetNoteRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_note), - '__call__') as call: - call.return_value = grafeas.Note() - client.get_note(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_note_field_headers_async(): - client = GrafeasAsyncClient( - 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 = grafeas.GetNoteRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_note), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) - await client.get_note(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_note_flattened(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_note), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Note() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_note( - 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_note_flattened_error(): - client = GrafeasClient( - 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_note( - grafeas.GetNoteRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_note_flattened_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_note), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Note() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_note( - 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_note_flattened_error_async(): - client = GrafeasAsyncClient( - 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_note( - grafeas.GetNoteRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - grafeas.ListNotesRequest, - dict, -]) -def test_list_notes(request_type, transport: str = 'grpc'): - client = GrafeasClient( - 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_notes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.ListNotesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_notes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = grafeas.ListNotesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNotesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_notes_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 = GrafeasClient( - 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 = grafeas.ListNotesRequest( - parent='parent_value', - filter='filter_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_notes), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_notes(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.ListNotesRequest( - parent='parent_value', - filter='filter_value', - page_token='page_token_value', - ) - -def test_list_notes_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GrafeasClient( - 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_notes in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_notes] = mock_rpc - request = {} - client.list_notes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_notes(request) - - # Establish that a new wrapper 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_notes_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = GrafeasAsyncClient( - 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_notes in client._client._transport._wrapped_methods - - # 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_notes] = mock_rpc - - request = {} - await client.list_notes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_notes(request) - - # Establish that a new wrapper 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_notes_async(transport: str = 'grpc_asyncio', request_type=grafeas.ListNotesRequest): - client = GrafeasAsyncClient( - 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_notes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.ListNotesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_notes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = grafeas.ListNotesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNotesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_notes_async_from_dict(): - await test_list_notes_async(request_type=dict) - -def test_list_notes_field_headers(): - client = GrafeasClient( - 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 = grafeas.ListNotesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notes), - '__call__') as call: - call.return_value = grafeas.ListNotesResponse() - client.list_notes(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_notes_field_headers_async(): - client = GrafeasAsyncClient( - 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 = grafeas.ListNotesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notes), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.ListNotesResponse()) - await client.list_notes(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_notes_flattened(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.ListNotesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_notes( - parent='parent_value', - filter='filter_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].filter - mock_val = 'filter_value' - assert arg == mock_val - - -def test_list_notes_flattened_error(): - client = GrafeasClient( - 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_notes( - grafeas.ListNotesRequest(), - parent='parent_value', - filter='filter_value', - ) - -@pytest.mark.asyncio -async def test_list_notes_flattened_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.ListNotesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.ListNotesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_notes( - parent='parent_value', - filter='filter_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].filter - mock_val = 'filter_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_notes_flattened_error_async(): - client = GrafeasAsyncClient( - 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_notes( - grafeas.ListNotesRequest(), - parent='parent_value', - filter='filter_value', - ) - - -def test_list_notes_pager(transport_name: str = "grpc"): - client = GrafeasClient( - 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_notes), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - grafeas.ListNotesResponse( - notes=[ - grafeas.Note(), - grafeas.Note(), - grafeas.Note(), - ], - next_page_token='abc', - ), - grafeas.ListNotesResponse( - notes=[], - next_page_token='def', - ), - grafeas.ListNotesResponse( - notes=[ - grafeas.Note(), - ], - next_page_token='ghi', - ), - grafeas.ListNotesResponse( - notes=[ - grafeas.Note(), - grafeas.Note(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_notes(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, grafeas.Note) - for i in results) -def test_list_notes_pages(transport_name: str = "grpc"): - client = GrafeasClient( - 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_notes), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - grafeas.ListNotesResponse( - notes=[ - grafeas.Note(), - grafeas.Note(), - grafeas.Note(), - ], - next_page_token='abc', - ), - grafeas.ListNotesResponse( - notes=[], - next_page_token='def', - ), - grafeas.ListNotesResponse( - notes=[ - grafeas.Note(), - ], - next_page_token='ghi', - ), - grafeas.ListNotesResponse( - notes=[ - grafeas.Note(), - grafeas.Note(), - ], - ), - RuntimeError, - ) - pages = list(client.list_notes(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_notes_async_pager(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notes), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - grafeas.ListNotesResponse( - notes=[ - grafeas.Note(), - grafeas.Note(), - grafeas.Note(), - ], - next_page_token='abc', - ), - grafeas.ListNotesResponse( - notes=[], - next_page_token='def', - ), - grafeas.ListNotesResponse( - notes=[ - grafeas.Note(), - ], - next_page_token='ghi', - ), - grafeas.ListNotesResponse( - notes=[ - grafeas.Note(), - grafeas.Note(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_notes(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, grafeas.Note) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_notes_async_pages(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notes), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - grafeas.ListNotesResponse( - notes=[ - grafeas.Note(), - grafeas.Note(), - grafeas.Note(), - ], - next_page_token='abc', - ), - grafeas.ListNotesResponse( - notes=[], - next_page_token='def', - ), - grafeas.ListNotesResponse( - notes=[ - grafeas.Note(), - ], - next_page_token='ghi', - ), - grafeas.ListNotesResponse( - notes=[ - grafeas.Note(), - grafeas.Note(), - ], - ), - 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_notes(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", [ - grafeas.DeleteNoteRequest, - dict, -]) -def test_delete_note(request_type, transport: str = 'grpc'): - client = GrafeasClient( - 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_note), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_note(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = grafeas.DeleteNoteRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_note_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 = GrafeasClient( - 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 = grafeas.DeleteNoteRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_note), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_note(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.DeleteNoteRequest( - name='name_value', - ) - -def test_delete_note_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GrafeasClient( - 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_note in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_note] = mock_rpc - request = {} - client.delete_note(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_note(request) - - # Establish that a new wrapper 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_note_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = GrafeasAsyncClient( - 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_note in client._client._transport._wrapped_methods - - # 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_note] = mock_rpc - - request = {} - await client.delete_note(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.delete_note(request) - - # Establish that a new wrapper 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_note_async(transport: str = 'grpc_asyncio', request_type=grafeas.DeleteNoteRequest): - client = GrafeasAsyncClient( - 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_note), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_note(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = grafeas.DeleteNoteRequest() - 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_note_async_from_dict(): - await test_delete_note_async(request_type=dict) - -def test_delete_note_field_headers(): - client = GrafeasClient( - 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 = grafeas.DeleteNoteRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_note), - '__call__') as call: - call.return_value = None - client.delete_note(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_note_field_headers_async(): - client = GrafeasAsyncClient( - 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 = grafeas.DeleteNoteRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_note), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_note(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_note_flattened(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_note), - '__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_note( - 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_note_flattened_error(): - client = GrafeasClient( - 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_note( - grafeas.DeleteNoteRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_note_flattened_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_note), - '__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_note( - 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_note_flattened_error_async(): - client = GrafeasAsyncClient( - 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_note( - grafeas.DeleteNoteRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - grafeas.CreateNoteRequest, - dict, -]) -def test_create_note(request_type, transport: str = 'grpc'): - client = GrafeasClient( - 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_note), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Note( - name='name_value', - short_description='short_description_value', - long_description='long_description_value', - kind=common.NoteKind.VULNERABILITY, - related_note_names=['related_note_names_value'], - ) - response = client.create_note(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = grafeas.CreateNoteRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Note) - assert response.name == 'name_value' - assert response.short_description == 'short_description_value' - assert response.long_description == 'long_description_value' - assert response.kind == common.NoteKind.VULNERABILITY - assert response.related_note_names == ['related_note_names_value'] - - -def test_create_note_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 = GrafeasClient( - 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 = grafeas.CreateNoteRequest( - parent='parent_value', - note_id='note_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_note), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_note(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.CreateNoteRequest( - parent='parent_value', - note_id='note_id_value', - ) - -def test_create_note_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GrafeasClient( - 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_note in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_note] = mock_rpc - request = {} - client.create_note(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_note(request) - - # Establish that a new wrapper 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_note_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = GrafeasAsyncClient( - 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_note in client._client._transport._wrapped_methods - - # 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_note] = mock_rpc - - request = {} - await client.create_note(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.create_note(request) - - # Establish that a new wrapper 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_note_async(transport: str = 'grpc_asyncio', request_type=grafeas.CreateNoteRequest): - client = GrafeasAsyncClient( - 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_note), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note( - name='name_value', - short_description='short_description_value', - long_description='long_description_value', - kind=common.NoteKind.VULNERABILITY, - related_note_names=['related_note_names_value'], - )) - response = await client.create_note(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = grafeas.CreateNoteRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Note) - assert response.name == 'name_value' - assert response.short_description == 'short_description_value' - assert response.long_description == 'long_description_value' - assert response.kind == common.NoteKind.VULNERABILITY - assert response.related_note_names == ['related_note_names_value'] - - -@pytest.mark.asyncio -async def test_create_note_async_from_dict(): - await test_create_note_async(request_type=dict) - -def test_create_note_field_headers(): - client = GrafeasClient( - 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 = grafeas.CreateNoteRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_note), - '__call__') as call: - call.return_value = grafeas.Note() - client.create_note(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_note_field_headers_async(): - client = GrafeasAsyncClient( - 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 = grafeas.CreateNoteRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_note), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) - await client.create_note(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_note_flattened(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_note), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Note() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_note( - parent='parent_value', - note_id='note_id_value', - note=grafeas.Note(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].note_id - mock_val = 'note_id_value' - assert arg == mock_val - arg = args[0].note - mock_val = grafeas.Note(name='name_value') - assert arg == mock_val - - -def test_create_note_flattened_error(): - client = GrafeasClient( - 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_note( - grafeas.CreateNoteRequest(), - parent='parent_value', - note_id='note_id_value', - note=grafeas.Note(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_note_flattened_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_note), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Note() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_note( - parent='parent_value', - note_id='note_id_value', - note=grafeas.Note(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].note_id - mock_val = 'note_id_value' - assert arg == mock_val - arg = args[0].note - mock_val = grafeas.Note(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_note_flattened_error_async(): - client = GrafeasAsyncClient( - 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_note( - grafeas.CreateNoteRequest(), - parent='parent_value', - note_id='note_id_value', - note=grafeas.Note(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - grafeas.BatchCreateNotesRequest, - dict, -]) -def test_batch_create_notes(request_type, transport: str = 'grpc'): - client = GrafeasClient( - 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.batch_create_notes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.BatchCreateNotesResponse( - ) - response = client.batch_create_notes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = grafeas.BatchCreateNotesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.BatchCreateNotesResponse) - - -def test_batch_create_notes_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 = GrafeasClient( - 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 = grafeas.BatchCreateNotesRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_notes), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.batch_create_notes(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.BatchCreateNotesRequest( - parent='parent_value', - ) - -def test_batch_create_notes_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GrafeasClient( - 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.batch_create_notes in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.batch_create_notes] = mock_rpc - request = {} - client.batch_create_notes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.batch_create_notes(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_batch_create_notes_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = GrafeasAsyncClient( - 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.batch_create_notes in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.batch_create_notes] = mock_rpc - - request = {} - await client.batch_create_notes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.batch_create_notes(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_batch_create_notes_async(transport: str = 'grpc_asyncio', request_type=grafeas.BatchCreateNotesRequest): - client = GrafeasAsyncClient( - 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.batch_create_notes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.BatchCreateNotesResponse( - )) - response = await client.batch_create_notes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = grafeas.BatchCreateNotesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.BatchCreateNotesResponse) - - -@pytest.mark.asyncio -async def test_batch_create_notes_async_from_dict(): - await test_batch_create_notes_async(request_type=dict) - -def test_batch_create_notes_field_headers(): - client = GrafeasClient( - 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 = grafeas.BatchCreateNotesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_notes), - '__call__') as call: - call.return_value = grafeas.BatchCreateNotesResponse() - client.batch_create_notes(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_batch_create_notes_field_headers_async(): - client = GrafeasAsyncClient( - 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 = grafeas.BatchCreateNotesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_notes), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.BatchCreateNotesResponse()) - await client.batch_create_notes(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_batch_create_notes_flattened(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_notes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.BatchCreateNotesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.batch_create_notes( - parent='parent_value', - notes={'key_value': grafeas.Note(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].notes - mock_val = {'key_value': grafeas.Note(name='name_value')} - assert arg == mock_val - - -def test_batch_create_notes_flattened_error(): - client = GrafeasClient( - 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.batch_create_notes( - grafeas.BatchCreateNotesRequest(), - parent='parent_value', - notes={'key_value': grafeas.Note(name='name_value')}, - ) - -@pytest.mark.asyncio -async def test_batch_create_notes_flattened_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_notes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.BatchCreateNotesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.BatchCreateNotesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.batch_create_notes( - parent='parent_value', - notes={'key_value': grafeas.Note(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].notes - mock_val = {'key_value': grafeas.Note(name='name_value')} - assert arg == mock_val - -@pytest.mark.asyncio -async def test_batch_create_notes_flattened_error_async(): - client = GrafeasAsyncClient( - 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.batch_create_notes( - grafeas.BatchCreateNotesRequest(), - parent='parent_value', - notes={'key_value': grafeas.Note(name='name_value')}, - ) - - -@pytest.mark.parametrize("request_type", [ - grafeas.UpdateNoteRequest, - dict, -]) -def test_update_note(request_type, transport: str = 'grpc'): - client = GrafeasClient( - 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_note), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Note( - name='name_value', - short_description='short_description_value', - long_description='long_description_value', - kind=common.NoteKind.VULNERABILITY, - related_note_names=['related_note_names_value'], - ) - response = client.update_note(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = grafeas.UpdateNoteRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Note) - assert response.name == 'name_value' - assert response.short_description == 'short_description_value' - assert response.long_description == 'long_description_value' - assert response.kind == common.NoteKind.VULNERABILITY - assert response.related_note_names == ['related_note_names_value'] - - -def test_update_note_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 = GrafeasClient( - 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 = grafeas.UpdateNoteRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_note), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_note(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.UpdateNoteRequest( - name='name_value', - ) - -def test_update_note_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GrafeasClient( - 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_note in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_note] = mock_rpc - request = {} - client.update_note(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_note(request) - - # Establish that a new wrapper 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_note_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = GrafeasAsyncClient( - 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_note in client._client._transport._wrapped_methods - - # 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_note] = mock_rpc - - request = {} - await client.update_note(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_note(request) - - # Establish that a new wrapper 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_note_async(transport: str = 'grpc_asyncio', request_type=grafeas.UpdateNoteRequest): - client = GrafeasAsyncClient( - 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_note), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note( - name='name_value', - short_description='short_description_value', - long_description='long_description_value', - kind=common.NoteKind.VULNERABILITY, - related_note_names=['related_note_names_value'], - )) - response = await client.update_note(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = grafeas.UpdateNoteRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Note) - assert response.name == 'name_value' - assert response.short_description == 'short_description_value' - assert response.long_description == 'long_description_value' - assert response.kind == common.NoteKind.VULNERABILITY - assert response.related_note_names == ['related_note_names_value'] - - -@pytest.mark.asyncio -async def test_update_note_async_from_dict(): - await test_update_note_async(request_type=dict) - -def test_update_note_field_headers(): - client = GrafeasClient( - 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 = grafeas.UpdateNoteRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_note), - '__call__') as call: - call.return_value = grafeas.Note() - client.update_note(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_update_note_field_headers_async(): - client = GrafeasAsyncClient( - 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 = grafeas.UpdateNoteRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_note), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) - await client.update_note(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_update_note_flattened(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_note), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Note() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_note( - name='name_value', - note=grafeas.Note(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].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].note - mock_val = grafeas.Note(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_note_flattened_error(): - client = GrafeasClient( - 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_note( - grafeas.UpdateNoteRequest(), - name='name_value', - note=grafeas.Note(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_note_flattened_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_note), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Note() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_note( - name='name_value', - note=grafeas.Note(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].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].note - mock_val = grafeas.Note(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_note_flattened_error_async(): - client = GrafeasAsyncClient( - 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_note( - grafeas.UpdateNoteRequest(), - name='name_value', - note=grafeas.Note(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - grafeas.ListNoteOccurrencesRequest, - dict, -]) -def test_list_note_occurrences(request_type, transport: str = 'grpc'): - client = GrafeasClient( - 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_note_occurrences), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.ListNoteOccurrencesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_note_occurrences(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = grafeas.ListNoteOccurrencesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNoteOccurrencesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_note_occurrences_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 = GrafeasClient( - 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 = grafeas.ListNoteOccurrencesRequest( - name='name_value', - filter='filter_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_note_occurrences), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_note_occurrences(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.ListNoteOccurrencesRequest( - name='name_value', - filter='filter_value', - page_token='page_token_value', - ) - -def test_list_note_occurrences_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GrafeasClient( - 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_note_occurrences in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_note_occurrences] = mock_rpc - request = {} - client.list_note_occurrences(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_note_occurrences(request) - - # Establish that a new wrapper 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_note_occurrences_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached 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 = GrafeasAsyncClient( - 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_note_occurrences in client._client._transport._wrapped_methods - - # 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_note_occurrences] = mock_rpc - - request = {} - await client.list_note_occurrences(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_note_occurrences(request) - - # Establish that a new wrapper 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_note_occurrences_async(transport: str = 'grpc_asyncio', request_type=grafeas.ListNoteOccurrencesRequest): - client = GrafeasAsyncClient( - 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_note_occurrences), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.ListNoteOccurrencesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_note_occurrences(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = grafeas.ListNoteOccurrencesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNoteOccurrencesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_note_occurrences_async_from_dict(): - await test_list_note_occurrences_async(request_type=dict) - -def test_list_note_occurrences_field_headers(): - client = GrafeasClient( - 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 = grafeas.ListNoteOccurrencesRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_note_occurrences), - '__call__') as call: - call.return_value = grafeas.ListNoteOccurrencesResponse() - client.list_note_occurrences(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_list_note_occurrences_field_headers_async(): - client = GrafeasAsyncClient( - 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 = grafeas.ListNoteOccurrencesRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_note_occurrences), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.ListNoteOccurrencesResponse()) - await client.list_note_occurrences(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_list_note_occurrences_flattened(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_note_occurrences), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.ListNoteOccurrencesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_note_occurrences( - name='name_value', - filter='filter_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 - arg = args[0].filter - mock_val = 'filter_value' - assert arg == mock_val - - -def test_list_note_occurrences_flattened_error(): - client = GrafeasClient( - 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_note_occurrences( - grafeas.ListNoteOccurrencesRequest(), - name='name_value', - filter='filter_value', - ) - -@pytest.mark.asyncio -async def test_list_note_occurrences_flattened_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_note_occurrences), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.ListNoteOccurrencesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.ListNoteOccurrencesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_note_occurrences( - name='name_value', - filter='filter_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 - arg = args[0].filter - mock_val = 'filter_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_note_occurrences_flattened_error_async(): - client = GrafeasAsyncClient( - 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_note_occurrences( - grafeas.ListNoteOccurrencesRequest(), - name='name_value', - filter='filter_value', - ) - - -def test_list_note_occurrences_pager(transport_name: str = "grpc"): - client = GrafeasClient( - 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_note_occurrences), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - grafeas.ListNoteOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - next_page_token='abc', - ), - grafeas.ListNoteOccurrencesResponse( - occurrences=[], - next_page_token='def', - ), - grafeas.ListNoteOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - ], - next_page_token='ghi', - ), - grafeas.ListNoteOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('name', ''), - )), - ) - pager = client.list_note_occurrences(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, grafeas.Occurrence) - for i in results) -def test_list_note_occurrences_pages(transport_name: str = "grpc"): - client = GrafeasClient( - 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_note_occurrences), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - grafeas.ListNoteOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - next_page_token='abc', - ), - grafeas.ListNoteOccurrencesResponse( - occurrences=[], - next_page_token='def', - ), - grafeas.ListNoteOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - ], - next_page_token='ghi', - ), - grafeas.ListNoteOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - ), - RuntimeError, - ) - pages = list(client.list_note_occurrences(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_note_occurrences_async_pager(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_note_occurrences), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - grafeas.ListNoteOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - next_page_token='abc', - ), - grafeas.ListNoteOccurrencesResponse( - occurrences=[], - next_page_token='def', - ), - grafeas.ListNoteOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - ], - next_page_token='ghi', - ), - grafeas.ListNoteOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_note_occurrences(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, grafeas.Occurrence) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_note_occurrences_async_pages(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_note_occurrences), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - grafeas.ListNoteOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - next_page_token='abc', - ), - grafeas.ListNoteOccurrencesResponse( - occurrences=[], - next_page_token='def', - ), - grafeas.ListNoteOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - ], - next_page_token='ghi', - ), - grafeas.ListNoteOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - ), - 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_note_occurrences(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_occurrence_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 = GrafeasClient( - 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_occurrence in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_occurrence] = mock_rpc - - request = {} - client.get_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_occurrence(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_occurrence_rest_required_fields(request_type=grafeas.GetOccurrenceRequest): - transport_class = transports.GrafeasRestTransport - - 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_occurrence._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_occurrence._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 = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = grafeas.Occurrence() - # 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 = grafeas.Occurrence.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_occurrence(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_occurrence_rest_unset_required_fields(): - transport = transports.GrafeasRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_occurrence._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_occurrence_rest_flattened(): - client = GrafeasClient( - 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 = grafeas.Occurrence() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/occurrences/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 = grafeas.Occurrence.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_occurrence(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/occurrences/*}" % client.transport._host, args[1]) - - -def test_get_occurrence_rest_flattened_error(transport: str = 'rest'): - client = GrafeasClient( - 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_occurrence( - grafeas.GetOccurrenceRequest(), - name='name_value', - ) - - -def test_list_occurrences_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 = GrafeasClient( - 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_occurrences in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_occurrences] = mock_rpc - - request = {} - client.list_occurrences(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_occurrences(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_occurrences_rest_required_fields(request_type=grafeas.ListOccurrencesRequest): - transport_class = transports.GrafeasRestTransport - - 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_occurrences._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_occurrences._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = grafeas.ListOccurrencesResponse() - # 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 = grafeas.ListOccurrencesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_occurrences(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_occurrences_rest_unset_required_fields(): - transport = transports.GrafeasRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_occurrences._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_occurrences_rest_flattened(): - client = GrafeasClient( - 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 = grafeas.ListOccurrencesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - filter='filter_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 = grafeas.ListOccurrencesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_occurrences(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*}/occurrences" % client.transport._host, args[1]) - - -def test_list_occurrences_rest_flattened_error(transport: str = 'rest'): - client = GrafeasClient( - 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_occurrences( - grafeas.ListOccurrencesRequest(), - parent='parent_value', - filter='filter_value', - ) - - -def test_list_occurrences_rest_pager(transport: str = 'rest'): - client = GrafeasClient( - 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 = ( - grafeas.ListOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - next_page_token='abc', - ), - grafeas.ListOccurrencesResponse( - occurrences=[], - next_page_token='def', - ), - grafeas.ListOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - ], - next_page_token='ghi', - ), - grafeas.ListOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(grafeas.ListOccurrencesResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1'} - - pager = client.list_occurrences(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, grafeas.Occurrence) - for i in results) - - pages = list(client.list_occurrences(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_delete_occurrence_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 = GrafeasClient( - 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_occurrence in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_occurrence] = mock_rpc - - request = {} - client.delete_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_occurrence(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_occurrence_rest_required_fields(request_type=grafeas.DeleteOccurrenceRequest): - transport_class = transports.GrafeasRestTransport - - 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_occurrence._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_occurrence._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 = GrafeasClient( - 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_occurrence(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_occurrence_rest_unset_required_fields(): - transport = transports.GrafeasRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_occurrence._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_delete_occurrence_rest_flattened(): - client = GrafeasClient( - 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': 'projects/sample1/occurrences/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_occurrence(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/occurrences/*}" % client.transport._host, args[1]) - - -def test_delete_occurrence_rest_flattened_error(transport: str = 'rest'): - client = GrafeasClient( - 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_occurrence( - grafeas.DeleteOccurrenceRequest(), - name='name_value', - ) - - -def test_create_occurrence_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 = GrafeasClient( - 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_occurrence in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_occurrence] = mock_rpc - - request = {} - client.create_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_occurrence(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_occurrence_rest_required_fields(request_type=grafeas.CreateOccurrenceRequest): - transport_class = transports.GrafeasRestTransport - - 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_occurrence._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_occurrence._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 = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = grafeas.Occurrence() - # 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 = grafeas.Occurrence.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_occurrence(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_occurrence_rest_unset_required_fields(): - transport = transports.GrafeasRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_occurrence._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "occurrence", ))) - - -def test_create_occurrence_rest_flattened(): - client = GrafeasClient( - 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 = grafeas.Occurrence() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - occurrence=grafeas.Occurrence(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 = grafeas.Occurrence.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_occurrence(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*}/occurrences" % client.transport._host, args[1]) - - -def test_create_occurrence_rest_flattened_error(transport: str = 'rest'): - client = GrafeasClient( - 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_occurrence( - grafeas.CreateOccurrenceRequest(), - parent='parent_value', - occurrence=grafeas.Occurrence(name='name_value'), - ) - - -def test_batch_create_occurrences_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 = GrafeasClient( - 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.batch_create_occurrences in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.batch_create_occurrences] = mock_rpc - - request = {} - client.batch_create_occurrences(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.batch_create_occurrences(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_batch_create_occurrences_rest_required_fields(request_type=grafeas.BatchCreateOccurrencesRequest): - transport_class = transports.GrafeasRestTransport - - 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()).batch_create_occurrences._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()).batch_create_occurrences._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 = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = grafeas.BatchCreateOccurrencesResponse() - # 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 = grafeas.BatchCreateOccurrencesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.batch_create_occurrences(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_batch_create_occurrences_rest_unset_required_fields(): - transport = transports.GrafeasRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.batch_create_occurrences._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "occurrences", ))) - - -def test_batch_create_occurrences_rest_flattened(): - client = GrafeasClient( - 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 = grafeas.BatchCreateOccurrencesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - occurrences=[grafeas.Occurrence(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 = grafeas.BatchCreateOccurrencesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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.batch_create_occurrences(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*}/occurrences:batchCreate" % client.transport._host, args[1]) - - -def test_batch_create_occurrences_rest_flattened_error(transport: str = 'rest'): - client = GrafeasClient( - 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.batch_create_occurrences( - grafeas.BatchCreateOccurrencesRequest(), - parent='parent_value', - occurrences=[grafeas.Occurrence(name='name_value')], - ) - - -def test_update_occurrence_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 = GrafeasClient( - 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_occurrence in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_occurrence] = mock_rpc - - request = {} - client.update_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_occurrence(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_occurrence_rest_required_fields(request_type=grafeas.UpdateOccurrenceRequest): - transport_class = transports.GrafeasRestTransport - - 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()).update_occurrence._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()).update_occurrence._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 - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = grafeas.Occurrence() - # 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 = grafeas.Occurrence.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_occurrence(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_occurrence_rest_unset_required_fields(): - transport = transports.GrafeasRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_occurrence._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("name", "occurrence", ))) - - -def test_update_occurrence_rest_flattened(): - client = GrafeasClient( - 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 = grafeas.Occurrence() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/occurrences/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - occurrence=grafeas.Occurrence(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 = grafeas.Occurrence.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_occurrence(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/occurrences/*}" % client.transport._host, args[1]) - - -def test_update_occurrence_rest_flattened_error(transport: str = 'rest'): - client = GrafeasClient( - 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_occurrence( - grafeas.UpdateOccurrenceRequest(), - name='name_value', - occurrence=grafeas.Occurrence(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_get_occurrence_note_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 = GrafeasClient( - 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_occurrence_note in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_occurrence_note] = mock_rpc - - request = {} - client.get_occurrence_note(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_occurrence_note(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_occurrence_note_rest_required_fields(request_type=grafeas.GetOccurrenceNoteRequest): - transport_class = transports.GrafeasRestTransport - - 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_occurrence_note._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_occurrence_note._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 = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = grafeas.Note() - # 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 = grafeas.Note.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_occurrence_note(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_occurrence_note_rest_unset_required_fields(): - transport = transports.GrafeasRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_occurrence_note._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_occurrence_note_rest_flattened(): - client = GrafeasClient( - 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 = grafeas.Note() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/occurrences/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 = grafeas.Note.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_occurrence_note(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/occurrences/*}/notes" % client.transport._host, args[1]) - - -def test_get_occurrence_note_rest_flattened_error(transport: str = 'rest'): - client = GrafeasClient( - 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_occurrence_note( - grafeas.GetOccurrenceNoteRequest(), - name='name_value', - ) - - -def test_get_note_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 = GrafeasClient( - 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_note in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_note] = mock_rpc - - request = {} - client.get_note(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_note(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_note_rest_required_fields(request_type=grafeas.GetNoteRequest): - transport_class = transports.GrafeasRestTransport - - 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_note._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_note._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 = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = grafeas.Note() - # 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 = grafeas.Note.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_note(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_note_rest_unset_required_fields(): - transport = transports.GrafeasRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_note._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_note_rest_flattened(): - client = GrafeasClient( - 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 = grafeas.Note() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/notes/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 = grafeas.Note.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_note(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/notes/*}" % client.transport._host, args[1]) - - -def test_get_note_rest_flattened_error(transport: str = 'rest'): - client = GrafeasClient( - 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_note( - grafeas.GetNoteRequest(), - name='name_value', - ) - - -def test_list_notes_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 = GrafeasClient( - 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_notes in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_notes] = mock_rpc - - request = {} - client.list_notes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_notes(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_notes_rest_required_fields(request_type=grafeas.ListNotesRequest): - transport_class = transports.GrafeasRestTransport - - 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_notes._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_notes._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = grafeas.ListNotesResponse() - # 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 = grafeas.ListNotesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_notes(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_notes_rest_unset_required_fields(): - transport = transports.GrafeasRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_notes._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_notes_rest_flattened(): - client = GrafeasClient( - 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 = grafeas.ListNotesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - filter='filter_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 = grafeas.ListNotesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_notes(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*}/notes" % client.transport._host, args[1]) - - -def test_list_notes_rest_flattened_error(transport: str = 'rest'): - client = GrafeasClient( - 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_notes( - grafeas.ListNotesRequest(), - parent='parent_value', - filter='filter_value', - ) - - -def test_list_notes_rest_pager(transport: str = 'rest'): - client = GrafeasClient( - 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 = ( - grafeas.ListNotesResponse( - notes=[ - grafeas.Note(), - grafeas.Note(), - grafeas.Note(), - ], - next_page_token='abc', - ), - grafeas.ListNotesResponse( - notes=[], - next_page_token='def', - ), - grafeas.ListNotesResponse( - notes=[ - grafeas.Note(), - ], - next_page_token='ghi', - ), - grafeas.ListNotesResponse( - notes=[ - grafeas.Note(), - grafeas.Note(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(grafeas.ListNotesResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1'} - - pager = client.list_notes(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, grafeas.Note) - for i in results) - - pages = list(client.list_notes(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_delete_note_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 = GrafeasClient( - 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_note in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_note] = mock_rpc - - request = {} - client.delete_note(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_note(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_note_rest_required_fields(request_type=grafeas.DeleteNoteRequest): - transport_class = transports.GrafeasRestTransport - - 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_note._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_note._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 = GrafeasClient( - 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_note(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_note_rest_unset_required_fields(): - transport = transports.GrafeasRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_note._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_delete_note_rest_flattened(): - client = GrafeasClient( - 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': 'projects/sample1/notes/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_note(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/notes/*}" % client.transport._host, args[1]) - - -def test_delete_note_rest_flattened_error(transport: str = 'rest'): - client = GrafeasClient( - 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_note( - grafeas.DeleteNoteRequest(), - name='name_value', - ) - - -def test_create_note_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 = GrafeasClient( - 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_note in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_note] = mock_rpc - - request = {} - client.create_note(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_note(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_note_rest_required_fields(request_type=grafeas.CreateNoteRequest): - transport_class = transports.GrafeasRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["note_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 "noteId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_note._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "noteId" in jsonified_request - assert jsonified_request["noteId"] == request_init["note_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["noteId"] = 'note_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_note._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("note_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 "noteId" in jsonified_request - assert jsonified_request["noteId"] == 'note_id_value' - - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = grafeas.Note() - # 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 = grafeas.Note.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_note(request) - - expected_params = [ - ( - "noteId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_note_rest_unset_required_fields(): - transport = transports.GrafeasRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_note._get_unset_required_fields({}) - assert set(unset_fields) == (set(("noteId", )) & set(("parent", "noteId", "note", ))) - - -def test_create_note_rest_flattened(): - client = GrafeasClient( - 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 = grafeas.Note() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - note_id='note_id_value', - note=grafeas.Note(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 = grafeas.Note.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_note(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*}/notes" % client.transport._host, args[1]) - - -def test_create_note_rest_flattened_error(transport: str = 'rest'): - client = GrafeasClient( - 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_note( - grafeas.CreateNoteRequest(), - parent='parent_value', - note_id='note_id_value', - note=grafeas.Note(name='name_value'), - ) - - -def test_batch_create_notes_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 = GrafeasClient( - 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.batch_create_notes in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.batch_create_notes] = mock_rpc - - request = {} - client.batch_create_notes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.batch_create_notes(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_batch_create_notes_rest_required_fields(request_type=grafeas.BatchCreateNotesRequest): - transport_class = transports.GrafeasRestTransport - - 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()).batch_create_notes._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()).batch_create_notes._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 = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = grafeas.BatchCreateNotesResponse() - # 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 = grafeas.BatchCreateNotesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.batch_create_notes(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_batch_create_notes_rest_unset_required_fields(): - transport = transports.GrafeasRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.batch_create_notes._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "notes", ))) - - -def test_batch_create_notes_rest_flattened(): - client = GrafeasClient( - 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 = grafeas.BatchCreateNotesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - notes={'key_value': grafeas.Note(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 = grafeas.BatchCreateNotesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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.batch_create_notes(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*}/notes:batchCreate" % client.transport._host, args[1]) - - -def test_batch_create_notes_rest_flattened_error(transport: str = 'rest'): - client = GrafeasClient( - 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.batch_create_notes( - grafeas.BatchCreateNotesRequest(), - parent='parent_value', - notes={'key_value': grafeas.Note(name='name_value')}, - ) - - -def test_update_note_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 = GrafeasClient( - 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_note in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_note] = mock_rpc - - request = {} - client.update_note(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_note(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_note_rest_required_fields(request_type=grafeas.UpdateNoteRequest): - transport_class = transports.GrafeasRestTransport - - 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()).update_note._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()).update_note._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 - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = grafeas.Note() - # 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 = grafeas.Note.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_note(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_note_rest_unset_required_fields(): - transport = transports.GrafeasRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_note._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("name", "note", ))) - - -def test_update_note_rest_flattened(): - client = GrafeasClient( - 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 = grafeas.Note() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/notes/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - note=grafeas.Note(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 = grafeas.Note.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_note(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/notes/*}" % client.transport._host, args[1]) - - -def test_update_note_rest_flattened_error(transport: str = 'rest'): - client = GrafeasClient( - 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_note( - grafeas.UpdateNoteRequest(), - name='name_value', - note=grafeas.Note(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_list_note_occurrences_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 = GrafeasClient( - 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_note_occurrences in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_note_occurrences] = mock_rpc - - request = {} - client.list_note_occurrences(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_note_occurrences(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_note_occurrences_rest_required_fields(request_type=grafeas.ListNoteOccurrencesRequest): - transport_class = transports.GrafeasRestTransport - - 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()).list_note_occurrences._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()).list_note_occurrences._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = grafeas.ListNoteOccurrencesResponse() - # 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 = grafeas.ListNoteOccurrencesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_note_occurrences(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_note_occurrences_rest_unset_required_fields(): - transport = transports.GrafeasRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_note_occurrences._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("name", ))) - - -def test_list_note_occurrences_rest_flattened(): - client = GrafeasClient( - 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 = grafeas.ListNoteOccurrencesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/notes/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - filter='filter_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 = grafeas.ListNoteOccurrencesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_note_occurrences(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/notes/*}/occurrences" % client.transport._host, args[1]) - - -def test_list_note_occurrences_rest_flattened_error(transport: str = 'rest'): - client = GrafeasClient( - 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_note_occurrences( - grafeas.ListNoteOccurrencesRequest(), - name='name_value', - filter='filter_value', - ) - - -def test_list_note_occurrences_rest_pager(transport: str = 'rest'): - client = GrafeasClient( - 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 = ( - grafeas.ListNoteOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - next_page_token='abc', - ), - grafeas.ListNoteOccurrencesResponse( - occurrences=[], - next_page_token='def', - ), - grafeas.ListNoteOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - ], - next_page_token='ghi', - ), - grafeas.ListNoteOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(grafeas.ListNoteOccurrencesResponse.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 = {'name': 'projects/sample1/notes/sample2'} - - pager = client.list_note_occurrences(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, grafeas.Occurrence) - for i in results) - - pages = list(client.list_note_occurrences(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.GrafeasGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.GrafeasGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = GrafeasClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.GrafeasGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = GrafeasClient( - 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 = GrafeasClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.GrafeasGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = GrafeasClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.GrafeasGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = GrafeasClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.GrafeasGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.GrafeasGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.GrafeasGrpcTransport, - transports.GrafeasGrpcAsyncIOTransport, - transports.GrafeasRestTransport, -]) -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 = GrafeasClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = GrafeasClient( - 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_occurrence_empty_call_grpc(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_occurrence), - '__call__') as call: - call.return_value = grafeas.Occurrence() - client.get_occurrence(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.GetOccurrenceRequest() - - assert args[0] == request_msg - - -# This 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_occurrences_empty_call_grpc(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_occurrences), - '__call__') as call: - call.return_value = grafeas.ListOccurrencesResponse() - client.list_occurrences(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.ListOccurrencesRequest() - - assert args[0] == request_msg - - -# This 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_occurrence_empty_call_grpc(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_occurrence), - '__call__') as call: - call.return_value = None - client.delete_occurrence(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.DeleteOccurrenceRequest() - - assert args[0] == request_msg - - -# This 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_occurrence_empty_call_grpc(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_occurrence), - '__call__') as call: - call.return_value = grafeas.Occurrence() - client.create_occurrence(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.CreateOccurrenceRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_batch_create_occurrences_empty_call_grpc(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_occurrences), - '__call__') as call: - call.return_value = grafeas.BatchCreateOccurrencesResponse() - client.batch_create_occurrences(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.BatchCreateOccurrencesRequest() - - assert args[0] == request_msg - - -# This 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_occurrence_empty_call_grpc(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_occurrence), - '__call__') as call: - call.return_value = grafeas.Occurrence() - client.update_occurrence(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.UpdateOccurrenceRequest() - - assert args[0] == request_msg - - -# This 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_occurrence_note_empty_call_grpc(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_occurrence_note), - '__call__') as call: - call.return_value = grafeas.Note() - client.get_occurrence_note(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.GetOccurrenceNoteRequest() - - assert args[0] == request_msg - - -# This 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_note_empty_call_grpc(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_note), - '__call__') as call: - call.return_value = grafeas.Note() - client.get_note(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.GetNoteRequest() - - assert args[0] == request_msg - - -# This 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_notes_empty_call_grpc(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_notes), - '__call__') as call: - call.return_value = grafeas.ListNotesResponse() - client.list_notes(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.ListNotesRequest() - - assert args[0] == request_msg - - -# This 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_note_empty_call_grpc(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_note), - '__call__') as call: - call.return_value = None - client.delete_note(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.DeleteNoteRequest() - - assert args[0] == request_msg - - -# This 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_note_empty_call_grpc(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_note), - '__call__') as call: - call.return_value = grafeas.Note() - client.create_note(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.CreateNoteRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_batch_create_notes_empty_call_grpc(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_notes), - '__call__') as call: - call.return_value = grafeas.BatchCreateNotesResponse() - client.batch_create_notes(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.BatchCreateNotesRequest() - - assert args[0] == request_msg - - -# This 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_note_empty_call_grpc(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_note), - '__call__') as call: - call.return_value = grafeas.Note() - client.update_note(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.UpdateNoteRequest() - - assert args[0] == request_msg - - -# This 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_note_occurrences_empty_call_grpc(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_note_occurrences), - '__call__') as call: - call.return_value = grafeas.ListNoteOccurrencesResponse() - client.list_note_occurrences(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.ListNoteOccurrencesRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = GrafeasAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = GrafeasAsyncClient( - 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_occurrence_empty_call_grpc_asyncio(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_occurrence), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence( - name='name_value', - resource_uri='resource_uri_value', - note_name='note_name_value', - kind=common.NoteKind.VULNERABILITY, - remediation='remediation_value', - )) - await client.get_occurrence(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.GetOccurrenceRequest() - - assert args[0] == request_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_occurrences_empty_call_grpc_asyncio(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_occurrences), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.ListOccurrencesResponse( - next_page_token='next_page_token_value', - )) - await client.list_occurrences(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.ListOccurrencesRequest() - - assert args[0] == request_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_occurrence_empty_call_grpc_asyncio(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_occurrence), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_occurrence(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.DeleteOccurrenceRequest() - - assert args[0] == request_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_occurrence_empty_call_grpc_asyncio(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_occurrence), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence( - name='name_value', - resource_uri='resource_uri_value', - note_name='note_name_value', - kind=common.NoteKind.VULNERABILITY, - remediation='remediation_value', - )) - await client.create_occurrence(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.CreateOccurrenceRequest() - - assert args[0] == request_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_batch_create_occurrences_empty_call_grpc_asyncio(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_occurrences), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.BatchCreateOccurrencesResponse( - )) - await client.batch_create_occurrences(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.BatchCreateOccurrencesRequest() - - assert args[0] == request_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_occurrence_empty_call_grpc_asyncio(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_occurrence), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence( - name='name_value', - resource_uri='resource_uri_value', - note_name='note_name_value', - kind=common.NoteKind.VULNERABILITY, - remediation='remediation_value', - )) - await client.update_occurrence(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.UpdateOccurrenceRequest() - - assert args[0] == request_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_occurrence_note_empty_call_grpc_asyncio(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_occurrence_note), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note( - name='name_value', - short_description='short_description_value', - long_description='long_description_value', - kind=common.NoteKind.VULNERABILITY, - related_note_names=['related_note_names_value'], - )) - await client.get_occurrence_note(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.GetOccurrenceNoteRequest() - - assert args[0] == request_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_note_empty_call_grpc_asyncio(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_note), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note( - name='name_value', - short_description='short_description_value', - long_description='long_description_value', - kind=common.NoteKind.VULNERABILITY, - related_note_names=['related_note_names_value'], - )) - await client.get_note(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.GetNoteRequest() - - assert args[0] == request_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_notes_empty_call_grpc_asyncio(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_notes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.ListNotesResponse( - next_page_token='next_page_token_value', - )) - await client.list_notes(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.ListNotesRequest() - - assert args[0] == request_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_note_empty_call_grpc_asyncio(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_note), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_note(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.DeleteNoteRequest() - - assert args[0] == request_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_note_empty_call_grpc_asyncio(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_note), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note( - name='name_value', - short_description='short_description_value', - long_description='long_description_value', - kind=common.NoteKind.VULNERABILITY, - related_note_names=['related_note_names_value'], - )) - await client.create_note(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.CreateNoteRequest() - - assert args[0] == request_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_batch_create_notes_empty_call_grpc_asyncio(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_notes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.BatchCreateNotesResponse( - )) - await client.batch_create_notes(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.BatchCreateNotesRequest() - - assert args[0] == request_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_note_empty_call_grpc_asyncio(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_note), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note( - name='name_value', - short_description='short_description_value', - long_description='long_description_value', - kind=common.NoteKind.VULNERABILITY, - related_note_names=['related_note_names_value'], - )) - await client.update_note(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.UpdateNoteRequest() - - assert args[0] == request_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_note_occurrences_empty_call_grpc_asyncio(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_note_occurrences), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.ListNoteOccurrencesResponse( - next_page_token='next_page_token_value', - )) - await client.list_note_occurrences(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.ListNoteOccurrencesRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = GrafeasClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_get_occurrence_rest_bad_request(request_type=grafeas.GetOccurrenceRequest): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/occurrences/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_occurrence(request) - - -@pytest.mark.parametrize("request_type", [ - grafeas.GetOccurrenceRequest, - dict, -]) -def test_get_occurrence_rest_call_success(request_type): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/occurrences/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 = grafeas.Occurrence( - name='name_value', - resource_uri='resource_uri_value', - note_name='note_name_value', - kind=common.NoteKind.VULNERABILITY, - remediation='remediation_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 = grafeas.Occurrence.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_occurrence(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Occurrence) - assert response.name == 'name_value' - assert response.resource_uri == 'resource_uri_value' - assert response.note_name == 'note_name_value' - assert response.kind == common.NoteKind.VULNERABILITY - assert response.remediation == 'remediation_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_occurrence_rest_interceptors(null_interceptor): - transport = transports.GrafeasRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), - ) - client = GrafeasClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.GrafeasRestInterceptor, "post_get_occurrence") as post, \ - mock.patch.object(transports.GrafeasRestInterceptor, "pre_get_occurrence") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = grafeas.GetOccurrenceRequest.pb(grafeas.GetOccurrenceRequest()) - 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 = grafeas.Occurrence.to_json(grafeas.Occurrence()) - req.return_value.content = return_value - - request = grafeas.GetOccurrenceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = grafeas.Occurrence() - - client.get_occurrence(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_occurrences_rest_bad_request(request_type=grafeas.ListOccurrencesRequest): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/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_occurrences(request) - - -@pytest.mark.parametrize("request_type", [ - grafeas.ListOccurrencesRequest, - dict, -]) -def test_list_occurrences_rest_call_success(request_type): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = grafeas.ListOccurrencesResponse( - 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 = grafeas.ListOccurrencesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_occurrences(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListOccurrencesPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_occurrences_rest_interceptors(null_interceptor): - transport = transports.GrafeasRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), - ) - client = GrafeasClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.GrafeasRestInterceptor, "post_list_occurrences") as post, \ - mock.patch.object(transports.GrafeasRestInterceptor, "pre_list_occurrences") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = grafeas.ListOccurrencesRequest.pb(grafeas.ListOccurrencesRequest()) - 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 = grafeas.ListOccurrencesResponse.to_json(grafeas.ListOccurrencesResponse()) - req.return_value.content = return_value - - request = grafeas.ListOccurrencesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = grafeas.ListOccurrencesResponse() - - client.list_occurrences(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_occurrence_rest_bad_request(request_type=grafeas.DeleteOccurrenceRequest): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/occurrences/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_occurrence(request) - - -@pytest.mark.parametrize("request_type", [ - grafeas.DeleteOccurrenceRequest, - dict, -]) -def test_delete_occurrence_rest_call_success(request_type): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/occurrences/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_occurrence(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_occurrence_rest_interceptors(null_interceptor): - transport = transports.GrafeasRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), - ) - client = GrafeasClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.GrafeasRestInterceptor, "pre_delete_occurrence") as pre: - pre.assert_not_called() - pb_message = grafeas.DeleteOccurrenceRequest.pb(grafeas.DeleteOccurrenceRequest()) - 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 = grafeas.DeleteOccurrenceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_occurrence(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_create_occurrence_rest_bad_request(request_type=grafeas.CreateOccurrenceRequest): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/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_occurrence(request) - - -@pytest.mark.parametrize("request_type", [ - grafeas.CreateOccurrenceRequest, - dict, -]) -def test_create_occurrence_rest_call_success(request_type): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request_init["occurrence"] = {'name': 'name_value', 'resource_uri': 'resource_uri_value', 'note_name': 'note_name_value', 'kind': 1, 'remediation': 'remediation_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'vulnerability': {'type_': 'type__value', 'severity': 1, 'cvss_score': 0.1082, 'cvssv3': {'base_score': 0.1046, 'exploitability_score': 0.21580000000000002, 'impact_score': 0.1273, 'attack_vector': 1, 'attack_complexity': 1, 'authentication': 1, 'privileges_required': 1, 'user_interaction': 1, 'scope': 1, 'confidentiality_impact': 1, 'integrity_impact': 1, 'availability_impact': 1}, 'package_issue': [{'affected_cpe_uri': 'affected_cpe_uri_value', 'affected_package': 'affected_package_value', 'affected_version': {'epoch': 527, 'name': 'name_value', 'revision': 'revision_value', 'inclusive': True, 'kind': 1, 'full_name': 'full_name_value'}, 'fixed_cpe_uri': 'fixed_cpe_uri_value', 'fixed_package': 'fixed_package_value', 'fixed_version': {}, 'fix_available': True, 'package_type': 'package_type_value', 'effective_severity': 1, 'file_location': [{'file_path': 'file_path_value'}]}], 'short_description': 'short_description_value', 'long_description': 'long_description_value', 'related_urls': [{'url': 'url_value', 'label': 'label_value'}], 'effective_severity': 1, 'fix_available': True, 'cvss_version': 1, 'cvss_v2': {}, 'vex_assessment': {'cve': 'cve_value', 'vulnerability_id': 'vulnerability_id_value', 'related_uris': {}, 'note_name': 'note_name_value', 'state': 1, 'impacts': ['impacts_value1', 'impacts_value2'], 'remediations': [{'remediation_type': 1, 'details': 'details_value', 'remediation_uri': {}}], 'justification': {'justification_type': 1, 'details': 'details_value'}}, 'extra_details': 'extra_details_value'}, 'build': {'provenance': {'id': 'id_value', 'project_id': 'project_id_value', 'commands': [{'name': 'name_value', 'env': ['env_value1', 'env_value2'], 'args': ['args_value1', 'args_value2'], 'dir_': 'dir__value', 'id': 'id_value', 'wait_for': ['wait_for_value1', 'wait_for_value2']}], 'built_artifacts': [{'checksum': 'checksum_value', 'id': 'id_value', 'names': ['names_value1', 'names_value2']}], 'create_time': {}, 'start_time': {}, 'end_time': {}, 'creator': 'creator_value', 'logs_uri': 'logs_uri_value', 'source_provenance': {'artifact_storage_source_uri': 'artifact_storage_source_uri_value', 'file_hashes': {}, 'context': {'cloud_repo': {'repo_id': {'project_repo_id': {'project_id': 'project_id_value', 'repo_name': 'repo_name_value'}, 'uid': 'uid_value'}, 'revision_id': 'revision_id_value', 'alias_context': {'kind': 1, 'name': 'name_value'}}, 'gerrit': {'host_uri': 'host_uri_value', 'gerrit_project': 'gerrit_project_value', 'revision_id': 'revision_id_value', 'alias_context': {}}, 'git': {'url': 'url_value', 'revision_id': 'revision_id_value'}, 'labels': {}}, 'additional_contexts': {}}, 'trigger_id': 'trigger_id_value', 'build_options': {}, 'builder_version': 'builder_version_value'}, 'provenance_bytes': 'provenance_bytes_value', 'intoto_provenance': {'builder_config': {'id': 'id_value'}, 'recipe': {'type_': 'type__value', 'defined_in_material': 1971, 'entry_point': 'entry_point_value', 'arguments': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}], 'environment': {}}, 'metadata': {'build_invocation_id': 'build_invocation_id_value', 'build_started_on': {}, 'build_finished_on': {}, 'completeness': {'arguments': True, 'environment': True, 'materials': True}, 'reproducible': True}, 'materials': ['materials_value1', 'materials_value2']}, 'intoto_statement': {'type_': 'type__value', 'subject': [{'name': 'name_value', 'digest': {}}], 'predicate_type': 'predicate_type_value', 'provenance': {}, 'slsa_provenance': {'builder': {'id': 'id_value'}, 'recipe': {'type_': 'type__value', 'defined_in_material': 1971, 'entry_point': 'entry_point_value', 'arguments': {}, 'environment': {}}, 'metadata': {'build_invocation_id': 'build_invocation_id_value', 'build_started_on': {}, 'build_finished_on': {}, 'completeness': {'arguments': True, 'environment': True, 'materials': True}, 'reproducible': True}, 'materials': [{'uri': 'uri_value', 'digest': {}}]}, 'slsa_provenance_zero_two': {'builder': {'id': 'id_value'}, 'build_type': 'build_type_value', 'invocation': {'config_source': {'uri': 'uri_value', 'digest': {}, 'entry_point': 'entry_point_value'}, 'parameters': {'fields': {}}, 'environment': {}}, 'build_config': {}, 'metadata': {'build_invocation_id': 'build_invocation_id_value', 'build_started_on': {}, 'build_finished_on': {}, 'completeness': {'parameters': True, 'environment': True, 'materials': True}, 'reproducible': True}, 'materials': [{'uri': 'uri_value', 'digest': {}}]}}, 'in_toto_slsa_provenance_v1': {'type_': 'type__value', 'subject': {}, 'predicate_type': 'predicate_type_value', 'predicate': {'build_definition': {'build_type': 'build_type_value', 'external_parameters': {}, 'internal_parameters': {}, 'resolved_dependencies': [{'name': 'name_value', 'uri': 'uri_value', 'digest': {}, 'content': b'content_blob', 'download_location': 'download_location_value', 'media_type': 'media_type_value', 'annotations': {}}]}, 'run_details': {'builder': {'id': 'id_value', 'version': {}, 'builder_dependencies': {}}, 'metadata': {'invocation_id': 'invocation_id_value', 'started_on': {}, 'finished_on': {}}, 'byproducts': {}}}}}, 'image': {'fingerprint': {'v1_name': 'v1_name_value', 'v2_blob': ['v2_blob_value1', 'v2_blob_value2'], 'v2_name': 'v2_name_value'}, 'distance': 843, 'layer_info': [{'directive': 'directive_value', 'arguments': 'arguments_value'}], 'base_resource_url': 'base_resource_url_value'}, 'package': {'name': 'name_value', 'location': [{'cpe_uri': 'cpe_uri_value', 'version': {}, 'path': 'path_value'}], 'package_type': 'package_type_value', 'cpe_uri': 'cpe_uri_value', 'architecture': 1, 'license_': {'expression': 'expression_value', 'comments': 'comments_value'}, 'version': {}}, 'deployment': {'user_email': 'user_email_value', 'deploy_time': {}, 'undeploy_time': {}, 'config': 'config_value', 'address': 'address_value', 'resource_uri': ['resource_uri_value1', 'resource_uri_value2'], 'platform': 1}, 'discovery': {'continuous_analysis': 1, 'analysis_status': 1, 'analysis_completed': {'analysis_type': ['analysis_type_value1', 'analysis_type_value2']}, 'analysis_error': [{'code': 411, 'message': 'message_value', 'details': {}}], 'analysis_status_error': {}, 'cpe': 'cpe_value', 'last_scan_time': {}, 'archive_time': {}, 'sbom_status': {'sbom_state': 1, 'error': 'error_value'}, 'vulnerability_attestation': {'last_attempt_time': {}, 'state': 1, 'error': 'error_value'}}, 'attestation': {'serialized_payload': b'serialized_payload_blob', 'signatures': [{'signature': b'signature_blob', 'public_key_id': 'public_key_id_value'}], 'jwts': [{'compact_jwt': 'compact_jwt_value'}]}, 'upgrade': {'package': 'package_value', 'parsed_version': {}, 'distribution': {'cpe_uri': 'cpe_uri_value', 'classification': 'classification_value', 'severity': 'severity_value', 'cve': ['cve_value1', 'cve_value2']}, 'windows_update': {'identity': {'update_id': 'update_id_value', 'revision': 879}, 'title': 'title_value', 'description': 'description_value', 'categories': [{'category_id': 'category_id_value', 'name': 'name_value'}], 'kb_article_ids': ['kb_article_ids_value1', 'kb_article_ids_value2'], 'support_url': 'support_url_value', 'last_published_timestamp': {}}}, 'compliance': {'non_compliant_files': [{'path': 'path_value', 'display_command': 'display_command_value', 'reason': 'reason_value'}], 'non_compliance_reason': 'non_compliance_reason_value', 'version': {'cpe_uri': 'cpe_uri_value', 'benchmark_document': 'benchmark_document_value', 'version': 'version_value'}}, 'dsse_attestation': {'envelope': {'payload': b'payload_blob', 'payload_type': 'payload_type_value', 'signatures': [{'sig': b'sig_blob', 'keyid': 'keyid_value'}]}, 'statement': {}}, 'sbom_reference': {'payload': {'type_': 'type__value', 'predicate_type': 'predicate_type_value', 'subject': {}, 'predicate': {'referrer_id': 'referrer_id_value', 'location': 'location_value', 'mime_type': 'mime_type_value', 'digest': {}}}, 'payload_type': 'payload_type_value', 'signatures': {}}, 'envelope': {}} - # 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 = grafeas.CreateOccurrenceRequest.meta.fields["occurrence"] - - 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["occurrence"].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["occurrence"][field])): - del request_init["occurrence"][field][i][subfield] - else: - del request_init["occurrence"][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 = grafeas.Occurrence( - name='name_value', - resource_uri='resource_uri_value', - note_name='note_name_value', - kind=common.NoteKind.VULNERABILITY, - remediation='remediation_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 = grafeas.Occurrence.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_occurrence(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Occurrence) - assert response.name == 'name_value' - assert response.resource_uri == 'resource_uri_value' - assert response.note_name == 'note_name_value' - assert response.kind == common.NoteKind.VULNERABILITY - assert response.remediation == 'remediation_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_occurrence_rest_interceptors(null_interceptor): - transport = transports.GrafeasRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), - ) - client = GrafeasClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.GrafeasRestInterceptor, "post_create_occurrence") as post, \ - mock.patch.object(transports.GrafeasRestInterceptor, "pre_create_occurrence") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = grafeas.CreateOccurrenceRequest.pb(grafeas.CreateOccurrenceRequest()) - 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 = grafeas.Occurrence.to_json(grafeas.Occurrence()) - req.return_value.content = return_value - - request = grafeas.CreateOccurrenceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = grafeas.Occurrence() - - client.create_occurrence(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_batch_create_occurrences_rest_bad_request(request_type=grafeas.BatchCreateOccurrencesRequest): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/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.batch_create_occurrences(request) - - -@pytest.mark.parametrize("request_type", [ - grafeas.BatchCreateOccurrencesRequest, - dict, -]) -def test_batch_create_occurrences_rest_call_success(request_type): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = grafeas.BatchCreateOccurrencesResponse( - ) - - # 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 = grafeas.BatchCreateOccurrencesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.batch_create_occurrences(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.BatchCreateOccurrencesResponse) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_create_occurrences_rest_interceptors(null_interceptor): - transport = transports.GrafeasRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), - ) - client = GrafeasClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.GrafeasRestInterceptor, "post_batch_create_occurrences") as post, \ - mock.patch.object(transports.GrafeasRestInterceptor, "pre_batch_create_occurrences") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = grafeas.BatchCreateOccurrencesRequest.pb(grafeas.BatchCreateOccurrencesRequest()) - 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 = grafeas.BatchCreateOccurrencesResponse.to_json(grafeas.BatchCreateOccurrencesResponse()) - req.return_value.content = return_value - - request = grafeas.BatchCreateOccurrencesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = grafeas.BatchCreateOccurrencesResponse() - - client.batch_create_occurrences(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_occurrence_rest_bad_request(request_type=grafeas.UpdateOccurrenceRequest): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/occurrences/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_occurrence(request) - - -@pytest.mark.parametrize("request_type", [ - grafeas.UpdateOccurrenceRequest, - dict, -]) -def test_update_occurrence_rest_call_success(request_type): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/occurrences/sample2'} - request_init["occurrence"] = {'name': 'name_value', 'resource_uri': 'resource_uri_value', 'note_name': 'note_name_value', 'kind': 1, 'remediation': 'remediation_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'vulnerability': {'type_': 'type__value', 'severity': 1, 'cvss_score': 0.1082, 'cvssv3': {'base_score': 0.1046, 'exploitability_score': 0.21580000000000002, 'impact_score': 0.1273, 'attack_vector': 1, 'attack_complexity': 1, 'authentication': 1, 'privileges_required': 1, 'user_interaction': 1, 'scope': 1, 'confidentiality_impact': 1, 'integrity_impact': 1, 'availability_impact': 1}, 'package_issue': [{'affected_cpe_uri': 'affected_cpe_uri_value', 'affected_package': 'affected_package_value', 'affected_version': {'epoch': 527, 'name': 'name_value', 'revision': 'revision_value', 'inclusive': True, 'kind': 1, 'full_name': 'full_name_value'}, 'fixed_cpe_uri': 'fixed_cpe_uri_value', 'fixed_package': 'fixed_package_value', 'fixed_version': {}, 'fix_available': True, 'package_type': 'package_type_value', 'effective_severity': 1, 'file_location': [{'file_path': 'file_path_value'}]}], 'short_description': 'short_description_value', 'long_description': 'long_description_value', 'related_urls': [{'url': 'url_value', 'label': 'label_value'}], 'effective_severity': 1, 'fix_available': True, 'cvss_version': 1, 'cvss_v2': {}, 'vex_assessment': {'cve': 'cve_value', 'vulnerability_id': 'vulnerability_id_value', 'related_uris': {}, 'note_name': 'note_name_value', 'state': 1, 'impacts': ['impacts_value1', 'impacts_value2'], 'remediations': [{'remediation_type': 1, 'details': 'details_value', 'remediation_uri': {}}], 'justification': {'justification_type': 1, 'details': 'details_value'}}, 'extra_details': 'extra_details_value'}, 'build': {'provenance': {'id': 'id_value', 'project_id': 'project_id_value', 'commands': [{'name': 'name_value', 'env': ['env_value1', 'env_value2'], 'args': ['args_value1', 'args_value2'], 'dir_': 'dir__value', 'id': 'id_value', 'wait_for': ['wait_for_value1', 'wait_for_value2']}], 'built_artifacts': [{'checksum': 'checksum_value', 'id': 'id_value', 'names': ['names_value1', 'names_value2']}], 'create_time': {}, 'start_time': {}, 'end_time': {}, 'creator': 'creator_value', 'logs_uri': 'logs_uri_value', 'source_provenance': {'artifact_storage_source_uri': 'artifact_storage_source_uri_value', 'file_hashes': {}, 'context': {'cloud_repo': {'repo_id': {'project_repo_id': {'project_id': 'project_id_value', 'repo_name': 'repo_name_value'}, 'uid': 'uid_value'}, 'revision_id': 'revision_id_value', 'alias_context': {'kind': 1, 'name': 'name_value'}}, 'gerrit': {'host_uri': 'host_uri_value', 'gerrit_project': 'gerrit_project_value', 'revision_id': 'revision_id_value', 'alias_context': {}}, 'git': {'url': 'url_value', 'revision_id': 'revision_id_value'}, 'labels': {}}, 'additional_contexts': {}}, 'trigger_id': 'trigger_id_value', 'build_options': {}, 'builder_version': 'builder_version_value'}, 'provenance_bytes': 'provenance_bytes_value', 'intoto_provenance': {'builder_config': {'id': 'id_value'}, 'recipe': {'type_': 'type__value', 'defined_in_material': 1971, 'entry_point': 'entry_point_value', 'arguments': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}], 'environment': {}}, 'metadata': {'build_invocation_id': 'build_invocation_id_value', 'build_started_on': {}, 'build_finished_on': {}, 'completeness': {'arguments': True, 'environment': True, 'materials': True}, 'reproducible': True}, 'materials': ['materials_value1', 'materials_value2']}, 'intoto_statement': {'type_': 'type__value', 'subject': [{'name': 'name_value', 'digest': {}}], 'predicate_type': 'predicate_type_value', 'provenance': {}, 'slsa_provenance': {'builder': {'id': 'id_value'}, 'recipe': {'type_': 'type__value', 'defined_in_material': 1971, 'entry_point': 'entry_point_value', 'arguments': {}, 'environment': {}}, 'metadata': {'build_invocation_id': 'build_invocation_id_value', 'build_started_on': {}, 'build_finished_on': {}, 'completeness': {'arguments': True, 'environment': True, 'materials': True}, 'reproducible': True}, 'materials': [{'uri': 'uri_value', 'digest': {}}]}, 'slsa_provenance_zero_two': {'builder': {'id': 'id_value'}, 'build_type': 'build_type_value', 'invocation': {'config_source': {'uri': 'uri_value', 'digest': {}, 'entry_point': 'entry_point_value'}, 'parameters': {'fields': {}}, 'environment': {}}, 'build_config': {}, 'metadata': {'build_invocation_id': 'build_invocation_id_value', 'build_started_on': {}, 'build_finished_on': {}, 'completeness': {'parameters': True, 'environment': True, 'materials': True}, 'reproducible': True}, 'materials': [{'uri': 'uri_value', 'digest': {}}]}}, 'in_toto_slsa_provenance_v1': {'type_': 'type__value', 'subject': {}, 'predicate_type': 'predicate_type_value', 'predicate': {'build_definition': {'build_type': 'build_type_value', 'external_parameters': {}, 'internal_parameters': {}, 'resolved_dependencies': [{'name': 'name_value', 'uri': 'uri_value', 'digest': {}, 'content': b'content_blob', 'download_location': 'download_location_value', 'media_type': 'media_type_value', 'annotations': {}}]}, 'run_details': {'builder': {'id': 'id_value', 'version': {}, 'builder_dependencies': {}}, 'metadata': {'invocation_id': 'invocation_id_value', 'started_on': {}, 'finished_on': {}}, 'byproducts': {}}}}}, 'image': {'fingerprint': {'v1_name': 'v1_name_value', 'v2_blob': ['v2_blob_value1', 'v2_blob_value2'], 'v2_name': 'v2_name_value'}, 'distance': 843, 'layer_info': [{'directive': 'directive_value', 'arguments': 'arguments_value'}], 'base_resource_url': 'base_resource_url_value'}, 'package': {'name': 'name_value', 'location': [{'cpe_uri': 'cpe_uri_value', 'version': {}, 'path': 'path_value'}], 'package_type': 'package_type_value', 'cpe_uri': 'cpe_uri_value', 'architecture': 1, 'license_': {'expression': 'expression_value', 'comments': 'comments_value'}, 'version': {}}, 'deployment': {'user_email': 'user_email_value', 'deploy_time': {}, 'undeploy_time': {}, 'config': 'config_value', 'address': 'address_value', 'resource_uri': ['resource_uri_value1', 'resource_uri_value2'], 'platform': 1}, 'discovery': {'continuous_analysis': 1, 'analysis_status': 1, 'analysis_completed': {'analysis_type': ['analysis_type_value1', 'analysis_type_value2']}, 'analysis_error': [{'code': 411, 'message': 'message_value', 'details': {}}], 'analysis_status_error': {}, 'cpe': 'cpe_value', 'last_scan_time': {}, 'archive_time': {}, 'sbom_status': {'sbom_state': 1, 'error': 'error_value'}, 'vulnerability_attestation': {'last_attempt_time': {}, 'state': 1, 'error': 'error_value'}}, 'attestation': {'serialized_payload': b'serialized_payload_blob', 'signatures': [{'signature': b'signature_blob', 'public_key_id': 'public_key_id_value'}], 'jwts': [{'compact_jwt': 'compact_jwt_value'}]}, 'upgrade': {'package': 'package_value', 'parsed_version': {}, 'distribution': {'cpe_uri': 'cpe_uri_value', 'classification': 'classification_value', 'severity': 'severity_value', 'cve': ['cve_value1', 'cve_value2']}, 'windows_update': {'identity': {'update_id': 'update_id_value', 'revision': 879}, 'title': 'title_value', 'description': 'description_value', 'categories': [{'category_id': 'category_id_value', 'name': 'name_value'}], 'kb_article_ids': ['kb_article_ids_value1', 'kb_article_ids_value2'], 'support_url': 'support_url_value', 'last_published_timestamp': {}}}, 'compliance': {'non_compliant_files': [{'path': 'path_value', 'display_command': 'display_command_value', 'reason': 'reason_value'}], 'non_compliance_reason': 'non_compliance_reason_value', 'version': {'cpe_uri': 'cpe_uri_value', 'benchmark_document': 'benchmark_document_value', 'version': 'version_value'}}, 'dsse_attestation': {'envelope': {'payload': b'payload_blob', 'payload_type': 'payload_type_value', 'signatures': [{'sig': b'sig_blob', 'keyid': 'keyid_value'}]}, 'statement': {}}, 'sbom_reference': {'payload': {'type_': 'type__value', 'predicate_type': 'predicate_type_value', 'subject': {}, 'predicate': {'referrer_id': 'referrer_id_value', 'location': 'location_value', 'mime_type': 'mime_type_value', 'digest': {}}}, 'payload_type': 'payload_type_value', 'signatures': {}}, 'envelope': {}} - # 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 = grafeas.UpdateOccurrenceRequest.meta.fields["occurrence"] - - 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["occurrence"].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["occurrence"][field])): - del request_init["occurrence"][field][i][subfield] - else: - del request_init["occurrence"][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 = grafeas.Occurrence( - name='name_value', - resource_uri='resource_uri_value', - note_name='note_name_value', - kind=common.NoteKind.VULNERABILITY, - remediation='remediation_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 = grafeas.Occurrence.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_occurrence(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Occurrence) - assert response.name == 'name_value' - assert response.resource_uri == 'resource_uri_value' - assert response.note_name == 'note_name_value' - assert response.kind == common.NoteKind.VULNERABILITY - assert response.remediation == 'remediation_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_occurrence_rest_interceptors(null_interceptor): - transport = transports.GrafeasRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), - ) - client = GrafeasClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.GrafeasRestInterceptor, "post_update_occurrence") as post, \ - mock.patch.object(transports.GrafeasRestInterceptor, "pre_update_occurrence") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = grafeas.UpdateOccurrenceRequest.pb(grafeas.UpdateOccurrenceRequest()) - 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 = grafeas.Occurrence.to_json(grafeas.Occurrence()) - req.return_value.content = return_value - - request = grafeas.UpdateOccurrenceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = grafeas.Occurrence() - - client.update_occurrence(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_occurrence_note_rest_bad_request(request_type=grafeas.GetOccurrenceNoteRequest): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/occurrences/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_occurrence_note(request) - - -@pytest.mark.parametrize("request_type", [ - grafeas.GetOccurrenceNoteRequest, - dict, -]) -def test_get_occurrence_note_rest_call_success(request_type): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/occurrences/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 = grafeas.Note( - name='name_value', - short_description='short_description_value', - long_description='long_description_value', - kind=common.NoteKind.VULNERABILITY, - related_note_names=['related_note_names_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 = grafeas.Note.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_occurrence_note(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Note) - assert response.name == 'name_value' - assert response.short_description == 'short_description_value' - assert response.long_description == 'long_description_value' - assert response.kind == common.NoteKind.VULNERABILITY - assert response.related_note_names == ['related_note_names_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_occurrence_note_rest_interceptors(null_interceptor): - transport = transports.GrafeasRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), - ) - client = GrafeasClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.GrafeasRestInterceptor, "post_get_occurrence_note") as post, \ - mock.patch.object(transports.GrafeasRestInterceptor, "pre_get_occurrence_note") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = grafeas.GetOccurrenceNoteRequest.pb(grafeas.GetOccurrenceNoteRequest()) - 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 = grafeas.Note.to_json(grafeas.Note()) - req.return_value.content = return_value - - request = grafeas.GetOccurrenceNoteRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = grafeas.Note() - - client.get_occurrence_note(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_note_rest_bad_request(request_type=grafeas.GetNoteRequest): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/notes/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_note(request) - - -@pytest.mark.parametrize("request_type", [ - grafeas.GetNoteRequest, - dict, -]) -def test_get_note_rest_call_success(request_type): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/notes/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 = grafeas.Note( - name='name_value', - short_description='short_description_value', - long_description='long_description_value', - kind=common.NoteKind.VULNERABILITY, - related_note_names=['related_note_names_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 = grafeas.Note.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_note(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Note) - assert response.name == 'name_value' - assert response.short_description == 'short_description_value' - assert response.long_description == 'long_description_value' - assert response.kind == common.NoteKind.VULNERABILITY - assert response.related_note_names == ['related_note_names_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_note_rest_interceptors(null_interceptor): - transport = transports.GrafeasRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), - ) - client = GrafeasClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.GrafeasRestInterceptor, "post_get_note") as post, \ - mock.patch.object(transports.GrafeasRestInterceptor, "pre_get_note") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = grafeas.GetNoteRequest.pb(grafeas.GetNoteRequest()) - 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 = grafeas.Note.to_json(grafeas.Note()) - req.return_value.content = return_value - - request = grafeas.GetNoteRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = grafeas.Note() - - client.get_note(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_notes_rest_bad_request(request_type=grafeas.ListNotesRequest): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/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_notes(request) - - -@pytest.mark.parametrize("request_type", [ - grafeas.ListNotesRequest, - dict, -]) -def test_list_notes_rest_call_success(request_type): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = grafeas.ListNotesResponse( - 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 = grafeas.ListNotesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_notes(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNotesPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_notes_rest_interceptors(null_interceptor): - transport = transports.GrafeasRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), - ) - client = GrafeasClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.GrafeasRestInterceptor, "post_list_notes") as post, \ - mock.patch.object(transports.GrafeasRestInterceptor, "pre_list_notes") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = grafeas.ListNotesRequest.pb(grafeas.ListNotesRequest()) - 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 = grafeas.ListNotesResponse.to_json(grafeas.ListNotesResponse()) - req.return_value.content = return_value - - request = grafeas.ListNotesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = grafeas.ListNotesResponse() - - client.list_notes(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_note_rest_bad_request(request_type=grafeas.DeleteNoteRequest): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/notes/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_note(request) - - -@pytest.mark.parametrize("request_type", [ - grafeas.DeleteNoteRequest, - dict, -]) -def test_delete_note_rest_call_success(request_type): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/notes/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_note(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_note_rest_interceptors(null_interceptor): - transport = transports.GrafeasRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), - ) - client = GrafeasClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.GrafeasRestInterceptor, "pre_delete_note") as pre: - pre.assert_not_called() - pb_message = grafeas.DeleteNoteRequest.pb(grafeas.DeleteNoteRequest()) - 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 = grafeas.DeleteNoteRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_note(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_create_note_rest_bad_request(request_type=grafeas.CreateNoteRequest): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/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_note(request) - - -@pytest.mark.parametrize("request_type", [ - grafeas.CreateNoteRequest, - dict, -]) -def test_create_note_rest_call_success(request_type): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request_init["note"] = {'name': 'name_value', 'short_description': 'short_description_value', 'long_description': 'long_description_value', 'kind': 1, 'related_url': [{'url': 'url_value', 'label': 'label_value'}], 'expiration_time': {'seconds': 751, 'nanos': 543}, 'create_time': {}, 'update_time': {}, 'related_note_names': ['related_note_names_value1', 'related_note_names_value2'], 'vulnerability': {'cvss_score': 0.1082, 'severity': 1, 'details': [{'severity_name': 'severity_name_value', 'description': 'description_value', 'package_type': 'package_type_value', 'affected_cpe_uri': 'affected_cpe_uri_value', 'affected_package': 'affected_package_value', 'affected_version_start': {'epoch': 527, 'name': 'name_value', 'revision': 'revision_value', 'inclusive': True, 'kind': 1, 'full_name': 'full_name_value'}, 'affected_version_end': {}, 'fixed_cpe_uri': 'fixed_cpe_uri_value', 'fixed_package': 'fixed_package_value', 'fixed_version': {}, 'is_obsolete': True, 'source_update_time': {}, 'source': 'source_value', 'vendor': 'vendor_value'}], 'cvss_v3': {'base_score': 0.1046, 'exploitability_score': 0.21580000000000002, 'impact_score': 0.1273, 'attack_vector': 1, 'attack_complexity': 1, 'privileges_required': 1, 'user_interaction': 1, 'scope': 1, 'confidentiality_impact': 1, 'integrity_impact': 1, 'availability_impact': 1}, 'windows_details': [{'cpe_uri': 'cpe_uri_value', 'name': 'name_value', 'description': 'description_value', 'fixing_kbs': [{'name': 'name_value', 'url': 'url_value'}]}], 'source_update_time': {}, 'cvss_version': 1, 'cvss_v2': {'base_score': 0.1046, 'exploitability_score': 0.21580000000000002, 'impact_score': 0.1273, 'attack_vector': 1, 'attack_complexity': 1, 'authentication': 1, 'privileges_required': 1, 'user_interaction': 1, 'scope': 1, 'confidentiality_impact': 1, 'integrity_impact': 1, 'availability_impact': 1}}, 'build': {'builder_version': 'builder_version_value'}, 'image': {'resource_url': 'resource_url_value', 'fingerprint': {'v1_name': 'v1_name_value', 'v2_blob': ['v2_blob_value1', 'v2_blob_value2'], 'v2_name': 'v2_name_value'}}, 'package': {'name': 'name_value', 'distribution': [{'cpe_uri': 'cpe_uri_value', 'architecture': 1, 'latest_version': {}, 'maintainer': 'maintainer_value', 'url': 'url_value', 'description': 'description_value'}], 'package_type': 'package_type_value', 'cpe_uri': 'cpe_uri_value', 'architecture': 1, 'version': {}, 'maintainer': 'maintainer_value', 'url': 'url_value', 'description': 'description_value', 'license_': {'expression': 'expression_value', 'comments': 'comments_value'}, 'digest': [{'algo': 'algo_value', 'digest_bytes': b'digest_bytes_blob'}]}, 'deployment': {'resource_uri': ['resource_uri_value1', 'resource_uri_value2']}, 'discovery': {'analysis_kind': 1}, 'attestation': {'hint': {'human_readable_name': 'human_readable_name_value'}}, 'upgrade': {'package': 'package_value', 'version': {}, 'distributions': [{'cpe_uri': 'cpe_uri_value', 'classification': 'classification_value', 'severity': 'severity_value', 'cve': ['cve_value1', 'cve_value2']}], 'windows_update': {'identity': {'update_id': 'update_id_value', 'revision': 879}, 'title': 'title_value', 'description': 'description_value', 'categories': [{'category_id': 'category_id_value', 'name': 'name_value'}], 'kb_article_ids': ['kb_article_ids_value1', 'kb_article_ids_value2'], 'support_url': 'support_url_value', 'last_published_timestamp': {}}}, 'compliance': {'title': 'title_value', 'description': 'description_value', 'version': [{'cpe_uri': 'cpe_uri_value', 'benchmark_document': 'benchmark_document_value', 'version': 'version_value'}], 'rationale': 'rationale_value', 'remediation': 'remediation_value', 'cis_benchmark': {'profile_level': 1384, 'severity': 1}, 'scan_instructions': b'scan_instructions_blob', 'impact': 'impact_value'}, 'dsse_attestation': {'hint': {'human_readable_name': 'human_readable_name_value'}}, 'vulnerability_assessment': {'title': 'title_value', 'short_description': 'short_description_value', 'long_description': 'long_description_value', 'language_code': 'language_code_value', 'publisher': {'name': 'name_value', 'issuing_authority': 'issuing_authority_value', 'publisher_namespace': 'publisher_namespace_value'}, 'product': {'name': 'name_value', 'id': 'id_value', 'generic_uri': 'generic_uri_value'}, 'assessment': {'cve': 'cve_value', 'vulnerability_id': 'vulnerability_id_value', 'short_description': 'short_description_value', 'long_description': 'long_description_value', 'related_uris': {}, 'state': 1, 'impacts': ['impacts_value1', 'impacts_value2'], 'justification': {'justification_type': 1, 'details': 'details_value'}, 'remediations': [{'remediation_type': 1, 'details': 'details_value', 'remediation_uri': {}}]}}, 'sbom_reference': {'format_': 'format__value', 'version': 'version_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 = grafeas.CreateNoteRequest.meta.fields["note"] - - 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["note"].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["note"][field])): - del request_init["note"][field][i][subfield] - else: - del request_init["note"][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 = grafeas.Note( - name='name_value', - short_description='short_description_value', - long_description='long_description_value', - kind=common.NoteKind.VULNERABILITY, - related_note_names=['related_note_names_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 = grafeas.Note.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_note(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Note) - assert response.name == 'name_value' - assert response.short_description == 'short_description_value' - assert response.long_description == 'long_description_value' - assert response.kind == common.NoteKind.VULNERABILITY - assert response.related_note_names == ['related_note_names_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_note_rest_interceptors(null_interceptor): - transport = transports.GrafeasRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), - ) - client = GrafeasClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.GrafeasRestInterceptor, "post_create_note") as post, \ - mock.patch.object(transports.GrafeasRestInterceptor, "pre_create_note") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = grafeas.CreateNoteRequest.pb(grafeas.CreateNoteRequest()) - 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 = grafeas.Note.to_json(grafeas.Note()) - req.return_value.content = return_value - - request = grafeas.CreateNoteRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = grafeas.Note() - - client.create_note(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_batch_create_notes_rest_bad_request(request_type=grafeas.BatchCreateNotesRequest): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/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.batch_create_notes(request) - - -@pytest.mark.parametrize("request_type", [ - grafeas.BatchCreateNotesRequest, - dict, -]) -def test_batch_create_notes_rest_call_success(request_type): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = grafeas.BatchCreateNotesResponse( - ) - - # 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 = grafeas.BatchCreateNotesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.batch_create_notes(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.BatchCreateNotesResponse) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_create_notes_rest_interceptors(null_interceptor): - transport = transports.GrafeasRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), - ) - client = GrafeasClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.GrafeasRestInterceptor, "post_batch_create_notes") as post, \ - mock.patch.object(transports.GrafeasRestInterceptor, "pre_batch_create_notes") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = grafeas.BatchCreateNotesRequest.pb(grafeas.BatchCreateNotesRequest()) - 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 = grafeas.BatchCreateNotesResponse.to_json(grafeas.BatchCreateNotesResponse()) - req.return_value.content = return_value - - request = grafeas.BatchCreateNotesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = grafeas.BatchCreateNotesResponse() - - client.batch_create_notes(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_note_rest_bad_request(request_type=grafeas.UpdateNoteRequest): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/notes/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_note(request) - - -@pytest.mark.parametrize("request_type", [ - grafeas.UpdateNoteRequest, - dict, -]) -def test_update_note_rest_call_success(request_type): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/notes/sample2'} - request_init["note"] = {'name': 'name_value', 'short_description': 'short_description_value', 'long_description': 'long_description_value', 'kind': 1, 'related_url': [{'url': 'url_value', 'label': 'label_value'}], 'expiration_time': {'seconds': 751, 'nanos': 543}, 'create_time': {}, 'update_time': {}, 'related_note_names': ['related_note_names_value1', 'related_note_names_value2'], 'vulnerability': {'cvss_score': 0.1082, 'severity': 1, 'details': [{'severity_name': 'severity_name_value', 'description': 'description_value', 'package_type': 'package_type_value', 'affected_cpe_uri': 'affected_cpe_uri_value', 'affected_package': 'affected_package_value', 'affected_version_start': {'epoch': 527, 'name': 'name_value', 'revision': 'revision_value', 'inclusive': True, 'kind': 1, 'full_name': 'full_name_value'}, 'affected_version_end': {}, 'fixed_cpe_uri': 'fixed_cpe_uri_value', 'fixed_package': 'fixed_package_value', 'fixed_version': {}, 'is_obsolete': True, 'source_update_time': {}, 'source': 'source_value', 'vendor': 'vendor_value'}], 'cvss_v3': {'base_score': 0.1046, 'exploitability_score': 0.21580000000000002, 'impact_score': 0.1273, 'attack_vector': 1, 'attack_complexity': 1, 'privileges_required': 1, 'user_interaction': 1, 'scope': 1, 'confidentiality_impact': 1, 'integrity_impact': 1, 'availability_impact': 1}, 'windows_details': [{'cpe_uri': 'cpe_uri_value', 'name': 'name_value', 'description': 'description_value', 'fixing_kbs': [{'name': 'name_value', 'url': 'url_value'}]}], 'source_update_time': {}, 'cvss_version': 1, 'cvss_v2': {'base_score': 0.1046, 'exploitability_score': 0.21580000000000002, 'impact_score': 0.1273, 'attack_vector': 1, 'attack_complexity': 1, 'authentication': 1, 'privileges_required': 1, 'user_interaction': 1, 'scope': 1, 'confidentiality_impact': 1, 'integrity_impact': 1, 'availability_impact': 1}}, 'build': {'builder_version': 'builder_version_value'}, 'image': {'resource_url': 'resource_url_value', 'fingerprint': {'v1_name': 'v1_name_value', 'v2_blob': ['v2_blob_value1', 'v2_blob_value2'], 'v2_name': 'v2_name_value'}}, 'package': {'name': 'name_value', 'distribution': [{'cpe_uri': 'cpe_uri_value', 'architecture': 1, 'latest_version': {}, 'maintainer': 'maintainer_value', 'url': 'url_value', 'description': 'description_value'}], 'package_type': 'package_type_value', 'cpe_uri': 'cpe_uri_value', 'architecture': 1, 'version': {}, 'maintainer': 'maintainer_value', 'url': 'url_value', 'description': 'description_value', 'license_': {'expression': 'expression_value', 'comments': 'comments_value'}, 'digest': [{'algo': 'algo_value', 'digest_bytes': b'digest_bytes_blob'}]}, 'deployment': {'resource_uri': ['resource_uri_value1', 'resource_uri_value2']}, 'discovery': {'analysis_kind': 1}, 'attestation': {'hint': {'human_readable_name': 'human_readable_name_value'}}, 'upgrade': {'package': 'package_value', 'version': {}, 'distributions': [{'cpe_uri': 'cpe_uri_value', 'classification': 'classification_value', 'severity': 'severity_value', 'cve': ['cve_value1', 'cve_value2']}], 'windows_update': {'identity': {'update_id': 'update_id_value', 'revision': 879}, 'title': 'title_value', 'description': 'description_value', 'categories': [{'category_id': 'category_id_value', 'name': 'name_value'}], 'kb_article_ids': ['kb_article_ids_value1', 'kb_article_ids_value2'], 'support_url': 'support_url_value', 'last_published_timestamp': {}}}, 'compliance': {'title': 'title_value', 'description': 'description_value', 'version': [{'cpe_uri': 'cpe_uri_value', 'benchmark_document': 'benchmark_document_value', 'version': 'version_value'}], 'rationale': 'rationale_value', 'remediation': 'remediation_value', 'cis_benchmark': {'profile_level': 1384, 'severity': 1}, 'scan_instructions': b'scan_instructions_blob', 'impact': 'impact_value'}, 'dsse_attestation': {'hint': {'human_readable_name': 'human_readable_name_value'}}, 'vulnerability_assessment': {'title': 'title_value', 'short_description': 'short_description_value', 'long_description': 'long_description_value', 'language_code': 'language_code_value', 'publisher': {'name': 'name_value', 'issuing_authority': 'issuing_authority_value', 'publisher_namespace': 'publisher_namespace_value'}, 'product': {'name': 'name_value', 'id': 'id_value', 'generic_uri': 'generic_uri_value'}, 'assessment': {'cve': 'cve_value', 'vulnerability_id': 'vulnerability_id_value', 'short_description': 'short_description_value', 'long_description': 'long_description_value', 'related_uris': {}, 'state': 1, 'impacts': ['impacts_value1', 'impacts_value2'], 'justification': {'justification_type': 1, 'details': 'details_value'}, 'remediations': [{'remediation_type': 1, 'details': 'details_value', 'remediation_uri': {}}]}}, 'sbom_reference': {'format_': 'format__value', 'version': 'version_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 = grafeas.UpdateNoteRequest.meta.fields["note"] - - 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["note"].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["note"][field])): - del request_init["note"][field][i][subfield] - else: - del request_init["note"][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 = grafeas.Note( - name='name_value', - short_description='short_description_value', - long_description='long_description_value', - kind=common.NoteKind.VULNERABILITY, - related_note_names=['related_note_names_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 = grafeas.Note.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_note(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Note) - assert response.name == 'name_value' - assert response.short_description == 'short_description_value' - assert response.long_description == 'long_description_value' - assert response.kind == common.NoteKind.VULNERABILITY - assert response.related_note_names == ['related_note_names_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_note_rest_interceptors(null_interceptor): - transport = transports.GrafeasRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), - ) - client = GrafeasClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.GrafeasRestInterceptor, "post_update_note") as post, \ - mock.patch.object(transports.GrafeasRestInterceptor, "pre_update_note") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = grafeas.UpdateNoteRequest.pb(grafeas.UpdateNoteRequest()) - 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 = grafeas.Note.to_json(grafeas.Note()) - req.return_value.content = return_value - - request = grafeas.UpdateNoteRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = grafeas.Note() - - client.update_note(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_note_occurrences_rest_bad_request(request_type=grafeas.ListNoteOccurrencesRequest): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/notes/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_note_occurrences(request) - - -@pytest.mark.parametrize("request_type", [ - grafeas.ListNoteOccurrencesRequest, - dict, -]) -def test_list_note_occurrences_rest_call_success(request_type): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/notes/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 = grafeas.ListNoteOccurrencesResponse( - 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 = grafeas.ListNoteOccurrencesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_note_occurrences(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNoteOccurrencesPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_note_occurrences_rest_interceptors(null_interceptor): - transport = transports.GrafeasRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), - ) - client = GrafeasClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.GrafeasRestInterceptor, "post_list_note_occurrences") as post, \ - mock.patch.object(transports.GrafeasRestInterceptor, "pre_list_note_occurrences") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = grafeas.ListNoteOccurrencesRequest.pb(grafeas.ListNoteOccurrencesRequest()) - 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 = grafeas.ListNoteOccurrencesResponse.to_json(grafeas.ListNoteOccurrencesResponse()) - req.return_value.content = return_value - - request = grafeas.ListNoteOccurrencesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = grafeas.ListNoteOccurrencesResponse() - - client.list_note_occurrences(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - -def test_initialize_client_w_rest(): - client = GrafeasClient( - 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_occurrence_empty_call_rest(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_occurrence), - '__call__') as call: - client.get_occurrence(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.GetOccurrenceRequest() - - assert args[0] == request_msg - - -# This 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_occurrences_empty_call_rest(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_occurrences), - '__call__') as call: - client.list_occurrences(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.ListOccurrencesRequest() - - assert args[0] == request_msg - - -# This 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_occurrence_empty_call_rest(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_occurrence), - '__call__') as call: - client.delete_occurrence(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.DeleteOccurrenceRequest() - - assert args[0] == request_msg - - -# This 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_occurrence_empty_call_rest(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_occurrence), - '__call__') as call: - client.create_occurrence(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.CreateOccurrenceRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_batch_create_occurrences_empty_call_rest(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_occurrences), - '__call__') as call: - client.batch_create_occurrences(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.BatchCreateOccurrencesRequest() - - assert args[0] == request_msg - - -# This 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_occurrence_empty_call_rest(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_occurrence), - '__call__') as call: - client.update_occurrence(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.UpdateOccurrenceRequest() - - assert args[0] == request_msg - - -# This 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_occurrence_note_empty_call_rest(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_occurrence_note), - '__call__') as call: - client.get_occurrence_note(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.GetOccurrenceNoteRequest() - - assert args[0] == request_msg - - -# This 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_note_empty_call_rest(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_note), - '__call__') as call: - client.get_note(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.GetNoteRequest() - - assert args[0] == request_msg - - -# This 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_notes_empty_call_rest(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_notes), - '__call__') as call: - client.list_notes(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.ListNotesRequest() - - assert args[0] == request_msg - - -# This 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_note_empty_call_rest(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_note), - '__call__') as call: - client.delete_note(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.DeleteNoteRequest() - - assert args[0] == request_msg - - -# This 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_note_empty_call_rest(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_note), - '__call__') as call: - client.create_note(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.CreateNoteRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_batch_create_notes_empty_call_rest(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_notes), - '__call__') as call: - client.batch_create_notes(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.BatchCreateNotesRequest() - - assert args[0] == request_msg - - -# This 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_note_empty_call_rest(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_note), - '__call__') as call: - client.update_note(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.UpdateNoteRequest() - - assert args[0] == request_msg - - -# This 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_note_occurrences_empty_call_rest(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_note_occurrences), - '__call__') as call: - client.list_note_occurrences(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.ListNoteOccurrencesRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.GrafeasGrpcTransport, - ) - -def test_grafeas_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.GrafeasTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_grafeas_base_transport(): - # Instantiate the base transport. - with mock.patch('grafeas.grafeas_v1.services.grafeas.transports.GrafeasTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.GrafeasTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'get_occurrence', - 'list_occurrences', - 'delete_occurrence', - 'create_occurrence', - 'batch_create_occurrences', - 'update_occurrence', - 'get_occurrence_note', - 'get_note', - 'list_notes', - 'delete_note', - 'create_note', - 'batch_create_notes', - 'update_note', - 'list_note_occurrences', - ) - 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_grafeas_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('grafeas.grafeas_v1.services.grafeas.transports.GrafeasTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.GrafeasTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( -), - quota_project_id="octopus", - ) - - -def test_grafeas_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('grafeas.grafeas_v1.services.grafeas.transports.GrafeasTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.GrafeasTransport() - adc.assert_called_once() - - -def test_grafeas_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) - GrafeasClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.GrafeasGrpcTransport, - transports.GrafeasGrpcAsyncIOTransport, - ], -) -def test_grafeas_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=(), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.GrafeasGrpcTransport, - transports.GrafeasGrpcAsyncIOTransport, - transports.GrafeasRestTransport, - ], -) -def test_grafeas_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.GrafeasGrpcTransport, grpc_helpers), - (transports.GrafeasGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_grafeas_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( - "containeranalysis.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( -), - scopes=["1", "2"], - default_host="containeranalysis.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.GrafeasGrpcTransport, transports.GrafeasGrpcAsyncIOTransport]) -def test_grafeas_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_grafeas_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.GrafeasRestTransport ( - 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_grafeas_host_no_port(transport_name): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='containeranalysis.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'containeranalysis.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://containeranalysis.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_grafeas_host_with_port(transport_name): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='containeranalysis.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'containeranalysis.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://containeranalysis.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_grafeas_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = GrafeasClient( - credentials=creds1, - transport=transport_name, - ) - client2 = GrafeasClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.get_occurrence._session - session2 = client2.transport.get_occurrence._session - assert session1 != session2 - session1 = client1.transport.list_occurrences._session - session2 = client2.transport.list_occurrences._session - assert session1 != session2 - session1 = client1.transport.delete_occurrence._session - session2 = client2.transport.delete_occurrence._session - assert session1 != session2 - session1 = client1.transport.create_occurrence._session - session2 = client2.transport.create_occurrence._session - assert session1 != session2 - session1 = client1.transport.batch_create_occurrences._session - session2 = client2.transport.batch_create_occurrences._session - assert session1 != session2 - session1 = client1.transport.update_occurrence._session - session2 = client2.transport.update_occurrence._session - assert session1 != session2 - session1 = client1.transport.get_occurrence_note._session - session2 = client2.transport.get_occurrence_note._session - assert session1 != session2 - session1 = client1.transport.get_note._session - session2 = client2.transport.get_note._session - assert session1 != session2 - session1 = client1.transport.list_notes._session - session2 = client2.transport.list_notes._session - assert session1 != session2 - session1 = client1.transport.delete_note._session - session2 = client2.transport.delete_note._session - assert session1 != session2 - session1 = client1.transport.create_note._session - session2 = client2.transport.create_note._session - assert session1 != session2 - session1 = client1.transport.batch_create_notes._session - session2 = client2.transport.batch_create_notes._session - assert session1 != session2 - session1 = client1.transport.update_note._session - session2 = client2.transport.update_note._session - assert session1 != session2 - session1 = client1.transport.list_note_occurrences._session - session2 = client2.transport.list_note_occurrences._session - assert session1 != session2 -def test_grafeas_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.GrafeasGrpcTransport( - 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_grafeas_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.GrafeasGrpcAsyncIOTransport( - 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.GrafeasGrpcTransport, transports.GrafeasGrpcAsyncIOTransport]) -def test_grafeas_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.GrafeasGrpcTransport, transports.GrafeasGrpcAsyncIOTransport]) -def test_grafeas_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_note_path(): - project = "squid" - note = "clam" - expected = "projects/{project}/notes/{note}".format(project=project, note=note, ) - actual = GrafeasClient.note_path(project, note) - assert expected == actual - - -def test_parse_note_path(): - expected = { - "project": "whelk", - "note": "octopus", - } - path = GrafeasClient.note_path(**expected) - - # Check that the path construction is reversible. - actual = GrafeasClient.parse_note_path(path) - assert expected == actual - -def test_occurrence_path(): - project = "oyster" - occurrence = "nudibranch" - expected = "projects/{project}/occurrences/{occurrence}".format(project=project, occurrence=occurrence, ) - actual = GrafeasClient.occurrence_path(project, occurrence) - assert expected == actual - - -def test_parse_occurrence_path(): - expected = { - "project": "cuttlefish", - "occurrence": "mussel", - } - path = GrafeasClient.occurrence_path(**expected) - - # Check that the path construction is reversible. - actual = GrafeasClient.parse_occurrence_path(path) - assert expected == actual - -def test_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = GrafeasClient.project_path(project) - assert expected == actual - - -def test_parse_project_path(): - expected = { - "project": "nautilus", - } - path = GrafeasClient.project_path(**expected) - - # Check that the path construction is reversible. - actual = GrafeasClient.parse_project_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = GrafeasClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "abalone", - } - path = GrafeasClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = GrafeasClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "squid" - expected = "folders/{folder}".format(folder=folder, ) - actual = GrafeasClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "clam", - } - path = GrafeasClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = GrafeasClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "whelk" - expected = "organizations/{organization}".format(organization=organization, ) - actual = GrafeasClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "octopus", - } - path = GrafeasClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = GrafeasClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "oyster" - expected = "projects/{project}".format(project=project, ) - actual = GrafeasClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nudibranch", - } - path = GrafeasClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = GrafeasClient.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 = GrafeasClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "winkle", - "location": "nautilus", - } - path = GrafeasClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = GrafeasClient.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.GrafeasTransport, '_prep_wrapped_messages') as prep: - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.GrafeasTransport, '_prep_wrapped_messages') as prep: - transport_class = GrafeasClient.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 = GrafeasClient( - 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 = GrafeasAsyncClient( - 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 = GrafeasClient( - 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 = GrafeasClient( - 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", [ - (GrafeasClient, transports.GrafeasGrpcTransport), - (GrafeasAsyncClient, transports.GrafeasGrpcAsyncIOTransport), -]) -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-maps-mapsplatformdatasets/google/maps/mapsplatformdatasets/gapic_version.py b/packages/google-maps-mapsplatformdatasets/google/maps/mapsplatformdatasets/gapic_version.py index aa5666b21197..558c8aab67c5 100644 --- a/packages/google-maps-mapsplatformdatasets/google/maps/mapsplatformdatasets/gapic_version.py +++ b/packages/google-maps-mapsplatformdatasets/google/maps/mapsplatformdatasets/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.4.4" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-maps-mapsplatformdatasets/google/maps/mapsplatformdatasets_v1/gapic_version.py b/packages/google-maps-mapsplatformdatasets/google/maps/mapsplatformdatasets_v1/gapic_version.py index aa5666b21197..558c8aab67c5 100644 --- a/packages/google-maps-mapsplatformdatasets/google/maps/mapsplatformdatasets_v1/gapic_version.py +++ b/packages/google-maps-mapsplatformdatasets/google/maps/mapsplatformdatasets_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.4.4" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-maps-mapsplatformdatasets/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/async_client.py b/packages/google-maps-mapsplatformdatasets/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/async_client.py index 515b3f3a7a64..ca22a4331ada 100644 --- a/packages/google-maps-mapsplatformdatasets/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/async_client.py +++ b/packages/google-maps-mapsplatformdatasets/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/async_client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import re from typing import ( Callable, @@ -56,6 +57,15 @@ from .transports.base import DEFAULT_CLIENT_INFO, MapsPlatformDatasetsTransport from .transports.grpc_asyncio import MapsPlatformDatasetsGrpcAsyncIOTransport +try: + from google.api_core import client_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 MapsPlatformDatasetsAsyncClient: """Service definition for the Maps Platform Datasets API.""" @@ -265,6 +275,28 @@ def __init__( client_info=client_info, ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsAsyncClient`.", + extra={ + "serviceName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "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.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "credentialsType": None, + }, + ) + async def create_dataset( self, request: Optional[ @@ -275,7 +307,7 @@ async def create_dataset( dataset: Optional[gmm_dataset.Dataset] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> gmm_dataset.Dataset: r"""Creates a new dataset for the specified project. @@ -326,8 +358,10 @@ async def sample_create_dataset(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.maps.mapsplatformdatasets_v1.types.Dataset: @@ -393,7 +427,7 @@ async def update_dataset_metadata( 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, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> gmm_dataset.Dataset: r"""Updates the metadata for the dataset. @@ -444,8 +478,10 @@ async def sample_update_dataset_metadata(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.maps.mapsplatformdatasets_v1.types.Dataset: @@ -510,7 +546,7 @@ async def get_dataset( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> dataset.Dataset: r"""Gets the dataset. @@ -561,8 +597,10 @@ async def sample_get_dataset(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.maps.mapsplatformdatasets_v1.types.Dataset: @@ -625,7 +663,7 @@ async def fetch_dataset_errors( dataset: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.FetchDatasetErrorsAsyncPager: r"""Gets all the errors of a dataset. @@ -670,8 +708,10 @@ async def sample_fetch_dataset_errors(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.maps.mapsplatformdatasets_v1.services.maps_platform_datasets.pagers.FetchDatasetErrorsAsyncPager: @@ -748,7 +788,7 @@ async def list_datasets( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListDatasetsAsyncPager: r"""Lists all the datasets for the specified project. @@ -794,8 +834,10 @@ async def sample_list_datasets(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.maps.mapsplatformdatasets_v1.services.maps_platform_datasets.pagers.ListDatasetsAsyncPager: @@ -872,7 +914,7 @@ async def delete_dataset( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: r"""Deletes the specified dataset. @@ -912,8 +954,10 @@ async def sample_delete_dataset(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 diff --git a/packages/google-maps-mapsplatformdatasets/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/client.py b/packages/google-maps-mapsplatformdatasets/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/client.py index 91dd506422a4..807d23c116a2 100644 --- a/packages/google-maps-mapsplatformdatasets/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/client.py +++ b/packages/google-maps-mapsplatformdatasets/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import os import re from typing import ( @@ -48,6 +49,15 @@ 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 timestamp_pb2 # type: ignore from google.rpc import status_pb2 # type: ignore @@ -584,6 +594,10 @@ def __init__( # 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( @@ -650,6 +664,29 @@ def __init__( 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.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient`.", + extra={ + "serviceName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "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.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "credentialsType": None, + }, + ) + def create_dataset( self, request: Optional[ @@ -660,7 +697,7 @@ def create_dataset( dataset: Optional[gmm_dataset.Dataset] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> gmm_dataset.Dataset: r"""Creates a new dataset for the specified project. @@ -711,8 +748,10 @@ def sample_create_dataset(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.maps.mapsplatformdatasets_v1.types.Dataset: @@ -775,7 +814,7 @@ def update_dataset_metadata( 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, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> gmm_dataset.Dataset: r"""Updates the metadata for the dataset. @@ -826,8 +865,10 @@ def sample_update_dataset_metadata(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.maps.mapsplatformdatasets_v1.types.Dataset: @@ -889,7 +930,7 @@ def get_dataset( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> dataset.Dataset: r"""Gets the dataset. @@ -940,8 +981,10 @@ def sample_get_dataset(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.maps.mapsplatformdatasets_v1.types.Dataset: @@ -1001,7 +1044,7 @@ def fetch_dataset_errors( dataset: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.FetchDatasetErrorsPager: r"""Gets all the errors of a dataset. @@ -1046,8 +1089,10 @@ def sample_fetch_dataset_errors(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.maps.mapsplatformdatasets_v1.services.maps_platform_datasets.pagers.FetchDatasetErrorsPager: @@ -1121,7 +1166,7 @@ def list_datasets( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListDatasetsPager: r"""Lists all the datasets for the specified project. @@ -1167,8 +1212,10 @@ def sample_list_datasets(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.maps.mapsplatformdatasets_v1.services.maps_platform_datasets.pagers.ListDatasetsPager: @@ -1242,7 +1289,7 @@ def delete_dataset( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: r"""Deletes the specified dataset. @@ -1282,8 +1329,10 @@ def sample_delete_dataset(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 diff --git a/packages/google-maps-mapsplatformdatasets/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/pagers.py b/packages/google-maps-mapsplatformdatasets/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/pagers.py index e2bec2262c51..57b61f338411 100644 --- a/packages/google-maps-mapsplatformdatasets/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/pagers.py +++ b/packages/google-maps-mapsplatformdatasets/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/pagers.py @@ -69,7 +69,7 @@ def __init__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiate the pager. @@ -83,8 +83,10 @@ def __init__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 = maps_platform_datasets.FetchDatasetErrorsRequest(request) @@ -145,7 +147,7 @@ def __init__( *, retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiates the pager. @@ -159,8 +161,10 @@ def __init__( 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 = maps_platform_datasets.FetchDatasetErrorsRequest(request) @@ -225,7 +229,7 @@ def __init__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiate the pager. @@ -239,8 +243,10 @@ def __init__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 = maps_platform_datasets.ListDatasetsRequest(request) @@ -299,7 +305,7 @@ def __init__( *, retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiates the pager. @@ -313,8 +319,10 @@ def __init__( 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 = maps_platform_datasets.ListDatasetsRequest(request) diff --git a/packages/google-maps-mapsplatformdatasets/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/grpc.py b/packages/google-maps-mapsplatformdatasets/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/grpc.py index 5c0532b541bf..48a7780d1b2e 100644 --- a/packages/google-maps-mapsplatformdatasets/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/grpc.py +++ b/packages/google-maps-mapsplatformdatasets/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/grpc.py @@ -13,6 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import json +import logging as std_logging +import pickle from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -21,7 +24,10 @@ 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.maps.mapsplatformdatasets_v1.types import dataset from google.maps.mapsplatformdatasets_v1.types import dataset as gmm_dataset @@ -29,6 +35,81 @@ from .base import DEFAULT_CLIENT_INFO, MapsPlatformDatasetsTransport +try: + from google.api_core import client_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.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "rpcName": 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.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + class MapsPlatformDatasetsGrpcTransport(MapsPlatformDatasetsTransport): """gRPC backend transport for MapsPlatformDatasets. @@ -182,7 +263,12 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -256,7 +342,7 @@ def create_dataset( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "create_dataset" not in self._stubs: - self._stubs["create_dataset"] = self.grpc_channel.unary_unary( + self._stubs["create_dataset"] = self._logged_channel.unary_unary( "/google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets/CreateDataset", request_serializer=maps_platform_datasets.CreateDatasetRequest.serialize, response_deserializer=gmm_dataset.Dataset.deserialize, @@ -284,7 +370,7 @@ def update_dataset_metadata( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "update_dataset_metadata" not in self._stubs: - self._stubs["update_dataset_metadata"] = self.grpc_channel.unary_unary( + self._stubs["update_dataset_metadata"] = self._logged_channel.unary_unary( "/google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets/UpdateDatasetMetadata", request_serializer=maps_platform_datasets.UpdateDatasetMetadataRequest.serialize, response_deserializer=gmm_dataset.Dataset.deserialize, @@ -310,7 +396,7 @@ def get_dataset( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_dataset" not in self._stubs: - self._stubs["get_dataset"] = self.grpc_channel.unary_unary( + self._stubs["get_dataset"] = self._logged_channel.unary_unary( "/google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets/GetDataset", request_serializer=maps_platform_datasets.GetDatasetRequest.serialize, response_deserializer=dataset.Dataset.deserialize, @@ -339,7 +425,7 @@ def fetch_dataset_errors( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "fetch_dataset_errors" not in self._stubs: - self._stubs["fetch_dataset_errors"] = self.grpc_channel.unary_unary( + self._stubs["fetch_dataset_errors"] = self._logged_channel.unary_unary( "/google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets/FetchDatasetErrors", request_serializer=maps_platform_datasets.FetchDatasetErrorsRequest.serialize, response_deserializer=maps_platform_datasets.FetchDatasetErrorsResponse.deserialize, @@ -368,7 +454,7 @@ def list_datasets( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_datasets" not in self._stubs: - self._stubs["list_datasets"] = self.grpc_channel.unary_unary( + self._stubs["list_datasets"] = self._logged_channel.unary_unary( "/google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets/ListDatasets", request_serializer=maps_platform_datasets.ListDatasetsRequest.serialize, response_deserializer=maps_platform_datasets.ListDatasetsResponse.deserialize, @@ -394,7 +480,7 @@ def delete_dataset( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "delete_dataset" not in self._stubs: - self._stubs["delete_dataset"] = self.grpc_channel.unary_unary( + self._stubs["delete_dataset"] = self._logged_channel.unary_unary( "/google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets/DeleteDataset", request_serializer=maps_platform_datasets.DeleteDatasetRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -402,7 +488,7 @@ def delete_dataset( return self._stubs["delete_dataset"] def close(self): - self.grpc_channel.close() + self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-maps-mapsplatformdatasets/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/grpc_asyncio.py b/packages/google-maps-mapsplatformdatasets/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/grpc_asyncio.py index cfea955fdf05..54dd547f486f 100644 --- a/packages/google-maps-mapsplatformdatasets/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/grpc_asyncio.py +++ b/packages/google-maps-mapsplatformdatasets/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/grpc_asyncio.py @@ -14,6 +14,9 @@ # limitations under the License. # import inspect +import json +import logging as std_logging +import pickle from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -23,8 +26,11 @@ 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 from grpc.experimental import aio # type: ignore +import proto # type: ignore from google.maps.mapsplatformdatasets_v1.types import dataset from google.maps.mapsplatformdatasets_v1.types import dataset as gmm_dataset @@ -33,6 +39,82 @@ from .base import DEFAULT_CLIENT_INFO, MapsPlatformDatasetsTransport from .grpc import MapsPlatformDatasetsGrpcTransport +try: + from google.api_core import client_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.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "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.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + class MapsPlatformDatasetsGrpcAsyncIOTransport(MapsPlatformDatasetsTransport): """gRPC AsyncIO backend transport for MapsPlatformDatasets. @@ -229,10 +311,13 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -266,7 +351,7 @@ def create_dataset( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "create_dataset" not in self._stubs: - self._stubs["create_dataset"] = self.grpc_channel.unary_unary( + self._stubs["create_dataset"] = self._logged_channel.unary_unary( "/google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets/CreateDataset", request_serializer=maps_platform_datasets.CreateDatasetRequest.serialize, response_deserializer=gmm_dataset.Dataset.deserialize, @@ -295,7 +380,7 @@ def update_dataset_metadata( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "update_dataset_metadata" not in self._stubs: - self._stubs["update_dataset_metadata"] = self.grpc_channel.unary_unary( + self._stubs["update_dataset_metadata"] = self._logged_channel.unary_unary( "/google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets/UpdateDatasetMetadata", request_serializer=maps_platform_datasets.UpdateDatasetMetadataRequest.serialize, response_deserializer=gmm_dataset.Dataset.deserialize, @@ -323,7 +408,7 @@ def get_dataset( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_dataset" not in self._stubs: - self._stubs["get_dataset"] = self.grpc_channel.unary_unary( + self._stubs["get_dataset"] = self._logged_channel.unary_unary( "/google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets/GetDataset", request_serializer=maps_platform_datasets.GetDatasetRequest.serialize, response_deserializer=dataset.Dataset.deserialize, @@ -352,7 +437,7 @@ def fetch_dataset_errors( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "fetch_dataset_errors" not in self._stubs: - self._stubs["fetch_dataset_errors"] = self.grpc_channel.unary_unary( + self._stubs["fetch_dataset_errors"] = self._logged_channel.unary_unary( "/google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets/FetchDatasetErrors", request_serializer=maps_platform_datasets.FetchDatasetErrorsRequest.serialize, response_deserializer=maps_platform_datasets.FetchDatasetErrorsResponse.deserialize, @@ -381,7 +466,7 @@ def list_datasets( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_datasets" not in self._stubs: - self._stubs["list_datasets"] = self.grpc_channel.unary_unary( + self._stubs["list_datasets"] = self._logged_channel.unary_unary( "/google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets/ListDatasets", request_serializer=maps_platform_datasets.ListDatasetsRequest.serialize, response_deserializer=maps_platform_datasets.ListDatasetsResponse.deserialize, @@ -409,7 +494,7 @@ def delete_dataset( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "delete_dataset" not in self._stubs: - self._stubs["delete_dataset"] = self.grpc_channel.unary_unary( + self._stubs["delete_dataset"] = self._logged_channel.unary_unary( "/google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets/DeleteDataset", request_serializer=maps_platform_datasets.DeleteDatasetRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -484,7 +569,7 @@ def _wrap_method(self, func, *args, **kwargs): return gapic_v1.method_async.wrap_method(func, *args, **kwargs) def close(self): - return self.grpc_channel.close() + return self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-maps-mapsplatformdatasets/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/rest.py b/packages/google-maps-mapsplatformdatasets/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/rest.py index 2264014d5ee6..081d4798e807 100644 --- a/packages/google-maps-mapsplatformdatasets/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/rest.py +++ b/packages/google-maps-mapsplatformdatasets/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/rest.py @@ -13,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import dataclasses import json # type: ignore +import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings @@ -40,6 +40,14 @@ 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, @@ -116,8 +124,11 @@ def post_update_dataset_metadata(self, response): def pre_create_dataset( self, request: maps_platform_datasets.CreateDatasetRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[maps_platform_datasets.CreateDatasetRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + maps_platform_datasets.CreateDatasetRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for create_dataset Override in a subclass to manipulate the request or metadata @@ -137,8 +148,11 @@ def post_create_dataset(self, response: gmm_dataset.Dataset) -> gmm_dataset.Data def pre_delete_dataset( self, request: maps_platform_datasets.DeleteDatasetRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[maps_platform_datasets.DeleteDatasetRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + maps_platform_datasets.DeleteDatasetRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for delete_dataset Override in a subclass to manipulate the request or metadata @@ -149,9 +163,10 @@ def pre_delete_dataset( def pre_fetch_dataset_errors( self, request: maps_platform_datasets.FetchDatasetErrorsRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - maps_platform_datasets.FetchDatasetErrorsRequest, Sequence[Tuple[str, str]] + maps_platform_datasets.FetchDatasetErrorsRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for fetch_dataset_errors @@ -174,8 +189,11 @@ def post_fetch_dataset_errors( def pre_get_dataset( self, request: maps_platform_datasets.GetDatasetRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[maps_platform_datasets.GetDatasetRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + maps_platform_datasets.GetDatasetRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for get_dataset Override in a subclass to manipulate the request or metadata @@ -195,8 +213,11 @@ def post_get_dataset(self, response: dataset.Dataset) -> dataset.Dataset: def pre_list_datasets( self, request: maps_platform_datasets.ListDatasetsRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[maps_platform_datasets.ListDatasetsRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + maps_platform_datasets.ListDatasetsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for list_datasets Override in a subclass to manipulate the request or metadata @@ -218,9 +239,10 @@ def post_list_datasets( def pre_update_dataset_metadata( self, request: maps_platform_datasets.UpdateDatasetMetadataRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - maps_platform_datasets.UpdateDatasetMetadataRequest, Sequence[Tuple[str, str]] + maps_platform_datasets.UpdateDatasetMetadataRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for update_dataset_metadata @@ -363,7 +385,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> gmm_dataset.Dataset: r"""Call the create dataset method over HTTP. @@ -373,8 +395,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.gmm_dataset.Dataset: @@ -386,6 +410,7 @@ def __call__( http_options = ( _BaseMapsPlatformDatasetsRestTransport._BaseCreateDataset._get_http_options() ) + request, metadata = self._interceptor.pre_create_dataset(request, metadata) transcoded_request = _BaseMapsPlatformDatasetsRestTransport._BaseCreateDataset._get_transcoded_request( http_options, request @@ -400,6 +425,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient.CreateDataset", + extra={ + "serviceName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "rpcName": "CreateDataset", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = MapsPlatformDatasetsRestTransport._CreateDataset._get_response( self._host, @@ -421,7 +473,29 @@ def __call__( pb_resp = gmm_dataset.Dataset.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_dataset(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = gmm_dataset.Dataset.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.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient.create_dataset", + extra={ + "serviceName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "rpcName": "CreateDataset", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _DeleteDataset( @@ -459,7 +533,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ): r"""Call the delete dataset method over HTTP. @@ -469,13 +543,16 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 = ( _BaseMapsPlatformDatasetsRestTransport._BaseDeleteDataset._get_http_options() ) + request, metadata = self._interceptor.pre_delete_dataset(request, metadata) transcoded_request = _BaseMapsPlatformDatasetsRestTransport._BaseDeleteDataset._get_transcoded_request( http_options, request @@ -486,6 +563,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + 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.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient.DeleteDataset", + extra={ + "serviceName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "rpcName": "DeleteDataset", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = MapsPlatformDatasetsRestTransport._DeleteDataset._get_response( self._host, @@ -536,7 +640,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> maps_platform_datasets.FetchDatasetErrorsResponse: r"""Call the fetch dataset errors method over HTTP. @@ -547,8 +651,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.maps_platform_datasets.FetchDatasetErrorsResponse: @@ -560,6 +666,7 @@ def __call__( http_options = ( _BaseMapsPlatformDatasetsRestTransport._BaseFetchDatasetErrors._get_http_options() ) + request, metadata = self._interceptor.pre_fetch_dataset_errors( request, metadata ) @@ -572,6 +679,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient.FetchDatasetErrors", + extra={ + "serviceName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "rpcName": "FetchDatasetErrors", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = ( MapsPlatformDatasetsRestTransport._FetchDatasetErrors._get_response( @@ -594,7 +728,33 @@ def __call__( pb_resp = maps_platform_datasets.FetchDatasetErrorsResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_fetch_dataset_errors(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + maps_platform_datasets.FetchDatasetErrorsResponse.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.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient.fetch_dataset_errors", + extra={ + "serviceName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "rpcName": "FetchDatasetErrors", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _GetDataset( @@ -632,7 +792,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> dataset.Dataset: r"""Call the get dataset method over HTTP. @@ -642,8 +802,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.dataset.Dataset: @@ -655,6 +817,7 @@ def __call__( http_options = ( _BaseMapsPlatformDatasetsRestTransport._BaseGetDataset._get_http_options() ) + request, metadata = self._interceptor.pre_get_dataset(request, metadata) transcoded_request = _BaseMapsPlatformDatasetsRestTransport._BaseGetDataset._get_transcoded_request( http_options, request @@ -665,6 +828,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient.GetDataset", + extra={ + "serviceName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "rpcName": "GetDataset", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = MapsPlatformDatasetsRestTransport._GetDataset._get_response( self._host, @@ -685,7 +875,29 @@ def __call__( pb_resp = dataset.Dataset.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_dataset(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = dataset.Dataset.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.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient.get_dataset", + extra={ + "serviceName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "rpcName": "GetDataset", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _ListDatasets( @@ -723,7 +935,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> maps_platform_datasets.ListDatasetsResponse: r"""Call the list datasets method over HTTP. @@ -734,8 +946,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.maps_platform_datasets.ListDatasetsResponse: @@ -745,6 +959,7 @@ def __call__( http_options = ( _BaseMapsPlatformDatasetsRestTransport._BaseListDatasets._get_http_options() ) + request, metadata = self._interceptor.pre_list_datasets(request, metadata) transcoded_request = _BaseMapsPlatformDatasetsRestTransport._BaseListDatasets._get_transcoded_request( http_options, request @@ -755,6 +970,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient.ListDatasets", + extra={ + "serviceName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "rpcName": "ListDatasets", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = MapsPlatformDatasetsRestTransport._ListDatasets._get_response( self._host, @@ -775,7 +1017,31 @@ def __call__( pb_resp = maps_platform_datasets.ListDatasetsResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_datasets(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + maps_platform_datasets.ListDatasetsResponse.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.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient.list_datasets", + extra={ + "serviceName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "rpcName": "ListDatasets", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _UpdateDatasetMetadata( @@ -814,7 +1080,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> gmm_dataset.Dataset: r"""Call the update dataset metadata method over HTTP. @@ -825,8 +1091,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.gmm_dataset.Dataset: @@ -838,6 +1106,7 @@ def __call__( http_options = ( _BaseMapsPlatformDatasetsRestTransport._BaseUpdateDatasetMetadata._get_http_options() ) + request, metadata = self._interceptor.pre_update_dataset_metadata( request, metadata ) @@ -854,6 +1123,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient.UpdateDatasetMetadata", + extra={ + "serviceName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "rpcName": "UpdateDatasetMetadata", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = ( MapsPlatformDatasetsRestTransport._UpdateDatasetMetadata._get_response( @@ -877,7 +1173,29 @@ def __call__( pb_resp = gmm_dataset.Dataset.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_dataset_metadata(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = gmm_dataset.Dataset.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.maps.mapsplatformdatasets_v1.MapsPlatformDatasetsClient.update_dataset_metadata", + extra={ + "serviceName": "google.maps.mapsplatformdatasets.v1.MapsPlatformDatasets", + "rpcName": "UpdateDatasetMetadata", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp @property diff --git a/packages/google-maps-mapsplatformdatasets/samples/generated_samples/snippet_metadata_google.maps.mapsplatformdatasets.v1.json b/packages/google-maps-mapsplatformdatasets/samples/generated_samples/snippet_metadata_google.maps.mapsplatformdatasets.v1.json index 562f762ba0f8..efd05ec97721 100644 --- a/packages/google-maps-mapsplatformdatasets/samples/generated_samples/snippet_metadata_google.maps.mapsplatformdatasets.v1.json +++ b/packages/google-maps-mapsplatformdatasets/samples/generated_samples/snippet_metadata_google.maps.mapsplatformdatasets.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-maps-mapsplatformdatasets", - "version": "0.4.4" + "version": "0.1.0" }, "snippets": [ { @@ -51,7 +51,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.maps.mapsplatformdatasets_v1.types.Dataset", @@ -135,7 +135,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.maps.mapsplatformdatasets_v1.types.Dataset", @@ -216,7 +216,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "shortName": "delete_dataset" @@ -293,7 +293,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "shortName": "delete_dataset" @@ -371,7 +371,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.maps.mapsplatformdatasets_v1.services.maps_platform_datasets.pagers.FetchDatasetErrorsAsyncPager", @@ -451,7 +451,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.maps.mapsplatformdatasets_v1.services.maps_platform_datasets.pagers.FetchDatasetErrorsPager", @@ -532,7 +532,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.maps.mapsplatformdatasets_v1.types.Dataset", @@ -612,7 +612,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.maps.mapsplatformdatasets_v1.types.Dataset", @@ -693,7 +693,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.maps.mapsplatformdatasets_v1.services.maps_platform_datasets.pagers.ListDatasetsAsyncPager", @@ -773,7 +773,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.maps.mapsplatformdatasets_v1.services.maps_platform_datasets.pagers.ListDatasetsPager", @@ -858,7 +858,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.maps.mapsplatformdatasets_v1.types.Dataset", @@ -942,7 +942,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.maps.mapsplatformdatasets_v1.types.Dataset", diff --git a/packages/google-maps-mapsplatformdatasets/tests/unit/gapic/mapsplatformdatasets_v1/test_maps_platform_datasets.py b/packages/google-maps-mapsplatformdatasets/tests/unit/gapic/mapsplatformdatasets_v1/test_maps_platform_datasets.py index 1a87f74fd534..60039a8110ef 100644 --- a/packages/google-maps-mapsplatformdatasets/tests/unit/gapic/mapsplatformdatasets_v1/test_maps_platform_datasets.py +++ b/packages/google-maps-mapsplatformdatasets/tests/unit/gapic/mapsplatformdatasets_v1/test_maps_platform_datasets.py @@ -3664,6 +3664,7 @@ def test_create_dataset_rest_required_fields( response_value._content = json_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_dataset(request) @@ -3718,6 +3719,7 @@ def test_create_dataset_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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_dataset(**mock_args) @@ -3851,6 +3853,7 @@ def test_update_dataset_metadata_rest_required_fields( response_value._content = json_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_dataset_metadata(request) @@ -3897,6 +3900,7 @@ def test_update_dataset_metadata_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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_dataset_metadata(**mock_args) @@ -4028,6 +4032,7 @@ def test_get_dataset_rest_required_fields( response_value._content = json_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_dataset(request) @@ -4073,6 +4078,7 @@ def test_get_dataset_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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_dataset(**mock_args) @@ -4215,6 +4221,7 @@ def test_fetch_dataset_errors_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.fetch_dataset_errors(request) @@ -4270,6 +4277,7 @@ def test_fetch_dataset_errors_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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.fetch_dataset_errors(**mock_args) @@ -4473,6 +4481,7 @@ def test_list_datasets_rest_required_fields( response_value._content = json_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_datasets(request) @@ -4527,6 +4536,7 @@ def test_list_datasets_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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_datasets(**mock_args) @@ -4716,6 +4726,7 @@ def test_delete_dataset_rest_required_fields( response_value._content = json_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_dataset(request) @@ -4759,6 +4770,7 @@ def test_delete_dataset_rest_flattened(): 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_dataset(**mock_args) @@ -5241,6 +5253,7 @@ def test_create_dataset_rest_bad_request( 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_dataset(request) @@ -5362,6 +5375,7 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_dataset(request) # Establish that the response is the type that we expect. @@ -5407,6 +5421,7 @@ def test_create_dataset_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 = gmm_dataset.Dataset.to_json(gmm_dataset.Dataset()) req.return_value.content = return_value @@ -5451,6 +5466,7 @@ def test_update_dataset_metadata_rest_bad_request( 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_dataset_metadata(request) @@ -5574,6 +5590,7 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_dataset_metadata(request) # Establish that the response is the type that we expect. @@ -5619,6 +5636,7 @@ def test_update_dataset_metadata_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 = gmm_dataset.Dataset.to_json(gmm_dataset.Dataset()) req.return_value.content = return_value @@ -5663,6 +5681,7 @@ def test_get_dataset_rest_bad_request( 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_dataset(request) @@ -5703,6 +5722,7 @@ def test_get_dataset_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_dataset(request) # Establish that the response is the type that we expect. @@ -5748,6 +5768,7 @@ def test_get_dataset_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 = dataset.Dataset.to_json(dataset.Dataset()) req.return_value.content = return_value @@ -5792,6 +5813,7 @@ def test_fetch_dataset_errors_rest_bad_request( 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.fetch_dataset_errors(request) @@ -5829,6 +5851,7 @@ def test_fetch_dataset_errors_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.fetch_dataset_errors(request) # Establish that the response is the type that we expect. @@ -5869,6 +5892,7 @@ def test_fetch_dataset_errors_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 = maps_platform_datasets.FetchDatasetErrorsResponse.to_json( maps_platform_datasets.FetchDatasetErrorsResponse() ) @@ -5915,6 +5939,7 @@ def test_list_datasets_rest_bad_request( 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_datasets(request) @@ -5950,6 +5975,7 @@ def test_list_datasets_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_datasets(request) # Establish that the response is the type that we expect. @@ -5990,6 +6016,7 @@ def test_list_datasets_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 = maps_platform_datasets.ListDatasetsResponse.to_json( maps_platform_datasets.ListDatasetsResponse() ) @@ -6036,6 +6063,7 @@ def test_delete_dataset_rest_bad_request( 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_dataset(request) @@ -6066,6 +6094,7 @@ def test_delete_dataset_rest_call_success(request_type): 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_dataset(request) # Establish that the response is the type that we expect. @@ -6102,6 +6131,7 @@ def test_delete_dataset_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"} request = maps_platform_datasets.DeleteDatasetRequest() metadata = [ diff --git a/packages/google-maps-places/google/maps/places/gapic_version.py b/packages/google-maps-places/google/maps/places/gapic_version.py index e04ba333d337..558c8aab67c5 100644 --- a/packages/google-maps-places/google/maps/places/gapic_version.py +++ b/packages/google-maps-places/google/maps/places/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.20" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-maps-places/google/maps/places_v1/gapic_version.py b/packages/google-maps-places/google/maps/places_v1/gapic_version.py index e04ba333d337..558c8aab67c5 100644 --- a/packages/google-maps-places/google/maps/places_v1/gapic_version.py +++ b/packages/google-maps-places/google/maps/places_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.20" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-maps-places/google/maps/places_v1/services/places/async_client.py b/packages/google-maps-places/google/maps/places_v1/services/places/async_client.py index c402dd58ed47..972568708862 100644 --- a/packages/google-maps-places/google/maps/places_v1/services/places/async_client.py +++ b/packages/google-maps-places/google/maps/places_v1/services/places/async_client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import re from typing import ( Callable, @@ -62,6 +63,15 @@ from .transports.base import DEFAULT_CLIENT_INFO, PlacesTransport from .transports.grpc_asyncio import PlacesGrpcAsyncIOTransport +try: + from google.api_core import client_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 PlacesAsyncClient: """Service definition for the Places API. Note: every request (except @@ -268,13 +278,35 @@ def __init__( client_info=client_info, ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.maps.places_v1.PlacesAsyncClient`.", + extra={ + "serviceName": "google.maps.places.v1.Places", + "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.maps.places.v1.Places", + "credentialsType": None, + }, + ) + async def search_nearby( self, request: Optional[Union[places_service.SearchNearbyRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> places_service.SearchNearbyResponse: r"""Search for places near locations. @@ -313,8 +345,10 @@ async def sample_search_nearby(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.maps.places_v1.types.SearchNearbyResponse: @@ -352,7 +386,7 @@ async def search_text( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> places_service.SearchTextResponse: r"""Text query based place search. @@ -388,8 +422,10 @@ async def sample_search_text(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.maps.places_v1.types.SearchTextResponse: @@ -428,7 +464,7 @@ async def get_photo_media( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> places_service.PhotoMedia: r"""Get a photo media with a photo reference string. @@ -479,8 +515,10 @@ async def sample_get_photo_media(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.maps.places_v1.types.PhotoMedia: @@ -539,7 +577,7 @@ async def get_place( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> place.Place: r"""Get the details of a place based on its resource name, which is a string in the ``places/{place_id}`` format. @@ -584,8 +622,10 @@ async def sample_get_place(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.maps.places_v1.types.Place: @@ -645,7 +685,7 @@ async def autocomplete_places( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> places_service.AutocompletePlacesResponse: r"""Returns predictions for the given input. @@ -681,8 +721,10 @@ async def sample_autocomplete_places(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.maps.places_v1.types.AutocompletePlacesResponse: diff --git a/packages/google-maps-places/google/maps/places_v1/services/places/client.py b/packages/google-maps-places/google/maps/places_v1/services/places/client.py index 6a9591368528..fafc04c6cf36 100644 --- a/packages/google-maps-places/google/maps/places_v1/services/places/client.py +++ b/packages/google-maps-places/google/maps/places_v1/services/places/client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import os import re from typing import ( @@ -48,6 +49,15 @@ 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.geo.type.types import viewport from google.type import latlng_pb2 # type: ignore from google.type import localized_text_pb2 # type: ignore @@ -640,6 +650,10 @@ def __init__( # 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( @@ -702,13 +716,36 @@ def __init__( 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.maps.places_v1.PlacesClient`.", + extra={ + "serviceName": "google.maps.places.v1.Places", + "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.maps.places.v1.Places", + "credentialsType": None, + }, + ) + def search_nearby( self, request: Optional[Union[places_service.SearchNearbyRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> places_service.SearchNearbyResponse: r"""Search for places near locations. @@ -747,8 +784,10 @@ def sample_search_nearby(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.maps.places_v1.types.SearchNearbyResponse: @@ -784,7 +823,7 @@ def search_text( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> places_service.SearchTextResponse: r"""Text query based place search. @@ -820,8 +859,10 @@ def sample_search_text(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.maps.places_v1.types.SearchTextResponse: @@ -858,7 +899,7 @@ def get_photo_media( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> places_service.PhotoMedia: r"""Get a photo media with a photo reference string. @@ -909,8 +950,10 @@ def sample_get_photo_media(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.maps.places_v1.types.PhotoMedia: @@ -966,7 +1009,7 @@ def get_place( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> place.Place: r"""Get the details of a place based on its resource name, which is a string in the ``places/{place_id}`` format. @@ -1011,8 +1054,10 @@ def sample_get_place(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.maps.places_v1.types.Place: @@ -1069,7 +1114,7 @@ def autocomplete_places( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> places_service.AutocompletePlacesResponse: r"""Returns predictions for the given input. @@ -1105,8 +1150,10 @@ def sample_autocomplete_places(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.maps.places_v1.types.AutocompletePlacesResponse: diff --git a/packages/google-maps-places/google/maps/places_v1/services/places/transports/grpc.py b/packages/google-maps-places/google/maps/places_v1/services/places/transports/grpc.py index 80a03eb614e9..b4843daefd33 100644 --- a/packages/google-maps-places/google/maps/places_v1/services/places/transports/grpc.py +++ b/packages/google-maps-places/google/maps/places_v1/services/places/transports/grpc.py @@ -13,6 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import json +import logging as std_logging +import pickle from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -20,12 +23,90 @@ 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.maps.places_v1.types import place, places_service from .base import DEFAULT_CLIENT_INFO, PlacesTransport +try: + from google.api_core import client_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.maps.places.v1.Places", + "rpcName": 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.maps.places.v1.Places", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + class PlacesGrpcTransport(PlacesTransport): """gRPC backend transport for Places. @@ -183,7 +264,12 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -259,7 +345,7 @@ def search_nearby( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "search_nearby" not in self._stubs: - self._stubs["search_nearby"] = self.grpc_channel.unary_unary( + self._stubs["search_nearby"] = self._logged_channel.unary_unary( "/google.maps.places.v1.Places/SearchNearby", request_serializer=places_service.SearchNearbyRequest.serialize, response_deserializer=places_service.SearchNearbyResponse.deserialize, @@ -287,7 +373,7 @@ def search_text( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "search_text" not in self._stubs: - self._stubs["search_text"] = self.grpc_channel.unary_unary( + self._stubs["search_text"] = self._logged_channel.unary_unary( "/google.maps.places.v1.Places/SearchText", request_serializer=places_service.SearchTextRequest.serialize, response_deserializer=places_service.SearchTextResponse.deserialize, @@ -313,7 +399,7 @@ def get_photo_media( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_photo_media" not in self._stubs: - self._stubs["get_photo_media"] = self.grpc_channel.unary_unary( + self._stubs["get_photo_media"] = self._logged_channel.unary_unary( "/google.maps.places.v1.Places/GetPhotoMedia", request_serializer=places_service.GetPhotoMediaRequest.serialize, response_deserializer=places_service.PhotoMedia.deserialize, @@ -338,7 +424,7 @@ def get_place(self) -> Callable[[places_service.GetPlaceRequest], place.Place]: # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_place" not in self._stubs: - self._stubs["get_place"] = self.grpc_channel.unary_unary( + self._stubs["get_place"] = self._logged_channel.unary_unary( "/google.maps.places.v1.Places/GetPlace", request_serializer=places_service.GetPlaceRequest.serialize, response_deserializer=place.Place.deserialize, @@ -367,7 +453,7 @@ def autocomplete_places( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "autocomplete_places" not in self._stubs: - self._stubs["autocomplete_places"] = self.grpc_channel.unary_unary( + self._stubs["autocomplete_places"] = self._logged_channel.unary_unary( "/google.maps.places.v1.Places/AutocompletePlaces", request_serializer=places_service.AutocompletePlacesRequest.serialize, response_deserializer=places_service.AutocompletePlacesResponse.deserialize, @@ -375,7 +461,7 @@ def autocomplete_places( return self._stubs["autocomplete_places"] def close(self): - self.grpc_channel.close() + self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-maps-places/google/maps/places_v1/services/places/transports/grpc_asyncio.py b/packages/google-maps-places/google/maps/places_v1/services/places/transports/grpc_asyncio.py index 060a9e4f5f0e..3ba7c1d7056b 100644 --- a/packages/google-maps-places/google/maps/places_v1/services/places/transports/grpc_asyncio.py +++ b/packages/google-maps-places/google/maps/places_v1/services/places/transports/grpc_asyncio.py @@ -14,6 +14,9 @@ # limitations under the License. # import inspect +import json +import logging as std_logging +import pickle from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -22,14 +25,93 @@ 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 from grpc.experimental import aio # type: ignore +import proto # type: ignore from google.maps.places_v1.types import place, places_service from .base import DEFAULT_CLIENT_INFO, PlacesTransport from .grpc import PlacesGrpcTransport +try: + from google.api_core import client_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.maps.places.v1.Places", + "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.maps.places.v1.Places", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + class PlacesGrpcAsyncIOTransport(PlacesTransport): """gRPC AsyncIO backend transport for Places. @@ -230,10 +312,13 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -268,7 +353,7 @@ def search_nearby( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "search_nearby" not in self._stubs: - self._stubs["search_nearby"] = self.grpc_channel.unary_unary( + self._stubs["search_nearby"] = self._logged_channel.unary_unary( "/google.maps.places.v1.Places/SearchNearby", request_serializer=places_service.SearchNearbyRequest.serialize, response_deserializer=places_service.SearchNearbyResponse.deserialize, @@ -296,7 +381,7 @@ def search_text( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "search_text" not in self._stubs: - self._stubs["search_text"] = self.grpc_channel.unary_unary( + self._stubs["search_text"] = self._logged_channel.unary_unary( "/google.maps.places.v1.Places/SearchText", request_serializer=places_service.SearchTextRequest.serialize, response_deserializer=places_service.SearchTextResponse.deserialize, @@ -324,7 +409,7 @@ def get_photo_media( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_photo_media" not in self._stubs: - self._stubs["get_photo_media"] = self.grpc_channel.unary_unary( + self._stubs["get_photo_media"] = self._logged_channel.unary_unary( "/google.maps.places.v1.Places/GetPhotoMedia", request_serializer=places_service.GetPhotoMediaRequest.serialize, response_deserializer=places_service.PhotoMedia.deserialize, @@ -351,7 +436,7 @@ def get_place( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_place" not in self._stubs: - self._stubs["get_place"] = self.grpc_channel.unary_unary( + self._stubs["get_place"] = self._logged_channel.unary_unary( "/google.maps.places.v1.Places/GetPlace", request_serializer=places_service.GetPlaceRequest.serialize, response_deserializer=place.Place.deserialize, @@ -380,7 +465,7 @@ def autocomplete_places( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "autocomplete_places" not in self._stubs: - self._stubs["autocomplete_places"] = self.grpc_channel.unary_unary( + self._stubs["autocomplete_places"] = self._logged_channel.unary_unary( "/google.maps.places.v1.Places/AutocompletePlaces", request_serializer=places_service.AutocompletePlacesRequest.serialize, response_deserializer=places_service.AutocompletePlacesResponse.deserialize, @@ -423,7 +508,7 @@ def _wrap_method(self, func, *args, **kwargs): return gapic_v1.method_async.wrap_method(func, *args, **kwargs) def close(self): - return self.grpc_channel.close() + return self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-maps-places/google/maps/places_v1/services/places/transports/rest.py b/packages/google-maps-places/google/maps/places_v1/services/places/transports/rest.py index ffbd77013d0d..141ae8b3f797 100644 --- a/packages/google-maps-places/google/maps/places_v1/services/places/transports/rest.py +++ b/packages/google-maps-places/google/maps/places_v1/services/places/transports/rest.py @@ -13,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import dataclasses import json # type: ignore +import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings @@ -37,6 +37,14 @@ 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, @@ -109,8 +117,11 @@ def post_search_text(self, response): def pre_autocomplete_places( self, request: places_service.AutocompletePlacesRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[places_service.AutocompletePlacesRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + places_service.AutocompletePlacesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for autocomplete_places Override in a subclass to manipulate the request or metadata @@ -132,8 +143,10 @@ def post_autocomplete_places( def pre_get_photo_media( self, request: places_service.GetPhotoMediaRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[places_service.GetPhotoMediaRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + places_service.GetPhotoMediaRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_photo_media Override in a subclass to manipulate the request or metadata @@ -155,8 +168,8 @@ def post_get_photo_media( def pre_get_place( self, request: places_service.GetPlaceRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[places_service.GetPlaceRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[places_service.GetPlaceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for get_place Override in a subclass to manipulate the request or metadata @@ -176,8 +189,10 @@ def post_get_place(self, response: place.Place) -> place.Place: def pre_search_nearby( self, request: places_service.SearchNearbyRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[places_service.SearchNearbyRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + places_service.SearchNearbyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for search_nearby Override in a subclass to manipulate the request or metadata @@ -199,8 +214,10 @@ def post_search_nearby( def pre_search_text( self, request: places_service.SearchTextRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[places_service.SearchTextRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + places_service.SearchTextRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for search_text Override in a subclass to manipulate the request or metadata @@ -345,7 +362,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> places_service.AutocompletePlacesResponse: r"""Call the autocomplete places method over HTTP. @@ -355,8 +372,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.places_service.AutocompletePlacesResponse: @@ -368,6 +387,7 @@ def __call__( http_options = ( _BasePlacesRestTransport._BaseAutocompletePlaces._get_http_options() ) + request, metadata = self._interceptor.pre_autocomplete_places( request, metadata ) @@ -388,6 +408,33 @@ def __call__( ) ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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.maps.places_v1.PlacesClient.AutocompletePlaces", + extra={ + "serviceName": "google.maps.places.v1.Places", + "rpcName": "AutocompletePlaces", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = PlacesRestTransport._AutocompletePlaces._get_response( self._host, @@ -409,7 +456,31 @@ def __call__( pb_resp = places_service.AutocompletePlacesResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_autocomplete_places(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + places_service.AutocompletePlacesResponse.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.maps.places_v1.PlacesClient.autocomplete_places", + extra={ + "serviceName": "google.maps.places.v1.Places", + "rpcName": "AutocompletePlaces", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _GetPhotoMedia(_BasePlacesRestTransport._BaseGetPhotoMedia, PlacesRestStub): @@ -444,7 +515,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> places_service.PhotoMedia: r"""Call the get photo media method over HTTP. @@ -455,8 +526,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.places_service.PhotoMedia: @@ -466,6 +539,7 @@ def __call__( http_options = ( _BasePlacesRestTransport._BaseGetPhotoMedia._get_http_options() ) + request, metadata = self._interceptor.pre_get_photo_media(request, metadata) transcoded_request = ( _BasePlacesRestTransport._BaseGetPhotoMedia._get_transcoded_request( @@ -480,6 +554,33 @@ def __call__( ) ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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.maps.places_v1.PlacesClient.GetPhotoMedia", + extra={ + "serviceName": "google.maps.places.v1.Places", + "rpcName": "GetPhotoMedia", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = PlacesRestTransport._GetPhotoMedia._get_response( self._host, @@ -500,7 +601,29 @@ def __call__( pb_resp = places_service.PhotoMedia.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_photo_media(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = places_service.PhotoMedia.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.maps.places_v1.PlacesClient.get_photo_media", + extra={ + "serviceName": "google.maps.places.v1.Places", + "rpcName": "GetPhotoMedia", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _GetPlace(_BasePlacesRestTransport._BaseGetPlace, PlacesRestStub): @@ -535,7 +658,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> place.Place: r"""Call the get place method over HTTP. @@ -546,8 +669,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.place.Place: @@ -557,6 +682,7 @@ def __call__( """ http_options = _BasePlacesRestTransport._BaseGetPlace._get_http_options() + request, metadata = self._interceptor.pre_get_place(request, metadata) transcoded_request = ( _BasePlacesRestTransport._BaseGetPlace._get_transcoded_request( @@ -571,6 +697,33 @@ def __call__( ) ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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.maps.places_v1.PlacesClient.GetPlace", + extra={ + "serviceName": "google.maps.places.v1.Places", + "rpcName": "GetPlace", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = PlacesRestTransport._GetPlace._get_response( self._host, @@ -591,7 +744,29 @@ def __call__( pb_resp = place.Place.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_place(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = place.Place.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.maps.places_v1.PlacesClient.get_place", + extra={ + "serviceName": "google.maps.places.v1.Places", + "rpcName": "GetPlace", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _SearchNearby(_BasePlacesRestTransport._BaseSearchNearby, PlacesRestStub): @@ -627,7 +802,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> places_service.SearchNearbyResponse: r"""Call the search nearby method over HTTP. @@ -637,8 +812,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.places_service.SearchNearbyResponse: @@ -648,6 +825,7 @@ def __call__( http_options = ( _BasePlacesRestTransport._BaseSearchNearby._get_http_options() ) + request, metadata = self._interceptor.pre_search_nearby(request, metadata) transcoded_request = ( _BasePlacesRestTransport._BaseSearchNearby._get_transcoded_request( @@ -666,6 +844,33 @@ def __call__( ) ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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.maps.places_v1.PlacesClient.SearchNearby", + extra={ + "serviceName": "google.maps.places.v1.Places", + "rpcName": "SearchNearby", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = PlacesRestTransport._SearchNearby._get_response( self._host, @@ -687,7 +892,31 @@ def __call__( pb_resp = places_service.SearchNearbyResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_search_nearby(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = places_service.SearchNearbyResponse.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.maps.places_v1.PlacesClient.search_nearby", + extra={ + "serviceName": "google.maps.places.v1.Places", + "rpcName": "SearchNearby", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _SearchText(_BasePlacesRestTransport._BaseSearchText, PlacesRestStub): @@ -723,7 +952,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> places_service.SearchTextResponse: r"""Call the search text method over HTTP. @@ -733,8 +962,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.places_service.SearchTextResponse: @@ -742,6 +973,7 @@ def __call__( """ http_options = _BasePlacesRestTransport._BaseSearchText._get_http_options() + request, metadata = self._interceptor.pre_search_text(request, metadata) transcoded_request = ( _BasePlacesRestTransport._BaseSearchText._get_transcoded_request( @@ -760,6 +992,33 @@ def __call__( ) ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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.maps.places_v1.PlacesClient.SearchText", + extra={ + "serviceName": "google.maps.places.v1.Places", + "rpcName": "SearchText", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = PlacesRestTransport._SearchText._get_response( self._host, @@ -781,7 +1040,31 @@ def __call__( pb_resp = places_service.SearchTextResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_search_text(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = places_service.SearchTextResponse.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.maps.places_v1.PlacesClient.search_text", + extra={ + "serviceName": "google.maps.places.v1.Places", + "rpcName": "SearchText", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp @property diff --git a/packages/google-maps-places/samples/generated_samples/snippet_metadata_google.maps.places.v1.json b/packages/google-maps-places/samples/generated_samples/snippet_metadata_google.maps.places.v1.json index a07d76715842..bea29a42b294 100644 --- a/packages/google-maps-places/samples/generated_samples/snippet_metadata_google.maps.places.v1.json +++ b/packages/google-maps-places/samples/generated_samples/snippet_metadata_google.maps.places.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-maps-places", - "version": "0.1.20" + "version": "0.1.0" }, "snippets": [ { @@ -43,7 +43,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.maps.places_v1.types.AutocompletePlacesResponse", @@ -119,7 +119,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.maps.places_v1.types.AutocompletePlacesResponse", @@ -200,7 +200,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.maps.places_v1.types.PhotoMedia", @@ -280,7 +280,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.maps.places_v1.types.PhotoMedia", @@ -361,7 +361,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.maps.places_v1.types.Place", @@ -441,7 +441,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.maps.places_v1.types.Place", @@ -518,7 +518,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.maps.places_v1.types.SearchNearbyResponse", @@ -594,7 +594,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.maps.places_v1.types.SearchNearbyResponse", @@ -671,7 +671,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.maps.places_v1.types.SearchTextResponse", @@ -747,7 +747,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.maps.places_v1.types.SearchTextResponse", diff --git a/packages/google-maps-places/tests/unit/gapic/places_v1/test_places.py b/packages/google-maps-places/tests/unit/gapic/places_v1/test_places.py index 2d2d4a4e2fa9..d2290b7fdf33 100644 --- a/packages/google-maps-places/tests/unit/gapic/places_v1/test_places.py +++ b/packages/google-maps-places/tests/unit/gapic/places_v1/test_places.py @@ -2468,6 +2468,7 @@ def test_search_nearby_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.search_nearby(request) @@ -2588,6 +2589,7 @@ def test_search_text_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.search_text(request) @@ -2715,6 +2717,7 @@ def test_get_photo_media_rest_required_fields( response_value._content = json_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_photo_media(request) @@ -2769,6 +2772,7 @@ def test_get_photo_media_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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_photo_media(**mock_args) @@ -2904,6 +2908,7 @@ def test_get_place_rest_required_fields(request_type=places_service.GetPlaceRequ response_value._content = json_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_place(request) @@ -2958,6 +2963,7 @@ def test_get_place_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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_place(**mock_args) @@ -3092,6 +3098,7 @@ def test_autocomplete_places_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.autocomplete_places(request) @@ -3537,6 +3544,7 @@ def test_search_nearby_rest_bad_request( 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.search_nearby(request) @@ -3570,6 +3578,7 @@ def test_search_nearby_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.search_nearby(request) # Establish that the response is the type that we expect. @@ -3607,6 +3616,7 @@ def test_search_nearby_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 = places_service.SearchNearbyResponse.to_json( places_service.SearchNearbyResponse() ) @@ -3651,6 +3661,7 @@ def test_search_text_rest_bad_request(request_type=places_service.SearchTextRequ 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.search_text(request) @@ -3684,6 +3695,7 @@ def test_search_text_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.search_text(request) # Establish that the response is the type that we expect. @@ -3721,6 +3733,7 @@ def test_search_text_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 = places_service.SearchTextResponse.to_json( places_service.SearchTextResponse() ) @@ -3767,6 +3780,7 @@ def test_get_photo_media_rest_bad_request( 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_photo_media(request) @@ -3803,6 +3817,7 @@ def test_get_photo_media_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_photo_media(request) # Establish that the response is the type that we expect. @@ -3842,6 +3857,7 @@ def test_get_photo_media_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 = places_service.PhotoMedia.to_json(places_service.PhotoMedia()) req.return_value.content = return_value @@ -3884,6 +3900,7 @@ def test_get_place_rest_bad_request(request_type=places_service.GetPlaceRequest) 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_place(request) @@ -3960,6 +3977,7 @@ def test_get_place_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_place(request) # Establish that the response is the type that we expect. @@ -4037,6 +4055,7 @@ def test_get_place_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 = place.Place.to_json(place.Place()) req.return_value.content = return_value @@ -4081,6 +4100,7 @@ def test_autocomplete_places_rest_bad_request( 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.autocomplete_places(request) @@ -4114,6 +4134,7 @@ def test_autocomplete_places_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.autocomplete_places(request) # Establish that the response is the type that we expect. @@ -4151,6 +4172,7 @@ def test_autocomplete_places_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 = places_service.AutocompletePlacesResponse.to_json( places_service.AutocompletePlacesResponse() ) diff --git a/packages/google-maps-routeoptimization/google/maps/routeoptimization/gapic_version.py b/packages/google-maps-routeoptimization/google/maps/routeoptimization/gapic_version.py index 51d2795b9d6b..558c8aab67c5 100644 --- a/packages/google-maps-routeoptimization/google/maps/routeoptimization/gapic_version.py +++ b/packages/google-maps-routeoptimization/google/maps/routeoptimization/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.6" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/gapic_version.py b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/gapic_version.py index 51d2795b9d6b..558c8aab67c5 100644 --- a/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/gapic_version.py +++ b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.6" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/async_client.py b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/async_client.py index d8ad78e46e99..4c42252bdb67 100644 --- a/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/async_client.py +++ b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/async_client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import re from typing import ( Callable, @@ -52,6 +53,15 @@ from .transports.base import DEFAULT_CLIENT_INFO, RouteOptimizationTransport from .transports.grpc_asyncio import RouteOptimizationGrpcAsyncIOTransport +try: + from google.api_core import client_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 RouteOptimizationAsyncClient: """A service for optimizing vehicle tours. @@ -282,6 +292,28 @@ def __init__( client_info=client_info, ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.maps.routeoptimization_v1.RouteOptimizationAsyncClient`.", + extra={ + "serviceName": "google.maps.routeoptimization.v1.RouteOptimization", + "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.maps.routeoptimization.v1.RouteOptimization", + "credentialsType": None, + }, + ) + async def optimize_tours( self, request: Optional[ @@ -290,7 +322,7 @@ async def optimize_tours( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> route_optimization_service.OptimizeToursResponse: r"""Sends an ``OptimizeToursRequest`` containing a ``ShipmentModel`` and returns an ``OptimizeToursResponse`` containing @@ -344,8 +376,10 @@ async def sample_optimize_tours(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.maps.routeoptimization_v1.types.OptimizeToursResponse: @@ -396,7 +430,7 @@ async def batch_optimize_tours( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation_async.AsyncOperation: r"""Optimizes vehicle tours for one or more ``OptimizeToursRequest`` messages as a batch. @@ -473,8 +507,10 @@ async def sample_batch_optimize_tours(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api_core.operation_async.AsyncOperation: @@ -533,7 +569,7 @@ async def get_operation( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: r"""Gets the latest state of a long-running operation. @@ -544,8 +580,10 @@ async def get_operation( 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.operations_pb2.Operation: An ``Operation`` object. diff --git a/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/client.py b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/client.py index 8f8dce2da47c..6d57e2ba7255 100644 --- a/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/client.py +++ b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import os import re from typing import ( @@ -48,6 +49,15 @@ 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.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore from google.longrunning import operations_pb2 # type: ignore @@ -586,6 +596,10 @@ def __init__( # 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( @@ -652,6 +666,29 @@ def __init__( 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.maps.routeoptimization_v1.RouteOptimizationClient`.", + extra={ + "serviceName": "google.maps.routeoptimization.v1.RouteOptimization", + "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.maps.routeoptimization.v1.RouteOptimization", + "credentialsType": None, + }, + ) + def optimize_tours( self, request: Optional[ @@ -660,7 +697,7 @@ def optimize_tours( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> route_optimization_service.OptimizeToursResponse: r"""Sends an ``OptimizeToursRequest`` containing a ``ShipmentModel`` and returns an ``OptimizeToursResponse`` containing @@ -714,8 +751,10 @@ def sample_optimize_tours(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.maps.routeoptimization_v1.types.OptimizeToursResponse: @@ -764,7 +803,7 @@ def batch_optimize_tours( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation.Operation: r"""Optimizes vehicle tours for one or more ``OptimizeToursRequest`` messages as a batch. @@ -841,8 +880,10 @@ def sample_batch_optimize_tours(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api_core.operation.Operation: @@ -912,7 +953,7 @@ def get_operation( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: r"""Gets the latest state of a long-running operation. @@ -923,8 +964,10 @@ def get_operation( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.operations_pb2.Operation: An ``Operation`` object. diff --git a/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/transports/grpc.py b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/transports/grpc.py index 79f73aece6fa..7607e1eacc51 100644 --- a/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/transports/grpc.py +++ b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/transports/grpc.py @@ -13,6 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import json +import logging as std_logging +import pickle from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -21,12 +24,90 @@ from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message import grpc # type: ignore +import proto # type: ignore from google.maps.routeoptimization_v1.types import route_optimization_service from .base import DEFAULT_CLIENT_INFO, RouteOptimizationTransport +try: + from google.api_core import client_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.maps.routeoptimization.v1.RouteOptimization", + "rpcName": 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.maps.routeoptimization.v1.RouteOptimization", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + class RouteOptimizationGrpcTransport(RouteOptimizationTransport): """gRPC backend transport for RouteOptimization. @@ -203,7 +284,12 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -267,7 +353,9 @@ def operations_client(self) -> operations_v1.OperationsClient: """ # Quick check: Only create a new client if we do not already have one. if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient(self.grpc_channel) + self._operations_client = operations_v1.OperationsClient( + self._logged_channel + ) # Return the client from cache. return self._operations_client @@ -309,7 +397,7 @@ def optimize_tours( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "optimize_tours" not in self._stubs: - self._stubs["optimize_tours"] = self.grpc_channel.unary_unary( + self._stubs["optimize_tours"] = self._logged_channel.unary_unary( "/google.maps.routeoptimization.v1.RouteOptimization/OptimizeTours", request_serializer=route_optimization_service.OptimizeToursRequest.serialize, response_deserializer=route_optimization_service.OptimizeToursResponse.deserialize, @@ -361,7 +449,7 @@ def batch_optimize_tours( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "batch_optimize_tours" not in self._stubs: - self._stubs["batch_optimize_tours"] = self.grpc_channel.unary_unary( + self._stubs["batch_optimize_tours"] = self._logged_channel.unary_unary( "/google.maps.routeoptimization.v1.RouteOptimization/BatchOptimizeTours", request_serializer=route_optimization_service.BatchOptimizeToursRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, @@ -369,7 +457,7 @@ def batch_optimize_tours( return self._stubs["batch_optimize_tours"] def close(self): - self.grpc_channel.close() + self._logged_channel.close() @property def get_operation( @@ -381,7 +469,7 @@ def get_operation( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( + self._stubs["get_operation"] = self._logged_channel.unary_unary( "/google.longrunning.Operations/GetOperation", request_serializer=operations_pb2.GetOperationRequest.SerializeToString, response_deserializer=operations_pb2.Operation.FromString, diff --git a/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/transports/grpc_asyncio.py b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/transports/grpc_asyncio.py index 36b86ca20bae..faef6ce0f04b 100644 --- a/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/transports/grpc_asyncio.py +++ b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/transports/grpc_asyncio.py @@ -14,6 +14,9 @@ # limitations under the License. # import inspect +import json +import logging as std_logging +import pickle from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -23,14 +26,93 @@ from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message import grpc # type: ignore from grpc.experimental import aio # type: ignore +import proto # type: ignore from google.maps.routeoptimization_v1.types import route_optimization_service from .base import DEFAULT_CLIENT_INFO, RouteOptimizationTransport from .grpc import RouteOptimizationGrpcTransport +try: + from google.api_core import client_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.maps.routeoptimization.v1.RouteOptimization", + "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.maps.routeoptimization.v1.RouteOptimization", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + class RouteOptimizationGrpcAsyncIOTransport(RouteOptimizationTransport): """gRPC AsyncIO backend transport for RouteOptimization. @@ -250,10 +332,13 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -276,7 +361,7 @@ def operations_client(self) -> operations_v1.OperationsAsyncClient: # Quick check: Only create a new client if we do not already have one. if self._operations_client is None: self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel + self._logged_channel ) # Return the client from cache. @@ -319,7 +404,7 @@ def optimize_tours( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "optimize_tours" not in self._stubs: - self._stubs["optimize_tours"] = self.grpc_channel.unary_unary( + self._stubs["optimize_tours"] = self._logged_channel.unary_unary( "/google.maps.routeoptimization.v1.RouteOptimization/OptimizeTours", request_serializer=route_optimization_service.OptimizeToursRequest.serialize, response_deserializer=route_optimization_service.OptimizeToursResponse.deserialize, @@ -372,7 +457,7 @@ def batch_optimize_tours( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "batch_optimize_tours" not in self._stubs: - self._stubs["batch_optimize_tours"] = self.grpc_channel.unary_unary( + self._stubs["batch_optimize_tours"] = self._logged_channel.unary_unary( "/google.maps.routeoptimization.v1.RouteOptimization/BatchOptimizeTours", request_serializer=route_optimization_service.BatchOptimizeToursRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, @@ -414,7 +499,7 @@ def _wrap_method(self, func, *args, **kwargs): return gapic_v1.method_async.wrap_method(func, *args, **kwargs) def close(self): - return self.grpc_channel.close() + return self._logged_channel.close() @property def kind(self) -> str: @@ -430,7 +515,7 @@ def get_operation( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( + self._stubs["get_operation"] = self._logged_channel.unary_unary( "/google.longrunning.Operations/GetOperation", request_serializer=operations_pb2.GetOperationRequest.SerializeToString, response_deserializer=operations_pb2.Operation.FromString, diff --git a/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/transports/rest.py b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/transports/rest.py index ab439b3fef3b..c5c585833fc9 100644 --- a/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/transports/rest.py +++ b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/transports/rest.py @@ -13,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import dataclasses import json # type: ignore +import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings @@ -38,6 +38,14 @@ 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, @@ -86,9 +94,10 @@ def post_optimize_tours(self, response): def pre_batch_optimize_tours( self, request: route_optimization_service.BatchOptimizeToursRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - route_optimization_service.BatchOptimizeToursRequest, Sequence[Tuple[str, str]] + route_optimization_service.BatchOptimizeToursRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for batch_optimize_tours @@ -111,9 +120,10 @@ def post_batch_optimize_tours( def pre_optimize_tours( self, request: route_optimization_service.OptimizeToursRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - route_optimization_service.OptimizeToursRequest, Sequence[Tuple[str, str]] + route_optimization_service.OptimizeToursRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for optimize_tours @@ -136,8 +146,10 @@ def post_optimize_tours( def pre_get_operation( self, request: operations_pb2.GetOperationRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_operation Override in a subclass to manipulate the request or metadata @@ -336,7 +348,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: r"""Call the batch optimize tours method over HTTP. @@ -352,8 +364,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.operations_pb2.Operation: @@ -366,6 +380,7 @@ def __call__( http_options = ( _BaseRouteOptimizationRestTransport._BaseBatchOptimizeTours._get_http_options() ) + request, metadata = self._interceptor.pre_batch_optimize_tours( request, metadata ) @@ -382,6 +397,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + 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.maps.routeoptimization_v1.RouteOptimizationClient.BatchOptimizeTours", + extra={ + "serviceName": "google.maps.routeoptimization.v1.RouteOptimization", + "rpcName": "BatchOptimizeTours", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = RouteOptimizationRestTransport._BatchOptimizeTours._get_response( self._host, @@ -401,7 +443,29 @@ def __call__( # Return the response resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_batch_optimize_tours(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.maps.routeoptimization_v1.RouteOptimizationClient.batch_optimize_tours", + extra={ + "serviceName": "google.maps.routeoptimization.v1.RouteOptimization", + "rpcName": "BatchOptimizeTours", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _OptimizeTours( @@ -440,7 +504,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> route_optimization_service.OptimizeToursResponse: r"""Call the optimize tours method over HTTP. @@ -453,8 +517,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.route_optimization_service.OptimizeToursResponse: @@ -469,6 +535,7 @@ def __call__( http_options = ( _BaseRouteOptimizationRestTransport._BaseOptimizeTours._get_http_options() ) + request, metadata = self._interceptor.pre_optimize_tours(request, metadata) transcoded_request = _BaseRouteOptimizationRestTransport._BaseOptimizeTours._get_transcoded_request( http_options, request @@ -483,6 +550,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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.maps.routeoptimization_v1.RouteOptimizationClient.OptimizeTours", + extra={ + "serviceName": "google.maps.routeoptimization.v1.RouteOptimization", + "rpcName": "OptimizeTours", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = RouteOptimizationRestTransport._OptimizeTours._get_response( self._host, @@ -504,7 +598,33 @@ def __call__( pb_resp = route_optimization_service.OptimizeToursResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_optimize_tours(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + route_optimization_service.OptimizeToursResponse.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.maps.routeoptimization_v1.RouteOptimizationClient.optimize_tours", + extra={ + "serviceName": "google.maps.routeoptimization.v1.RouteOptimization", + "rpcName": "OptimizeTours", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp @property @@ -566,7 +686,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: r"""Call the get operation method over HTTP. @@ -576,8 +696,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: operations_pb2.Operation: Response from GetOperation method. @@ -586,6 +708,7 @@ def __call__( http_options = ( _BaseRouteOptimizationRestTransport._BaseGetOperation._get_http_options() ) + request, metadata = self._interceptor.pre_get_operation(request, metadata) transcoded_request = _BaseRouteOptimizationRestTransport._BaseGetOperation._get_transcoded_request( http_options, request @@ -596,6 +719,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + 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.maps.routeoptimization_v1.RouteOptimizationClient.GetOperation", + extra={ + "serviceName": "google.maps.routeoptimization.v1.RouteOptimization", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = RouteOptimizationRestTransport._GetOperation._get_response( self._host, @@ -615,6 +765,27 @@ def __call__( resp = operations_pb2.Operation() resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.maps.routeoptimization_v1.RouteOptimizationAsyncClient.GetOperation", + extra={ + "serviceName": "google.maps.routeoptimization.v1.RouteOptimization", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) return resp @property diff --git a/packages/google-maps-routeoptimization/samples/generated_samples/snippet_metadata_google.maps.routeoptimization.v1.json b/packages/google-maps-routeoptimization/samples/generated_samples/snippet_metadata_google.maps.routeoptimization.v1.json index 16fb1d76800a..fcfcf65d2f4f 100644 --- a/packages/google-maps-routeoptimization/samples/generated_samples/snippet_metadata_google.maps.routeoptimization.v1.json +++ b/packages/google-maps-routeoptimization/samples/generated_samples/snippet_metadata_google.maps.routeoptimization.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-maps-routeoptimization", - "version": "0.1.6" + "version": "0.1.0" }, "snippets": [ { @@ -43,7 +43,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.api_core.operation_async.AsyncOperation", @@ -119,7 +119,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.api_core.operation.Operation", @@ -196,7 +196,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.maps.routeoptimization_v1.types.OptimizeToursResponse", @@ -272,7 +272,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.maps.routeoptimization_v1.types.OptimizeToursResponse", diff --git a/packages/google-maps-routeoptimization/tests/unit/gapic/routeoptimization_v1/test_route_optimization.py b/packages/google-maps-routeoptimization/tests/unit/gapic/routeoptimization_v1/test_route_optimization.py index 875a89bb1e67..c8817288cd0e 100644 --- a/packages/google-maps-routeoptimization/tests/unit/gapic/routeoptimization_v1/test_route_optimization.py +++ b/packages/google-maps-routeoptimization/tests/unit/gapic/routeoptimization_v1/test_route_optimization.py @@ -1719,6 +1719,7 @@ def test_optimize_tours_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.optimize_tours(request) @@ -1844,6 +1845,7 @@ def test_batch_optimize_tours_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.batch_optimize_tours(request) @@ -2115,6 +2117,7 @@ def test_optimize_tours_rest_bad_request( 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.optimize_tours(request) @@ -2150,6 +2153,7 @@ def test_optimize_tours_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.optimize_tours(request) # Establish that the response is the type that we expect. @@ -2190,6 +2194,7 @@ def test_optimize_tours_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 = route_optimization_service.OptimizeToursResponse.to_json( route_optimization_service.OptimizeToursResponse() ) @@ -2236,6 +2241,7 @@ def test_batch_optimize_tours_rest_bad_request( 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.batch_optimize_tours(request) @@ -2266,6 +2272,7 @@ def test_batch_optimize_tours_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.batch_optimize_tours(request) # Establish that the response is the type that we expect. @@ -2307,6 +2314,7 @@ def test_batch_optimize_tours_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 = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value @@ -2353,6 +2361,7 @@ def test_get_operation_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.get_operation(request) @@ -2383,6 +2392,7 @@ def test_get_operation_rest(request_type): response_value.content = json_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_operation(request) diff --git a/packages/google-maps-routing/google/maps/routing_v2/services/routes/async_client.py b/packages/google-maps-routing/google/maps/routing_v2/services/routes/async_client.py index a6882615fc53..a060eb0bcd7d 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/services/routes/async_client.py +++ b/packages/google-maps-routing/google/maps/routing_v2/services/routes/async_client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import re from typing import ( AsyncIterable, @@ -58,6 +59,15 @@ from .transports.base import DEFAULT_CLIENT_INFO, RoutesTransport from .transports.grpc_asyncio import RoutesGrpcAsyncIOTransport +try: + from google.api_core import client_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 RoutesAsyncClient: """The Routes API.""" @@ -251,13 +261,35 @@ def __init__( client_info=client_info, ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.maps.routing_v2.RoutesAsyncClient`.", + extra={ + "serviceName": "google.maps.routing.v2.Routes", + "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.maps.routing.v2.Routes", + "credentialsType": None, + }, + ) + async def compute_routes( self, request: Optional[Union[routes_service.ComputeRoutesRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> routes_service.ComputeRoutesResponse: r"""Returns the primary route along with optional alternate routes, given a set of terminal and intermediate waypoints. @@ -328,8 +360,10 @@ async def sample_compute_routes(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.maps.routing_v2.types.ComputeRoutesResponse: @@ -367,7 +401,7 @@ def compute_route_matrix( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> Awaitable[AsyncIterable[routes_service.RouteMatrixElement]]: r"""Takes in a list of origins and destinations and returns a stream containing route information for each combination of origin and @@ -440,8 +474,10 @@ async def sample_compute_route_matrix(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: AsyncIterable[google.maps.routing_v2.types.RouteMatrixElement]: diff --git a/packages/google-maps-routing/google/maps/routing_v2/services/routes/client.py b/packages/google-maps-routing/google/maps/routing_v2/services/routes/client.py index f190526e7f87..71cdfe6b5391 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/services/routes/client.py +++ b/packages/google-maps-routing/google/maps/routing_v2/services/routes/client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import os import re from typing import ( @@ -49,6 +50,15 @@ 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 duration_pb2 # type: ignore from google.rpc import status_pb2 # type: ignore @@ -562,6 +572,10 @@ def __init__( # 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( @@ -624,13 +638,36 @@ def __init__( 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.maps.routing_v2.RoutesClient`.", + extra={ + "serviceName": "google.maps.routing.v2.Routes", + "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.maps.routing.v2.Routes", + "credentialsType": None, + }, + ) + def compute_routes( self, request: Optional[Union[routes_service.ComputeRoutesRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> routes_service.ComputeRoutesResponse: r"""Returns the primary route along with optional alternate routes, given a set of terminal and intermediate waypoints. @@ -701,8 +738,10 @@ def sample_compute_routes(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.maps.routing_v2.types.ComputeRoutesResponse: @@ -738,7 +777,7 @@ def compute_route_matrix( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> Iterable[routes_service.RouteMatrixElement]: r"""Takes in a list of origins and destinations and returns a stream containing route information for each combination of origin and @@ -811,8 +850,10 @@ def sample_compute_route_matrix(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: Iterable[google.maps.routing_v2.types.RouteMatrixElement]: diff --git a/packages/google-maps-routing/google/maps/routing_v2/services/routes/transports/grpc.py b/packages/google-maps-routing/google/maps/routing_v2/services/routes/transports/grpc.py index c2b9f751e312..11ba4ec58540 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/services/routes/transports/grpc.py +++ b/packages/google-maps-routing/google/maps/routing_v2/services/routes/transports/grpc.py @@ -13,6 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import json +import logging as std_logging +import pickle from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -20,12 +23,90 @@ 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.maps.routing_v2.types import routes_service from .base import DEFAULT_CLIENT_INFO, RoutesTransport +try: + from google.api_core import client_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.maps.routing.v2.Routes", + "rpcName": 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.maps.routing.v2.Routes", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + class RoutesGrpcTransport(RoutesTransport): """gRPC backend transport for Routes. @@ -179,7 +260,12 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -291,7 +377,7 @@ def compute_routes( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "compute_routes" not in self._stubs: - self._stubs["compute_routes"] = self.grpc_channel.unary_unary( + self._stubs["compute_routes"] = self._logged_channel.unary_unary( "/google.maps.routing.v2.Routes/ComputeRoutes", request_serializer=routes_service.ComputeRoutesRequest.serialize, response_deserializer=routes_service.ComputeRoutesResponse.deserialize, @@ -356,7 +442,7 @@ def compute_route_matrix( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "compute_route_matrix" not in self._stubs: - self._stubs["compute_route_matrix"] = self.grpc_channel.unary_stream( + self._stubs["compute_route_matrix"] = self._logged_channel.unary_stream( "/google.maps.routing.v2.Routes/ComputeRouteMatrix", request_serializer=routes_service.ComputeRouteMatrixRequest.serialize, response_deserializer=routes_service.RouteMatrixElement.deserialize, @@ -364,7 +450,7 @@ def compute_route_matrix( return self._stubs["compute_route_matrix"] def close(self): - self.grpc_channel.close() + self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-maps-routing/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py b/packages/google-maps-routing/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py index 53f4300794cc..fb7a0daa133b 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py +++ b/packages/google-maps-routing/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py @@ -14,6 +14,9 @@ # limitations under the License. # import inspect +import json +import logging as std_logging +import pickle from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -22,14 +25,93 @@ 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 from grpc.experimental import aio # type: ignore +import proto # type: ignore from google.maps.routing_v2.types import routes_service from .base import DEFAULT_CLIENT_INFO, RoutesTransport from .grpc import RoutesGrpcTransport +try: + from google.api_core import client_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.maps.routing.v2.Routes", + "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.maps.routing.v2.Routes", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + class RoutesGrpcAsyncIOTransport(RoutesTransport): """gRPC AsyncIO backend transport for Routes. @@ -226,10 +308,13 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -300,7 +385,7 @@ def compute_routes( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "compute_routes" not in self._stubs: - self._stubs["compute_routes"] = self.grpc_channel.unary_unary( + self._stubs["compute_routes"] = self._logged_channel.unary_unary( "/google.maps.routing.v2.Routes/ComputeRoutes", request_serializer=routes_service.ComputeRoutesRequest.serialize, response_deserializer=routes_service.ComputeRoutesResponse.deserialize, @@ -366,7 +451,7 @@ def compute_route_matrix( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "compute_route_matrix" not in self._stubs: - self._stubs["compute_route_matrix"] = self.grpc_channel.unary_stream( + self._stubs["compute_route_matrix"] = self._logged_channel.unary_stream( "/google.maps.routing.v2.Routes/ComputeRouteMatrix", request_serializer=routes_service.ComputeRouteMatrixRequest.serialize, response_deserializer=routes_service.RouteMatrixElement.deserialize, @@ -394,7 +479,7 @@ def _wrap_method(self, func, *args, **kwargs): return gapic_v1.method_async.wrap_method(func, *args, **kwargs) def close(self): - return self.grpc_channel.close() + return self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-maps-routing/google/maps/routing_v2/services/routes/transports/rest.py b/packages/google-maps-routing/google/maps/routing_v2/services/routes/transports/rest.py index 7228185de516..e3209c8e05df 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/services/routes/transports/rest.py +++ b/packages/google-maps-routing/google/maps/routing_v2/services/routes/transports/rest.py @@ -13,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import dataclasses import json # type: ignore +import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings @@ -37,6 +37,14 @@ 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, @@ -85,8 +93,11 @@ def post_compute_routes(self, response): def pre_compute_route_matrix( self, request: routes_service.ComputeRouteMatrixRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[routes_service.ComputeRouteMatrixRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + routes_service.ComputeRouteMatrixRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for compute_route_matrix Override in a subclass to manipulate the request or metadata @@ -108,8 +119,10 @@ def post_compute_route_matrix( def pre_compute_routes( self, request: routes_service.ComputeRoutesRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[routes_service.ComputeRoutesRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + routes_service.ComputeRoutesRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for compute_routes Override in a subclass to manipulate the request or metadata @@ -251,7 +264,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> rest_streaming.ResponseIterator: r"""Call the compute route matrix method over HTTP. @@ -261,8 +274,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.routes_service.RouteMatrixElement: @@ -276,6 +291,7 @@ def __call__( http_options = ( _BaseRoutesRestTransport._BaseComputeRouteMatrix._get_http_options() ) + request, metadata = self._interceptor.pre_compute_route_matrix( request, metadata ) @@ -296,6 +312,33 @@ def __call__( ) ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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.maps.routing_v2.RoutesClient.ComputeRouteMatrix", + extra={ + "serviceName": "google.maps.routing.v2.Routes", + "rpcName": "ComputeRouteMatrix", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = RoutesRestTransport._ComputeRouteMatrix._get_response( self._host, @@ -316,6 +359,7 @@ def __call__( resp = rest_streaming.ResponseIterator( response, routes_service.RouteMatrixElement ) + resp = self._interceptor.post_compute_route_matrix(resp) return resp @@ -352,7 +396,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> routes_service.ComputeRoutesResponse: r"""Call the compute routes method over HTTP. @@ -362,8 +406,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.routes_service.ComputeRoutesResponse: @@ -373,6 +419,7 @@ def __call__( http_options = ( _BaseRoutesRestTransport._BaseComputeRoutes._get_http_options() ) + request, metadata = self._interceptor.pre_compute_routes(request, metadata) transcoded_request = ( _BaseRoutesRestTransport._BaseComputeRoutes._get_transcoded_request( @@ -391,6 +438,33 @@ def __call__( ) ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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.maps.routing_v2.RoutesClient.ComputeRoutes", + extra={ + "serviceName": "google.maps.routing.v2.Routes", + "rpcName": "ComputeRoutes", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = RoutesRestTransport._ComputeRoutes._get_response( self._host, @@ -412,7 +486,31 @@ def __call__( pb_resp = routes_service.ComputeRoutesResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_compute_routes(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = routes_service.ComputeRoutesResponse.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.maps.routing_v2.RoutesClient.compute_routes", + extra={ + "serviceName": "google.maps.routing.v2.Routes", + "rpcName": "ComputeRoutes", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp @property diff --git a/packages/google-maps-routing/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json b/packages/google-maps-routing/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json index b5ed5aca319c..ebb0fa3e0c00 100644 --- a/packages/google-maps-routing/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json +++ b/packages/google-maps-routing/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json @@ -43,7 +43,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "Iterable[google.maps.routing_v2.types.RouteMatrixElement]", @@ -119,7 +119,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "Iterable[google.maps.routing_v2.types.RouteMatrixElement]", @@ -196,7 +196,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.maps.routing_v2.types.ComputeRoutesResponse", @@ -272,7 +272,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.maps.routing_v2.types.ComputeRoutesResponse", diff --git a/packages/google-maps-routing/tests/unit/gapic/routing_v2/test_routes.py b/packages/google-maps-routing/tests/unit/gapic/routing_v2/test_routes.py index 4f52fcf75276..133a7dcd7615 100644 --- a/packages/google-maps-routing/tests/unit/gapic/routing_v2/test_routes.py +++ b/packages/google-maps-routing/tests/unit/gapic/routing_v2/test_routes.py @@ -1477,6 +1477,7 @@ def test_compute_routes_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.compute_routes(request) @@ -1605,6 +1606,7 @@ def test_compute_route_matrix_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} with mock.patch.object(response_value, "iter_content") as iter_content: iter_content.return_value = iter(json_return_value) @@ -1877,6 +1879,7 @@ def test_compute_routes_rest_bad_request( 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.compute_routes(request) @@ -1910,6 +1913,7 @@ def test_compute_routes_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.compute_routes(request) # Establish that the response is the type that we expect. @@ -1947,6 +1951,7 @@ def test_compute_routes_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 = routes_service.ComputeRoutesResponse.to_json( routes_service.ComputeRoutesResponse() ) @@ -1993,6 +1998,7 @@ def test_compute_route_matrix_rest_bad_request( 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.compute_route_matrix(request) @@ -2032,6 +2038,7 @@ def test_compute_route_matrix_rest_call_success(request_type): json_return_value = "[{}]".format(json_return_value) response_value.iter_content = mock.Mock(return_value=iter(json_return_value)) req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.compute_route_matrix(request) assert isinstance(response, Iterable) @@ -2076,6 +2083,7 @@ def test_compute_route_matrix_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 = routes_service.RouteMatrixElement.to_json( routes_service.RouteMatrixElement() ) diff --git a/packages/google-maps-solar/google/maps/solar/gapic_version.py b/packages/google-maps-solar/google/maps/solar/gapic_version.py index 937ede8823ef..558c8aab67c5 100644 --- a/packages/google-maps-solar/google/maps/solar/gapic_version.py +++ b/packages/google-maps-solar/google/maps/solar/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.4" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-maps-solar/google/maps/solar_v1/gapic_version.py b/packages/google-maps-solar/google/maps/solar_v1/gapic_version.py index 937ede8823ef..558c8aab67c5 100644 --- a/packages/google-maps-solar/google/maps/solar_v1/gapic_version.py +++ b/packages/google-maps-solar/google/maps/solar_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.4" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-maps-solar/google/maps/solar_v1/services/solar/async_client.py b/packages/google-maps-solar/google/maps/solar_v1/services/solar/async_client.py index 73899add5518..a966bdc57950 100644 --- a/packages/google-maps-solar/google/maps/solar_v1/services/solar/async_client.py +++ b/packages/google-maps-solar/google/maps/solar_v1/services/solar/async_client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import re from typing import ( Callable, @@ -53,6 +54,15 @@ from .transports.base import DEFAULT_CLIENT_INFO, SolarTransport from .transports.grpc_asyncio import SolarGrpcAsyncIOTransport +try: + from google.api_core import client_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 SolarAsyncClient: """Service definition for the Solar API.""" @@ -246,6 +256,28 @@ def __init__( client_info=client_info, ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.maps.solar_v1.SolarAsyncClient`.", + extra={ + "serviceName": "google.maps.solar.v1.Solar", + "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.maps.solar.v1.Solar", + "credentialsType": None, + }, + ) + async def find_closest_building_insights( self, request: Optional[ @@ -254,7 +286,7 @@ async def find_closest_building_insights( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> solar_service.BuildingInsights: r"""Locates the closest building to a query point. Returns an error with code ``NOT_FOUND`` if there are no buildings within @@ -292,8 +324,10 @@ async def sample_find_closest_building_insights(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.maps.solar_v1.types.BuildingInsights: @@ -334,7 +368,7 @@ async def get_data_layers( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> solar_service.DataLayers: r"""Gets solar information for a region surrounding a location. Returns an error with code ``NOT_FOUND`` if the location is @@ -372,8 +406,10 @@ async def sample_get_data_layers(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.maps.solar_v1.types.DataLayers: @@ -424,7 +460,7 @@ async def get_geo_tiff( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> httpbody_pb2.HttpBody: r"""Returns an image by its ID. @@ -460,8 +496,10 @@ async def sample_get_geo_tiff(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api.httpbody_pb2.HttpBody: diff --git a/packages/google-maps-solar/google/maps/solar_v1/services/solar/client.py b/packages/google-maps-solar/google/maps/solar_v1/services/solar/client.py index 41740884fecb..48fcc5a94162 100644 --- a/packages/google-maps-solar/google/maps/solar_v1/services/solar/client.py +++ b/packages/google-maps-solar/google/maps/solar_v1/services/solar/client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import os import re from typing import ( @@ -48,6 +49,15 @@ 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.api import httpbody_pb2 # type: ignore from google.protobuf import any_pb2 # type: ignore from google.type import date_pb2 # type: ignore @@ -558,6 +568,10 @@ def __init__( # 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( @@ -620,6 +634,29 @@ def __init__( 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.maps.solar_v1.SolarClient`.", + extra={ + "serviceName": "google.maps.solar.v1.Solar", + "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.maps.solar.v1.Solar", + "credentialsType": None, + }, + ) + def find_closest_building_insights( self, request: Optional[ @@ -628,7 +665,7 @@ def find_closest_building_insights( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> solar_service.BuildingInsights: r"""Locates the closest building to a query point. Returns an error with code ``NOT_FOUND`` if there are no buildings within @@ -666,8 +703,10 @@ def sample_find_closest_building_insights(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.maps.solar_v1.types.BuildingInsights: @@ -708,7 +747,7 @@ def get_data_layers( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> solar_service.DataLayers: r"""Gets solar information for a region surrounding a location. Returns an error with code ``NOT_FOUND`` if the location is @@ -746,8 +785,10 @@ def sample_get_data_layers(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.maps.solar_v1.types.DataLayers: @@ -796,7 +837,7 @@ def get_geo_tiff( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> httpbody_pb2.HttpBody: r"""Returns an image by its ID. @@ -832,8 +873,10 @@ def sample_get_geo_tiff(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api.httpbody_pb2.HttpBody: diff --git a/packages/google-maps-solar/google/maps/solar_v1/services/solar/transports/grpc.py b/packages/google-maps-solar/google/maps/solar_v1/services/solar/transports/grpc.py index 733317529da1..05659b774fc8 100644 --- a/packages/google-maps-solar/google/maps/solar_v1/services/solar/transports/grpc.py +++ b/packages/google-maps-solar/google/maps/solar_v1/services/solar/transports/grpc.py @@ -13,6 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import json +import logging as std_logging +import pickle from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -21,12 +24,90 @@ 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.maps.solar_v1.types import solar_service from .base import DEFAULT_CLIENT_INFO, SolarTransport +try: + from google.api_core import client_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.maps.solar.v1.Solar", + "rpcName": 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.maps.solar.v1.Solar", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + class SolarGrpcTransport(SolarTransport): """gRPC backend transport for Solar. @@ -180,7 +261,12 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -261,7 +347,7 @@ def find_closest_building_insights( if "find_closest_building_insights" not in self._stubs: self._stubs[ "find_closest_building_insights" - ] = self.grpc_channel.unary_unary( + ] = self._logged_channel.unary_unary( "/google.maps.solar.v1.Solar/FindClosestBuildingInsights", request_serializer=solar_service.FindClosestBuildingInsightsRequest.serialize, response_deserializer=solar_service.BuildingInsights.deserialize, @@ -289,7 +375,7 @@ def get_data_layers( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_data_layers" not in self._stubs: - self._stubs["get_data_layers"] = self.grpc_channel.unary_unary( + self._stubs["get_data_layers"] = self._logged_channel.unary_unary( "/google.maps.solar.v1.Solar/GetDataLayers", request_serializer=solar_service.GetDataLayersRequest.serialize, response_deserializer=solar_service.DataLayers.deserialize, @@ -315,7 +401,7 @@ def get_geo_tiff( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_geo_tiff" not in self._stubs: - self._stubs["get_geo_tiff"] = self.grpc_channel.unary_unary( + self._stubs["get_geo_tiff"] = self._logged_channel.unary_unary( "/google.maps.solar.v1.Solar/GetGeoTiff", request_serializer=solar_service.GetGeoTiffRequest.serialize, response_deserializer=httpbody_pb2.HttpBody.FromString, @@ -323,7 +409,7 @@ def get_geo_tiff( return self._stubs["get_geo_tiff"] def close(self): - self.grpc_channel.close() + self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-maps-solar/google/maps/solar_v1/services/solar/transports/grpc_asyncio.py b/packages/google-maps-solar/google/maps/solar_v1/services/solar/transports/grpc_asyncio.py index 920b24e85628..3eab671a7e04 100644 --- a/packages/google-maps-solar/google/maps/solar_v1/services/solar/transports/grpc_asyncio.py +++ b/packages/google-maps-solar/google/maps/solar_v1/services/solar/transports/grpc_asyncio.py @@ -14,6 +14,9 @@ # limitations under the License. # import inspect +import json +import logging as std_logging +import pickle from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -23,14 +26,93 @@ 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 from grpc.experimental import aio # type: ignore +import proto # type: ignore from google.maps.solar_v1.types import solar_service from .base import DEFAULT_CLIENT_INFO, SolarTransport from .grpc import SolarGrpcTransport +try: + from google.api_core import client_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.maps.solar.v1.Solar", + "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.maps.solar.v1.Solar", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + class SolarGrpcAsyncIOTransport(SolarTransport): """gRPC AsyncIO backend transport for Solar. @@ -227,10 +309,13 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -269,7 +354,7 @@ def find_closest_building_insights( if "find_closest_building_insights" not in self._stubs: self._stubs[ "find_closest_building_insights" - ] = self.grpc_channel.unary_unary( + ] = self._logged_channel.unary_unary( "/google.maps.solar.v1.Solar/FindClosestBuildingInsights", request_serializer=solar_service.FindClosestBuildingInsightsRequest.serialize, response_deserializer=solar_service.BuildingInsights.deserialize, @@ -299,7 +384,7 @@ def get_data_layers( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_data_layers" not in self._stubs: - self._stubs["get_data_layers"] = self.grpc_channel.unary_unary( + self._stubs["get_data_layers"] = self._logged_channel.unary_unary( "/google.maps.solar.v1.Solar/GetDataLayers", request_serializer=solar_service.GetDataLayersRequest.serialize, response_deserializer=solar_service.DataLayers.deserialize, @@ -325,7 +410,7 @@ def get_geo_tiff( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_geo_tiff" not in self._stubs: - self._stubs["get_geo_tiff"] = self.grpc_channel.unary_unary( + self._stubs["get_geo_tiff"] = self._logged_channel.unary_unary( "/google.maps.solar.v1.Solar/GetGeoTiff", request_serializer=solar_service.GetGeoTiffRequest.serialize, response_deserializer=httpbody_pb2.HttpBody.FromString, @@ -385,7 +470,7 @@ def _wrap_method(self, func, *args, **kwargs): return gapic_v1.method_async.wrap_method(func, *args, **kwargs) def close(self): - return self.grpc_channel.close() + return self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-maps-solar/google/maps/solar_v1/services/solar/transports/rest.py b/packages/google-maps-solar/google/maps/solar_v1/services/solar/transports/rest.py index 27123714fe7d..876ab8b0ffcd 100644 --- a/packages/google-maps-solar/google/maps/solar_v1/services/solar/transports/rest.py +++ b/packages/google-maps-solar/google/maps/solar_v1/services/solar/transports/rest.py @@ -13,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import dataclasses import json # type: ignore +import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings @@ -38,6 +38,14 @@ 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, @@ -94,9 +102,10 @@ def post_get_geo_tiff(self, response): def pre_find_closest_building_insights( self, request: solar_service.FindClosestBuildingInsightsRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - solar_service.FindClosestBuildingInsightsRequest, Sequence[Tuple[str, str]] + solar_service.FindClosestBuildingInsightsRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for find_closest_building_insights @@ -119,8 +128,10 @@ def post_find_closest_building_insights( def pre_get_data_layers( self, request: solar_service.GetDataLayersRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[solar_service.GetDataLayersRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + solar_service.GetDataLayersRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_data_layers Override in a subclass to manipulate the request or metadata @@ -142,8 +153,10 @@ def post_get_data_layers( def pre_get_geo_tiff( self, request: solar_service.GetGeoTiffRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[solar_service.GetGeoTiffRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + solar_service.GetGeoTiffRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_geo_tiff Override in a subclass to manipulate the request or metadata @@ -283,7 +296,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> solar_service.BuildingInsights: r"""Call the find closest building insights method over HTTP. @@ -295,8 +308,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.solar_service.BuildingInsights: @@ -310,6 +325,7 @@ def __call__( http_options = ( _BaseSolarRestTransport._BaseFindClosestBuildingInsights._get_http_options() ) + request, metadata = self._interceptor.pre_find_closest_building_insights( request, metadata ) @@ -322,6 +338,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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.maps.solar_v1.SolarClient.FindClosestBuildingInsights", + extra={ + "serviceName": "google.maps.solar.v1.Solar", + "rpcName": "FindClosestBuildingInsights", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = SolarRestTransport._FindClosestBuildingInsights._get_response( self._host, @@ -342,7 +385,29 @@ def __call__( pb_resp = solar_service.BuildingInsights.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_find_closest_building_insights(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = solar_service.BuildingInsights.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.maps.solar_v1.SolarClient.find_closest_building_insights", + extra={ + "serviceName": "google.maps.solar.v1.Solar", + "rpcName": "FindClosestBuildingInsights", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _GetDataLayers(_BaseSolarRestTransport._BaseGetDataLayers, SolarRestStub): @@ -377,7 +442,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> solar_service.DataLayers: r"""Call the get data layers method over HTTP. @@ -387,8 +452,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.solar_service.DataLayers: @@ -410,6 +477,7 @@ def __call__( http_options = ( _BaseSolarRestTransport._BaseGetDataLayers._get_http_options() ) + request, metadata = self._interceptor.pre_get_data_layers(request, metadata) transcoded_request = ( _BaseSolarRestTransport._BaseGetDataLayers._get_transcoded_request( @@ -424,6 +492,33 @@ def __call__( ) ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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.maps.solar_v1.SolarClient.GetDataLayers", + extra={ + "serviceName": "google.maps.solar.v1.Solar", + "rpcName": "GetDataLayers", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = SolarRestTransport._GetDataLayers._get_response( self._host, @@ -444,7 +539,29 @@ def __call__( pb_resp = solar_service.DataLayers.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_data_layers(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = solar_service.DataLayers.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.maps.solar_v1.SolarClient.get_data_layers", + extra={ + "serviceName": "google.maps.solar.v1.Solar", + "rpcName": "GetDataLayers", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _GetGeoTiff(_BaseSolarRestTransport._BaseGetGeoTiff, SolarRestStub): @@ -479,7 +596,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> httpbody_pb2.HttpBody: r"""Call the get geo tiff method over HTTP. @@ -489,8 +606,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.httpbody_pb2.HttpBody: @@ -547,6 +666,7 @@ def __call__( """ http_options = _BaseSolarRestTransport._BaseGetGeoTiff._get_http_options() + request, metadata = self._interceptor.pre_get_geo_tiff(request, metadata) transcoded_request = ( _BaseSolarRestTransport._BaseGetGeoTiff._get_transcoded_request( @@ -561,6 +681,33 @@ def __call__( ) ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + 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.maps.solar_v1.SolarClient.GetGeoTiff", + extra={ + "serviceName": "google.maps.solar.v1.Solar", + "rpcName": "GetGeoTiff", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = SolarRestTransport._GetGeoTiff._get_response( self._host, @@ -581,7 +728,29 @@ def __call__( pb_resp = resp json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_geo_tiff(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.maps.solar_v1.SolarClient.get_geo_tiff", + extra={ + "serviceName": "google.maps.solar.v1.Solar", + "rpcName": "GetGeoTiff", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp @property diff --git a/packages/google-maps-solar/samples/generated_samples/snippet_metadata_google.maps.solar.v1.json b/packages/google-maps-solar/samples/generated_samples/snippet_metadata_google.maps.solar.v1.json index 18729f320138..b0cd14fdb324 100644 --- a/packages/google-maps-solar/samples/generated_samples/snippet_metadata_google.maps.solar.v1.json +++ b/packages/google-maps-solar/samples/generated_samples/snippet_metadata_google.maps.solar.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-maps-solar", - "version": "0.1.4" + "version": "0.1.0" }, "snippets": [ { @@ -43,7 +43,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.maps.solar_v1.types.BuildingInsights", @@ -119,7 +119,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.maps.solar_v1.types.BuildingInsights", @@ -196,7 +196,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.maps.solar_v1.types.DataLayers", @@ -272,7 +272,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.maps.solar_v1.types.DataLayers", @@ -349,7 +349,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.api.httpbody_pb2.HttpBody", @@ -425,7 +425,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.api.httpbody_pb2.HttpBody", diff --git a/packages/google-maps-solar/tests/unit/gapic/solar_v1/test_solar.py b/packages/google-maps-solar/tests/unit/gapic/solar_v1/test_solar.py index c7a25577650d..3771905a07a0 100644 --- a/packages/google-maps-solar/tests/unit/gapic/solar_v1/test_solar.py +++ b/packages/google-maps-solar/tests/unit/gapic/solar_v1/test_solar.py @@ -1693,6 +1693,7 @@ def test_find_closest_building_insights_rest_required_fields( response_value._content = json_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_closest_building_insights(request) @@ -1837,6 +1838,7 @@ def test_get_data_layers_rest_required_fields( response_value._content = json_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_data_layers(request) @@ -1982,6 +1984,7 @@ def test_get_geo_tiff_rest_required_fields( response_value._content = json_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_geo_tiff(request) @@ -2313,6 +2316,7 @@ def test_find_closest_building_insights_rest_bad_request( 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_closest_building_insights(request) @@ -2353,6 +2357,7 @@ def test_find_closest_building_insights_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_closest_building_insights(request) # Establish that the response is the type that we expect. @@ -2396,6 +2401,7 @@ def test_find_closest_building_insights_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 = solar_service.BuildingInsights.to_json( solar_service.BuildingInsights() ) @@ -2442,6 +2448,7 @@ def test_get_data_layers_rest_bad_request( 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_data_layers(request) @@ -2483,6 +2490,7 @@ def test_get_data_layers_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_data_layers(request) # Establish that the response is the type that we expect. @@ -2527,6 +2535,7 @@ def test_get_data_layers_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 = solar_service.DataLayers.to_json(solar_service.DataLayers()) req.return_value.content = return_value @@ -2569,6 +2578,7 @@ def test_get_geo_tiff_rest_bad_request(request_type=solar_service.GetGeoTiffRequ 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_geo_tiff(request) @@ -2602,6 +2612,7 @@ def test_get_geo_tiff_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_geo_tiff(request) # Establish that the response is the type that we expect. @@ -2641,6 +2652,7 @@ def test_get_geo_tiff_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 = json_format.MessageToJson(httpbody_pb2.HttpBody()) req.return_value.content = return_value 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 d1a1a883babd..558c8aab67c5 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.2.2" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} 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 d1a1a883babd..558c8aab67c5 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.2.2" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_issue_service/async_client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_issue_service/async_client.py index 1cbc438a3fa5..0c4f7b7c70c1 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_issue_service/async_client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_issue_service/async_client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import re from typing import ( Callable, @@ -51,6 +52,15 @@ 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.""" @@ -264,6 +274,28 @@ def __init__( 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, @@ -271,7 +303,7 @@ async def list_account_issues( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListAccountIssuesAsyncPager: r"""Lists all account issues of a Merchant Center account. @@ -316,8 +348,10 @@ async def sample_list_account_issues(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_issue_service/client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_issue_service/client.py index f519f463d0c9..7b2617438d45 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_issue_service/client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_issue_service/client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import os import re from typing import ( @@ -48,6 +49,15 @@ 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, ) @@ -594,6 +604,10 @@ def __init__( # 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( @@ -660,6 +674,29 @@ def __init__( 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, @@ -667,7 +704,7 @@ def list_account_issues( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListAccountIssuesPager: r"""Lists all account issues of a Merchant Center account. @@ -712,8 +749,10 @@ def sample_list_account_issues(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_issue_service/pagers.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_issue_service/pagers.py index 0aef6d8bc843..2c02d846a735 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_issue_service/pagers.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_issue_service/pagers.py @@ -67,7 +67,7 @@ def __init__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiate the pager. @@ -81,8 +81,10 @@ def __init__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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) @@ -141,7 +143,7 @@ def __init__( *, retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiates the pager. @@ -155,8 +157,10 @@ def __init__( 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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) diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/grpc.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/grpc.py index 497d5655bac6..141540f0e5ab 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/grpc.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/grpc.py @@ -13,6 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import json +import logging as std_logging +import pickle from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -20,12 +23,90 @@ 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 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 + +_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": 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. @@ -179,7 +260,12 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -256,7 +342,7 @@ def list_account_issues( # 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.grpc_channel.unary_unary( + 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, @@ -264,7 +350,7 @@ def list_account_issues( return self._stubs["list_account_issues"] def close(self): - self.grpc_channel.close() + self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/grpc_asyncio.py index 240f7523f536..ec1db1b4df83 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/grpc_asyncio.py @@ -14,6 +14,9 @@ # limitations under the License. # import inspect +import json +import logging as std_logging +import pickle from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -22,14 +25,93 @@ 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 from grpc.experimental import aio # type: ignore +import proto # type: ignore from google.shopping.merchant_accounts_v1beta.types import accountissue 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 + +_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. @@ -226,10 +308,13 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -265,7 +350,7 @@ def list_account_issues( # 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.grpc_channel.unary_unary( + 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, @@ -288,7 +373,7 @@ def _wrap_method(self, func, *args, **kwargs): return gapic_v1.method_async.wrap_method(func, *args, **kwargs) def close(self): - return self.grpc_channel.close() + return self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/rest.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/rest.py index 00df2d37ee7c..f50f616ca4c4 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/rest.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/rest.py @@ -13,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import dataclasses import json # type: ignore +import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings @@ -37,6 +37,14 @@ 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, @@ -77,8 +85,10 @@ def post_list_account_issues(self, response): def pre_list_account_issues( self, request: accountissue.ListAccountIssuesRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[accountissue.ListAccountIssuesRequest, Sequence[Tuple[str, str]]]: + 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 @@ -219,7 +229,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> accountissue.ListAccountIssuesResponse: r"""Call the list account issues method over HTTP. @@ -229,8 +239,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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: @@ -240,6 +252,7 @@ def __call__( http_options = ( _BaseAccountIssueServiceRestTransport._BaseListAccountIssues._get_http_options() ) + request, metadata = self._interceptor.pre_list_account_issues( request, metadata ) @@ -252,6 +265,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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( @@ -274,7 +314,31 @@ def __call__( 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) + 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 diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_tax_service/async_client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_tax_service/async_client.py index 136885e029cb..ee92fa2ce59c 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_tax_service/async_client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_tax_service/async_client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import re from typing import ( Callable, @@ -55,6 +56,15 @@ from .transports.base import DEFAULT_CLIENT_INFO, AccountTaxServiceTransport from .transports.grpc_asyncio import AccountTaxServiceGrpcAsyncIOTransport +try: + from google.api_core import client_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. @@ -271,6 +281,28 @@ def __init__( 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, @@ -278,7 +310,7 @@ async def get_account_tax( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> account_tax.AccountTax: r"""Returns the tax rules that match the conditions of GetAccountTaxRequest @@ -322,8 +354,10 @@ async def sample_get_account_tax(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -385,7 +419,7 @@ async def list_account_tax( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListAccountTaxAsyncPager: r"""Lists the tax settings of the sub-accounts only in your Merchant Center account. @@ -437,8 +471,10 @@ async def sample_list_account_tax(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -517,7 +553,7 @@ async def update_account_tax( 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, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> gsma_account_tax.AccountTax: r"""Updates the tax settings of the account. @@ -564,8 +600,10 @@ async def sample_update_account_tax(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_tax_service/client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_tax_service/client.py index 40389337002c..e861d5641259 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_tax_service/client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_tax_service/client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import os import re from typing import ( @@ -48,6 +49,15 @@ 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 @@ -588,6 +598,10 @@ def __init__( # 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( @@ -654,6 +668,29 @@ def __init__( 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, @@ -661,7 +698,7 @@ def get_account_tax( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> account_tax.AccountTax: r"""Returns the tax rules that match the conditions of GetAccountTaxRequest @@ -705,8 +742,10 @@ def sample_get_account_tax(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -765,7 +804,7 @@ def list_account_tax( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListAccountTaxPager: r"""Lists the tax settings of the sub-accounts only in your Merchant Center account. @@ -817,8 +856,10 @@ def sample_list_account_tax(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -894,7 +935,7 @@ def update_account_tax( 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, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> gsma_account_tax.AccountTax: r"""Updates the tax settings of the account. @@ -941,8 +982,10 @@ def sample_update_account_tax(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_tax_service/pagers.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_tax_service/pagers.py index 21dd67c0076f..8ca74417eaf8 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_tax_service/pagers.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_tax_service/pagers.py @@ -67,7 +67,7 @@ def __init__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiate the pager. @@ -81,8 +81,10 @@ def __init__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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) @@ -141,7 +143,7 @@ def __init__( *, retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiates the pager. @@ -155,8 +157,10 @@ def __init__( 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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) diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/grpc.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/grpc.py index 4eb4c19924fc..4c975ab748d2 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/grpc.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/grpc.py @@ -13,6 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import json +import logging as std_logging +import pickle from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -20,7 +23,10 @@ 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 as gsma_account_tax, @@ -29,6 +35,81 @@ from .base import DEFAULT_CLIENT_INFO, AccountTaxServiceTransport +try: + from google.api_core import client_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": 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. @@ -186,7 +267,12 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -261,7 +347,7 @@ def get_account_tax( # 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.grpc_channel.unary_unary( + 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, @@ -292,7 +378,7 @@ def list_account_tax( # 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.grpc_channel.unary_unary( + 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, @@ -320,7 +406,7 @@ def update_account_tax( # 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.grpc_channel.unary_unary( + 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, @@ -328,7 +414,7 @@ def update_account_tax( return self._stubs["update_account_tax"] def close(self): - self.grpc_channel.close() + self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/grpc_asyncio.py index 620cf2c12ae6..68080d549d5b 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/grpc_asyncio.py @@ -14,6 +14,9 @@ # limitations under the License. # import inspect +import json +import logging as std_logging +import pickle from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -22,8 +25,11 @@ 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 from grpc.experimental import aio # type: ignore +import proto # type: ignore from google.shopping.merchant_accounts_v1beta.types import ( account_tax as gsma_account_tax, @@ -33,6 +39,82 @@ from .base import DEFAULT_CLIENT_INFO, AccountTaxServiceTransport 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. @@ -233,10 +315,13 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -271,7 +356,7 @@ def get_account_tax( # 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.grpc_channel.unary_unary( + 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, @@ -303,7 +388,7 @@ def list_account_tax( # 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.grpc_channel.unary_unary( + 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, @@ -332,7 +417,7 @@ def update_account_tax( # 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.grpc_channel.unary_unary( + 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, @@ -365,7 +450,7 @@ def _wrap_method(self, func, *args, **kwargs): return gapic_v1.method_async.wrap_method(func, *args, **kwargs) def close(self): - return self.grpc_channel.close() + return self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/rest.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/rest.py index abf839241aca..4c562090d9b4 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/rest.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/rest.py @@ -13,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import dataclasses import json # type: ignore +import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings @@ -40,6 +40,14 @@ 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, @@ -96,8 +104,10 @@ def post_update_account_tax(self, response): def pre_get_account_tax( self, request: account_tax.GetAccountTaxRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[account_tax.GetAccountTaxRequest, Sequence[Tuple[str, str]]]: + 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 @@ -119,8 +129,10 @@ def post_get_account_tax( def pre_list_account_tax( self, request: account_tax.ListAccountTaxRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[account_tax.ListAccountTaxRequest, Sequence[Tuple[str, str]]]: + 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 @@ -142,8 +154,11 @@ def post_list_account_tax( def pre_update_account_tax( self, request: gsma_account_tax.UpdateAccountTaxRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[gsma_account_tax.UpdateAccountTaxRequest, Sequence[Tuple[str, str]]]: + 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 @@ -288,7 +303,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> account_tax.AccountTax: r"""Call the get account tax method over HTTP. @@ -298,8 +313,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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: @@ -312,6 +329,7 @@ def __call__( 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 @@ -322,6 +340,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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, @@ -342,7 +387,29 @@ def __call__( 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) + 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( @@ -380,7 +447,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> account_tax.ListAccountTaxResponse: r"""Call the list account tax method over HTTP. @@ -394,8 +461,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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: @@ -409,6 +478,7 @@ def __call__( http_options = ( _BaseAccountTaxServiceRestTransport._BaseListAccountTax._get_http_options() ) + request, metadata = self._interceptor.pre_list_account_tax( request, metadata ) @@ -421,6 +491,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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, @@ -441,7 +538,31 @@ def __call__( 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) + 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( @@ -480,7 +601,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> gsma_account_tax.AccountTax: r"""Call the update account tax method over HTTP. @@ -490,8 +611,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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: @@ -504,6 +627,7 @@ def __call__( http_options = ( _BaseAccountTaxServiceRestTransport._BaseUpdateAccountTax._get_http_options() ) + request, metadata = self._interceptor.pre_update_account_tax( request, metadata ) @@ -520,6 +644,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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, @@ -541,7 +692,29 @@ def __call__( 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) + 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 diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/accounts_service/async_client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/accounts_service/async_client.py index 7a39ba6829d3..9149f44506dc 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/accounts_service/async_client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/accounts_service/async_client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import re from typing import ( Callable, @@ -52,6 +53,15 @@ 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.""" @@ -265,6 +275,28 @@ def __init__( 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, @@ -272,7 +304,7 @@ async def get_account( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> accounts.Account: r"""Retrieves an account from your Merchant Center account. After inserting, updating, or deleting an @@ -318,8 +350,10 @@ async def sample_get_account(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -379,7 +413,7 @@ async def create_and_configure_account( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + 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 @@ -422,8 +456,10 @@ async def sample_create_and_configure_account(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -462,7 +498,7 @@ async def delete_account( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + 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 @@ -508,8 +544,10 @@ async def sample_delete_account(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 @@ -562,7 +600,7 @@ async def update_account( 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, str]] = (), + 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 @@ -618,8 +656,10 @@ async def sample_update_account(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -681,7 +721,7 @@ async def list_accounts( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + 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 @@ -724,8 +764,10 @@ async def sample_list_accounts(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -779,7 +821,7 @@ async def list_sub_accounts( provider: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + 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`` @@ -827,8 +869,10 @@ async def sample_list_sub_accounts(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/accounts_service/client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/accounts_service/client.py index 574d711de7c2..b494944f8580 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/accounts_service/client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/accounts_service/client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import os import re from typing import ( @@ -48,6 +49,15 @@ 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.type import datetime_pb2 # type: ignore @@ -608,6 +618,10 @@ def __init__( # 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( @@ -673,6 +687,29 @@ def __init__( 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, @@ -680,7 +717,7 @@ def get_account( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> accounts.Account: r"""Retrieves an account from your Merchant Center account. After inserting, updating, or deleting an @@ -726,8 +763,10 @@ def sample_get_account(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -784,7 +823,7 @@ def create_and_configure_account( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + 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 @@ -827,8 +866,10 @@ def sample_create_and_configure_account(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -867,7 +908,7 @@ def delete_account( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + 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 @@ -913,8 +954,10 @@ def sample_delete_account(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 @@ -964,7 +1007,7 @@ def update_account( 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, str]] = (), + 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 @@ -1020,8 +1063,10 @@ def sample_update_account(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -1080,7 +1125,7 @@ def list_accounts( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + 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 @@ -1123,8 +1168,10 @@ def sample_list_accounts(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -1176,7 +1223,7 @@ def list_sub_accounts( provider: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + 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`` @@ -1224,8 +1271,10 @@ def sample_list_sub_accounts(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/accounts_service/pagers.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/accounts_service/pagers.py index 9c4d852d9a9b..de4f59a8bc09 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/accounts_service/pagers.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/accounts_service/pagers.py @@ -67,7 +67,7 @@ def __init__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiate the pager. @@ -81,8 +81,10 @@ def __init__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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) @@ -141,7 +143,7 @@ def __init__( *, retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiates the pager. @@ -155,8 +157,10 @@ def __init__( 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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) @@ -219,7 +223,7 @@ def __init__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiate the pager. @@ -233,8 +237,10 @@ def __init__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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) @@ -293,7 +299,7 @@ def __init__( *, retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiates the pager. @@ -307,8 +313,10 @@ def __init__( 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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) diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/grpc.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/grpc.py index c2c0d8c4abc7..f32791d4bfdb 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/grpc.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/grpc.py @@ -13,6 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import json +import logging as std_logging +import pickle from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -21,12 +24,90 @@ 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.shopping.merchant_accounts_v1beta.types import accounts 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 + +_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": 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. @@ -180,7 +261,12 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -255,7 +341,7 @@ def get_account(self) -> Callable[[accounts.GetAccountRequest], accounts.Account # 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.grpc_channel.unary_unary( + 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, @@ -283,7 +369,9 @@ def create_and_configure_account( # 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.grpc_channel.unary_unary( + 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, @@ -315,7 +403,7 @@ def delete_account( # 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.grpc_channel.unary_unary( + 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, @@ -343,7 +431,7 @@ def update_account( # 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.grpc_channel.unary_unary( + 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, @@ -376,7 +464,7 @@ def list_accounts( # 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.grpc_channel.unary_unary( + 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, @@ -406,7 +494,7 @@ def list_sub_accounts( # 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.grpc_channel.unary_unary( + 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, @@ -414,7 +502,7 @@ def list_sub_accounts( return self._stubs["list_sub_accounts"] def close(self): - self.grpc_channel.close() + self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/grpc_asyncio.py index 1e3d872aa0b2..18e8ed5ca3cd 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/grpc_asyncio.py @@ -14,6 +14,9 @@ # limitations under the License. # import inspect +import json +import logging as std_logging +import pickle from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -23,14 +26,93 @@ 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 from grpc.experimental import aio # type: ignore +import proto # type: ignore from google.shopping.merchant_accounts_v1beta.types import accounts 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 + +_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. @@ -227,10 +309,13 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -265,7 +350,7 @@ def get_account( # 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.grpc_channel.unary_unary( + 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, @@ -295,7 +380,9 @@ def create_and_configure_account( # 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.grpc_channel.unary_unary( + 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, @@ -327,7 +414,7 @@ def delete_account( # 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.grpc_channel.unary_unary( + 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, @@ -355,7 +442,7 @@ def update_account( # 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.grpc_channel.unary_unary( + 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, @@ -390,7 +477,7 @@ def list_accounts( # 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.grpc_channel.unary_unary( + 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, @@ -422,7 +509,7 @@ def list_sub_accounts( # 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.grpc_channel.unary_unary( + 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, @@ -470,7 +557,7 @@ def _wrap_method(self, func, *args, **kwargs): return gapic_v1.method_async.wrap_method(func, *args, **kwargs) def close(self): - return self.grpc_channel.close() + return self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/rest.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/rest.py index e497a179734f..ccc7fb9ca712 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/rest.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/rest.py @@ -13,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import dataclasses import json # type: ignore +import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings @@ -38,6 +38,14 @@ 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, @@ -114,8 +122,11 @@ def post_update_account(self, response): def pre_create_and_configure_account( self, request: accounts.CreateAndConfigureAccountRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[accounts.CreateAndConfigureAccountRequest, Sequence[Tuple[str, str]]]: + 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 @@ -137,8 +148,8 @@ def post_create_and_configure_account( def pre_delete_account( self, request: accounts.DeleteAccountRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[accounts.DeleteAccountRequest, Sequence[Tuple[str, str]]]: + 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 @@ -147,8 +158,10 @@ def pre_delete_account( return request, metadata def pre_get_account( - self, request: accounts.GetAccountRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[accounts.GetAccountRequest, Sequence[Tuple[str, str]]]: + 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 @@ -166,8 +179,10 @@ def post_get_account(self, response: accounts.Account) -> accounts.Account: return response def pre_list_accounts( - self, request: accounts.ListAccountsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[accounts.ListAccountsRequest, Sequence[Tuple[str, str]]]: + 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 @@ -189,8 +204,10 @@ def post_list_accounts( def pre_list_sub_accounts( self, request: accounts.ListSubAccountsRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[accounts.ListSubAccountsRequest, Sequence[Tuple[str, str]]]: + 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 @@ -212,8 +229,8 @@ def post_list_sub_accounts( def pre_update_account( self, request: accounts.UpdateAccountRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[accounts.UpdateAccountRequest, Sequence[Tuple[str, str]]]: + 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 @@ -353,7 +370,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> accounts.Account: r"""Call the create and configure account method over HTTP. @@ -365,8 +382,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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: @@ -376,6 +395,7 @@ def __call__( http_options = ( _BaseAccountsServiceRestTransport._BaseCreateAndConfigureAccount._get_http_options() ) + request, metadata = self._interceptor.pre_create_and_configure_account( request, metadata ) @@ -392,6 +412,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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( @@ -415,7 +462,29 @@ def __call__( 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) + 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( @@ -452,7 +521,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ): r"""Call the delete account method over HTTP. @@ -462,13 +531,16 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 @@ -479,6 +551,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + 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, @@ -528,7 +627,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> accounts.Account: r"""Call the get account method over HTTP. @@ -538,8 +637,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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: @@ -549,6 +650,7 @@ def __call__( 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 @@ -559,6 +661,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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, @@ -579,7 +708,29 @@ def __call__( pb_resp = accounts.Account.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_account(resp) + 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( @@ -616,7 +767,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> accounts.ListAccountsResponse: r"""Call the list accounts method over HTTP. @@ -626,8 +777,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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: @@ -637,6 +790,7 @@ def __call__( 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 @@ -647,6 +801,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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, @@ -667,7 +848,29 @@ def __call__( pb_resp = accounts.ListAccountsResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_accounts(resp) + 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( @@ -704,7 +907,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> accounts.ListSubAccountsResponse: r"""Call the list sub accounts method over HTTP. @@ -714,8 +917,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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: @@ -725,6 +930,7 @@ def __call__( http_options = ( _BaseAccountsServiceRestTransport._BaseListSubAccounts._get_http_options() ) + request, metadata = self._interceptor.pre_list_sub_accounts( request, metadata ) @@ -737,6 +943,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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, @@ -757,7 +990,31 @@ def __call__( 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) + 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( @@ -795,7 +1052,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> accounts.Account: r"""Call the update account method over HTTP. @@ -805,8 +1062,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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: @@ -816,6 +1075,7 @@ def __call__( 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 @@ -830,6 +1090,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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, @@ -851,7 +1138,29 @@ def __call__( pb_resp = accounts.Account.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_account(resp) + 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 diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/async_client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/async_client.py index e01855825f41..53f565e5f2f8 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/async_client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/async_client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import re from typing import ( Callable, @@ -50,6 +51,15 @@ 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 @@ -272,6 +282,28 @@ def __init__( 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[ @@ -281,7 +313,7 @@ async def get_autofeed_settings( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> autofeedsettings.AutofeedSettings: r"""Retrieves the autofeed settings of an account. @@ -324,8 +356,10 @@ async def sample_get_autofeed_settings(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -390,7 +424,7 @@ async def update_autofeed_settings( 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, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> autofeedsettings.AutofeedSettings: r"""Updates the autofeed settings of an account. @@ -444,8 +478,10 @@ async def sample_update_autofeed_settings(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/client.py index de84163f566e..7e539b0f9167 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import os import re from typing import ( @@ -48,6 +49,15 @@ 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 @@ -583,6 +593,10 @@ def __init__( # 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( @@ -649,6 +663,29 @@ def __init__( 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[ @@ -658,7 +695,7 @@ def get_autofeed_settings( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> autofeedsettings.AutofeedSettings: r"""Retrieves the autofeed settings of an account. @@ -701,8 +738,10 @@ def sample_get_autofeed_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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -764,7 +803,7 @@ def update_autofeed_settings( 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, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> autofeedsettings.AutofeedSettings: r"""Updates the autofeed settings of an account. @@ -818,8 +857,10 @@ def sample_update_autofeed_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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/grpc.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/grpc.py index dbe95388a05c..97e350f27a68 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/grpc.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/grpc.py @@ -13,6 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import json +import logging as std_logging +import pickle from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -20,12 +23,90 @@ 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 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 + +_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": 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. @@ -181,7 +262,12 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -257,7 +343,7 @@ def get_autofeed_settings( # 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.grpc_channel.unary_unary( + 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, @@ -286,7 +372,7 @@ def update_autofeed_settings( # 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.grpc_channel.unary_unary( + 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, @@ -294,7 +380,7 @@ def update_autofeed_settings( return self._stubs["update_autofeed_settings"] def close(self): - self.grpc_channel.close() + self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/grpc_asyncio.py index 8a3be82e594e..038d5a647270 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/grpc_asyncio.py @@ -14,6 +14,9 @@ # limitations under the License. # import inspect +import json +import logging as std_logging +import pickle from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -22,14 +25,93 @@ 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 from grpc.experimental import aio # type: ignore +import proto # type: ignore from google.shopping.merchant_accounts_v1beta.types import autofeedsettings 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 + +_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. @@ -228,10 +310,13 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -266,7 +351,7 @@ def get_autofeed_settings( # 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.grpc_channel.unary_unary( + 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, @@ -295,7 +380,7 @@ def update_autofeed_settings( # 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.grpc_channel.unary_unary( + 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, @@ -323,7 +408,7 @@ def _wrap_method(self, func, *args, **kwargs): return gapic_v1.method_async.wrap_method(func, *args, **kwargs) def close(self): - return self.grpc_channel.close() + return self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/rest.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/rest.py index 286471f99b66..c2b1813251d5 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/rest.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/rest.py @@ -13,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import dataclasses import json # type: ignore +import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings @@ -37,6 +37,14 @@ 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, @@ -85,8 +93,11 @@ def post_update_autofeed_settings(self, response): def pre_get_autofeed_settings( self, request: autofeedsettings.GetAutofeedSettingsRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[autofeedsettings.GetAutofeedSettingsRequest, Sequence[Tuple[str, str]]]: + 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 @@ -108,9 +119,10 @@ def post_get_autofeed_settings( def pre_update_autofeed_settings( self, request: autofeedsettings.UpdateAutofeedSettingsRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - autofeedsettings.UpdateAutofeedSettingsRequest, Sequence[Tuple[str, str]] + autofeedsettings.UpdateAutofeedSettingsRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for update_autofeed_settings @@ -254,7 +266,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> autofeedsettings.AutofeedSettings: r"""Call the get autofeed settings method over HTTP. @@ -264,8 +276,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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: @@ -278,6 +292,7 @@ def __call__( http_options = ( _BaseAutofeedSettingsServiceRestTransport._BaseGetAutofeedSettings._get_http_options() ) + request, metadata = self._interceptor.pre_get_autofeed_settings( request, metadata ) @@ -290,6 +305,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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( @@ -312,7 +354,31 @@ def __call__( 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) + 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( @@ -351,7 +417,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> autofeedsettings.AutofeedSettings: r"""Call the update autofeed settings method over HTTP. @@ -362,8 +428,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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: @@ -376,6 +444,7 @@ def __call__( http_options = ( _BaseAutofeedSettingsServiceRestTransport._BaseUpdateAutofeedSettings._get_http_options() ) + request, metadata = self._interceptor.pre_update_autofeed_settings( request, metadata ) @@ -392,6 +461,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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, @@ -413,7 +509,31 @@ def __call__( 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) + 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 diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/business_identity_service/async_client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/business_identity_service/async_client.py index 0961ffbb5ccc..fa62da4addea 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/business_identity_service/async_client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/business_identity_service/async_client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import re from typing import ( Callable, @@ -50,6 +51,15 @@ 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 @@ -272,6 +282,28 @@ def __init__( 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[ @@ -281,7 +313,7 @@ async def get_business_identity( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> businessidentity.BusinessIdentity: r"""Retrieves the business identity of an account. @@ -324,8 +356,10 @@ async def sample_get_business_identity(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -389,7 +423,7 @@ async def update_business_identity( 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, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> businessidentity.BusinessIdentity: r"""Updates the business identity of an account. Executing this method requires admin access. @@ -440,8 +474,10 @@ async def sample_update_business_identity(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/business_identity_service/client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/business_identity_service/client.py index ec0da6d3ff28..2dc21c12dd3d 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/business_identity_service/client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/business_identity_service/client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import os import re from typing import ( @@ -48,6 +49,15 @@ 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 @@ -583,6 +593,10 @@ def __init__( # 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( @@ -649,6 +663,29 @@ def __init__( 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[ @@ -658,7 +695,7 @@ def get_business_identity( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> businessidentity.BusinessIdentity: r"""Retrieves the business identity of an account. @@ -701,8 +738,10 @@ def sample_get_business_identity(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -763,7 +802,7 @@ def update_business_identity( 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, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> businessidentity.BusinessIdentity: r"""Updates the business identity of an account. Executing this method requires admin access. @@ -814,8 +853,10 @@ def sample_update_business_identity(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/grpc.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/grpc.py index eea782c1b6f9..1fb80e27ed79 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/grpc.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/grpc.py @@ -13,6 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import json +import logging as std_logging +import pickle from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -20,12 +23,90 @@ 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 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 + +_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": 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. @@ -181,7 +262,12 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -257,7 +343,7 @@ def get_business_identity( # 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.grpc_channel.unary_unary( + 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, @@ -287,7 +373,7 @@ def update_business_identity( # 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.grpc_channel.unary_unary( + 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, @@ -295,7 +381,7 @@ def update_business_identity( return self._stubs["update_business_identity"] def close(self): - self.grpc_channel.close() + self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/grpc_asyncio.py index cef1a65f4404..33fec1947411 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/grpc_asyncio.py @@ -14,6 +14,9 @@ # limitations under the License. # import inspect +import json +import logging as std_logging +import pickle from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -22,14 +25,93 @@ 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 from grpc.experimental import aio # type: ignore +import proto # type: ignore from google.shopping.merchant_accounts_v1beta.types import businessidentity 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 + +_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. @@ -228,10 +310,13 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -266,7 +351,7 @@ def get_business_identity( # 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.grpc_channel.unary_unary( + 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, @@ -296,7 +381,7 @@ def update_business_identity( # 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.grpc_channel.unary_unary( + 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, @@ -324,7 +409,7 @@ def _wrap_method(self, func, *args, **kwargs): return gapic_v1.method_async.wrap_method(func, *args, **kwargs) def close(self): - return self.grpc_channel.close() + return self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/rest.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/rest.py index 676645a4e162..56639f05a5cf 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/rest.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/rest.py @@ -13,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import dataclasses import json # type: ignore +import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings @@ -37,6 +37,14 @@ 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, @@ -85,8 +93,11 @@ def post_update_business_identity(self, response): def pre_get_business_identity( self, request: businessidentity.GetBusinessIdentityRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[businessidentity.GetBusinessIdentityRequest, Sequence[Tuple[str, str]]]: + 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 @@ -108,9 +119,10 @@ def post_get_business_identity( def pre_update_business_identity( self, request: businessidentity.UpdateBusinessIdentityRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - businessidentity.UpdateBusinessIdentityRequest, Sequence[Tuple[str, str]] + businessidentity.UpdateBusinessIdentityRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for update_business_identity @@ -254,7 +266,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> businessidentity.BusinessIdentity: r"""Call the get business identity method over HTTP. @@ -264,8 +276,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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: @@ -277,6 +291,7 @@ def __call__( http_options = ( _BaseBusinessIdentityServiceRestTransport._BaseGetBusinessIdentity._get_http_options() ) + request, metadata = self._interceptor.pre_get_business_identity( request, metadata ) @@ -289,6 +304,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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( @@ -311,7 +353,31 @@ def __call__( 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) + 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( @@ -350,7 +416,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> businessidentity.BusinessIdentity: r"""Call the update business identity method over HTTP. @@ -361,8 +427,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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: @@ -374,6 +442,7 @@ def __call__( http_options = ( _BaseBusinessIdentityServiceRestTransport._BaseUpdateBusinessIdentity._get_http_options() ) + request, metadata = self._interceptor.pre_update_business_identity( request, metadata ) @@ -390,6 +459,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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, @@ -411,7 +507,31 @@ def __call__( 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) + 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 diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/business_info_service/async_client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/business_info_service/async_client.py index 470d273018fa..cb2ca9f69deb 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/business_info_service/async_client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/business_info_service/async_client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import re from typing import ( Callable, @@ -56,6 +57,15 @@ 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.""" @@ -267,6 +277,28 @@ def __init__( 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, @@ -274,7 +306,7 @@ async def get_business_info( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> businessinfo.BusinessInfo: r"""Retrieves the business info of an account. @@ -317,8 +349,10 @@ async def sample_get_business_info(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -380,7 +414,7 @@ async def update_business_info( 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, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> businessinfo.BusinessInfo: r"""Updates the business info of an account. Executing this method requires admin access. @@ -430,8 +464,10 @@ async def sample_update_business_info(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/business_info_service/client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/business_info_service/client.py index cede5fac296a..78fc2fa851ff 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/business_info_service/client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/business_info_service/client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import os import re from typing import ( @@ -48,6 +49,15 @@ 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.type import phone_number_pb2 # type: ignore from google.type import postal_address_pb2 # type: ignore @@ -582,6 +592,10 @@ def __init__( # 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( @@ -648,6 +662,29 @@ def __init__( 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, @@ -655,7 +692,7 @@ def get_business_info( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> businessinfo.BusinessInfo: r"""Retrieves the business info of an account. @@ -698,8 +735,10 @@ def sample_get_business_info(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -758,7 +797,7 @@ def update_business_info( 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, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> businessinfo.BusinessInfo: r"""Updates the business info of an account. Executing this method requires admin access. @@ -808,8 +847,10 @@ def sample_update_business_info(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/grpc.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/grpc.py index b77bab780f35..e08ebbf7b6d2 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/grpc.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/grpc.py @@ -13,6 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import json +import logging as std_logging +import pickle from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -20,12 +23,90 @@ 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 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 + +_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": 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. @@ -179,7 +260,12 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -253,7 +339,7 @@ def get_business_info( # 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.grpc_channel.unary_unary( + 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, @@ -280,7 +366,7 @@ def update_business_info( # 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.grpc_channel.unary_unary( + 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, @@ -288,7 +374,7 @@ def update_business_info( return self._stubs["update_business_info"] def close(self): - self.grpc_channel.close() + self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/grpc_asyncio.py index e1c608c2ad30..c767585e9b0a 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/grpc_asyncio.py @@ -14,6 +14,9 @@ # limitations under the License. # import inspect +import json +import logging as std_logging +import pickle from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -22,14 +25,93 @@ 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 from grpc.experimental import aio # type: ignore +import proto # type: ignore from google.shopping.merchant_accounts_v1beta.types import businessinfo 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 + +_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. @@ -226,10 +308,13 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -263,7 +348,7 @@ def get_business_info( # 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.grpc_channel.unary_unary( + 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, @@ -292,7 +377,7 @@ def update_business_info( # 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.grpc_channel.unary_unary( + 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, @@ -320,7 +405,7 @@ def _wrap_method(self, func, *args, **kwargs): return gapic_v1.method_async.wrap_method(func, *args, **kwargs) def close(self): - return self.grpc_channel.close() + return self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/rest.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/rest.py index 7de136978256..27e29fd0e255 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/rest.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/rest.py @@ -13,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import dataclasses import json # type: ignore +import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings @@ -37,6 +37,14 @@ 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, @@ -85,8 +93,10 @@ def post_update_business_info(self, response): def pre_get_business_info( self, request: businessinfo.GetBusinessInfoRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[businessinfo.GetBusinessInfoRequest, Sequence[Tuple[str, str]]]: + 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 @@ -108,8 +118,10 @@ def post_get_business_info( def pre_update_business_info( self, request: businessinfo.UpdateBusinessInfoRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[businessinfo.UpdateBusinessInfoRequest, Sequence[Tuple[str, str]]]: + 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 @@ -250,7 +262,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> businessinfo.BusinessInfo: r"""Call the get business info method over HTTP. @@ -260,8 +272,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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: @@ -273,6 +287,7 @@ def __call__( http_options = ( _BaseBusinessInfoServiceRestTransport._BaseGetBusinessInfo._get_http_options() ) + request, metadata = self._interceptor.pre_get_business_info( request, metadata ) @@ -285,6 +300,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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, @@ -305,7 +347,29 @@ def __call__( 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) + 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( @@ -344,7 +408,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> businessinfo.BusinessInfo: r"""Call the update business info method over HTTP. @@ -354,8 +418,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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: @@ -367,6 +433,7 @@ def __call__( http_options = ( _BaseBusinessInfoServiceRestTransport._BaseUpdateBusinessInfo._get_http_options() ) + request, metadata = self._interceptor.pre_update_business_info( request, metadata ) @@ -383,6 +450,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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( @@ -406,7 +500,29 @@ def __call__( 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) + 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 diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/async_client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/async_client.py index 024febb291db..79f1ddd99f91 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/async_client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/async_client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import re from typing import ( Callable, @@ -50,6 +51,15 @@ 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. @@ -273,6 +283,28 @@ def __init__( 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[ @@ -282,7 +314,7 @@ async def get_email_preferences( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> emailpreferences.EmailPreferences: r"""Returns the email preferences for a Merchant Center account user. @@ -331,8 +363,10 @@ async def sample_get_email_preferences(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -399,7 +433,7 @@ async def update_email_preferences( 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, str]] = (), + 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 @@ -460,8 +494,10 @@ async def sample_update_email_preferences(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/client.py index c0c5ae0e2911..db65e710fa86 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import os import re from typing import ( @@ -48,6 +49,15 @@ 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 @@ -588,6 +598,10 @@ def __init__( # 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( @@ -654,6 +668,29 @@ def __init__( 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[ @@ -663,7 +700,7 @@ def get_email_preferences( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> emailpreferences.EmailPreferences: r"""Returns the email preferences for a Merchant Center account user. @@ -712,8 +749,10 @@ def sample_get_email_preferences(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -777,7 +816,7 @@ def update_email_preferences( 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, str]] = (), + 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 @@ -838,8 +877,10 @@ def sample_update_email_preferences(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/grpc.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/grpc.py index 79b98addeaa5..ec91f5e79ac0 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/grpc.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/grpc.py @@ -13,6 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import json +import logging as std_logging +import pickle from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -20,12 +23,90 @@ 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 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 + +_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": 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. @@ -182,7 +263,12 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -262,7 +348,7 @@ def get_email_preferences( # 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.grpc_channel.unary_unary( + 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, @@ -302,7 +388,7 @@ def update_email_preferences( # 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.grpc_channel.unary_unary( + 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, @@ -310,7 +396,7 @@ def update_email_preferences( return self._stubs["update_email_preferences"] def close(self): - self.grpc_channel.close() + self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/grpc_asyncio.py index 650ebee527de..2f5a29bc3758 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/grpc_asyncio.py @@ -14,6 +14,9 @@ # limitations under the License. # import inspect +import json +import logging as std_logging +import pickle from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -22,14 +25,93 @@ 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 from grpc.experimental import aio # type: ignore +import proto # type: ignore from google.shopping.merchant_accounts_v1beta.types import emailpreferences 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 + +_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. @@ -229,10 +311,13 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -271,7 +356,7 @@ def get_email_preferences( # 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.grpc_channel.unary_unary( + 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, @@ -311,7 +396,7 @@ def update_email_preferences( # 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.grpc_channel.unary_unary( + 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, @@ -339,7 +424,7 @@ def _wrap_method(self, func, *args, **kwargs): return gapic_v1.method_async.wrap_method(func, *args, **kwargs) def close(self): - return self.grpc_channel.close() + return self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/rest.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/rest.py index 42876f3e5661..28c774418566 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/rest.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/rest.py @@ -13,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import dataclasses import json # type: ignore +import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings @@ -37,6 +37,14 @@ 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, @@ -85,8 +93,11 @@ def post_update_email_preferences(self, response): def pre_get_email_preferences( self, request: emailpreferences.GetEmailPreferencesRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[emailpreferences.GetEmailPreferencesRequest, Sequence[Tuple[str, str]]]: + 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 @@ -108,9 +119,10 @@ def post_get_email_preferences( def pre_update_email_preferences( self, request: emailpreferences.UpdateEmailPreferencesRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - emailpreferences.UpdateEmailPreferencesRequest, Sequence[Tuple[str, str]] + emailpreferences.UpdateEmailPreferencesRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for update_email_preferences @@ -255,7 +267,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> emailpreferences.EmailPreferences: r"""Call the get email preferences method over HTTP. @@ -266,8 +278,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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: @@ -282,6 +296,7 @@ def __call__( http_options = ( _BaseEmailPreferencesServiceRestTransport._BaseGetEmailPreferences._get_http_options() ) + request, metadata = self._interceptor.pre_get_email_preferences( request, metadata ) @@ -294,6 +309,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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( @@ -316,7 +358,31 @@ def __call__( 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) + 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( @@ -355,7 +421,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> emailpreferences.EmailPreferences: r"""Call the update email preferences method over HTTP. @@ -366,8 +432,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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: @@ -382,6 +450,7 @@ def __call__( http_options = ( _BaseEmailPreferencesServiceRestTransport._BaseUpdateEmailPreferences._get_http_options() ) + request, metadata = self._interceptor.pre_update_email_preferences( request, metadata ) @@ -398,6 +467,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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, @@ -419,7 +515,31 @@ def __call__( 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) + 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 diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/homepage_service/async_client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/homepage_service/async_client.py index 54e31ed88a03..d0c05fe4a457 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/homepage_service/async_client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/homepage_service/async_client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import re from typing import ( Callable, @@ -51,6 +52,15 @@ 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.""" @@ -258,6 +268,28 @@ def __init__( 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, @@ -265,7 +297,7 @@ async def get_homepage( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> homepage.Homepage: r"""Retrieves a store's homepage. @@ -308,8 +340,10 @@ async def sample_get_homepage(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -369,7 +403,7 @@ async def update_homepage( 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, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> gsma_homepage.Homepage: r"""Updates a store's homepage. Executing this method requires admin access. @@ -419,8 +453,10 @@ async def sample_update_homepage(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -482,7 +518,7 @@ async def claim_homepage( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> homepage.Homepage: r"""Claims a store's homepage. Executing this method requires admin access. @@ -530,8 +566,10 @@ async def sample_claim_homepage(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -575,7 +613,7 @@ async def unclaim_homepage( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> homepage.Homepage: r"""Unclaims a store's homepage. Executing this method requires admin access. @@ -612,8 +650,10 @@ async def sample_unclaim_homepage(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/homepage_service/client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/homepage_service/client.py index feba2a7d395c..358914a9dece 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/homepage_service/client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/homepage_service/client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import os import re from typing import ( @@ -48,6 +49,15 @@ 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 as gsma_homepage @@ -575,6 +585,10 @@ def __init__( # 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( @@ -640,6 +654,29 @@ def __init__( 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, @@ -647,7 +684,7 @@ def get_homepage( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> homepage.Homepage: r"""Retrieves a store's homepage. @@ -690,8 +727,10 @@ def sample_get_homepage(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -748,7 +787,7 @@ def update_homepage( 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, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> gsma_homepage.Homepage: r"""Updates a store's homepage. Executing this method requires admin access. @@ -798,8 +837,10 @@ def sample_update_homepage(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -858,7 +899,7 @@ def claim_homepage( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> homepage.Homepage: r"""Claims a store's homepage. Executing this method requires admin access. @@ -906,8 +947,10 @@ def sample_claim_homepage(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -949,7 +992,7 @@ def unclaim_homepage( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> homepage.Homepage: r"""Unclaims a store's homepage. Executing this method requires admin access. @@ -986,8 +1029,10 @@ def sample_unclaim_homepage(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/grpc.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/grpc.py index 8b9a4a317a7d..464fc04a181b 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/grpc.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/grpc.py @@ -13,6 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import json +import logging as std_logging +import pickle from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -20,13 +23,91 @@ 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 as gsma_homepage from google.shopping.merchant_accounts_v1beta.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 + +_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": 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. @@ -180,7 +261,12 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -254,7 +340,7 @@ def get_homepage( # 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.grpc_channel.unary_unary( + 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, @@ -281,7 +367,7 @@ def update_homepage( # 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.grpc_channel.unary_unary( + 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, @@ -319,7 +405,7 @@ def claim_homepage( # 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.grpc_channel.unary_unary( + 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, @@ -346,7 +432,7 @@ def unclaim_homepage( # 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.grpc_channel.unary_unary( + 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, @@ -354,7 +440,7 @@ def unclaim_homepage( return self._stubs["unclaim_homepage"] def close(self): - self.grpc_channel.close() + self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/grpc_asyncio.py index b6a09e6a7af3..53f9c814bc1a 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/grpc_asyncio.py @@ -14,6 +14,9 @@ # limitations under the License. # import inspect +import json +import logging as std_logging +import pickle from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -22,8 +25,11 @@ 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 from grpc.experimental import aio # type: ignore +import proto # type: ignore from google.shopping.merchant_accounts_v1beta.types import homepage as gsma_homepage from google.shopping.merchant_accounts_v1beta.types import homepage @@ -31,6 +37,82 @@ 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 + +_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. @@ -227,10 +309,13 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -262,7 +347,7 @@ def get_homepage( # 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.grpc_channel.unary_unary( + 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, @@ -291,7 +376,7 @@ def update_homepage( # 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.grpc_channel.unary_unary( + 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, @@ -329,7 +414,7 @@ def claim_homepage( # 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.grpc_channel.unary_unary( + 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, @@ -356,7 +441,7 @@ def unclaim_homepage( # 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.grpc_channel.unary_unary( + 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, @@ -394,7 +479,7 @@ def _wrap_method(self, func, *args, **kwargs): return gapic_v1.method_async.wrap_method(func, *args, **kwargs) def close(self): - return self.grpc_channel.close() + return self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/rest.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/rest.py index 75e036c32d11..f39ea3706937 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/rest.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/rest.py @@ -13,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import dataclasses import json # type: ignore +import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings @@ -38,6 +38,14 @@ 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, @@ -102,8 +110,8 @@ def post_update_homepage(self, response): def pre_claim_homepage( self, request: homepage.ClaimHomepageRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[homepage.ClaimHomepageRequest, Sequence[Tuple[str, str]]]: + 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 @@ -121,8 +129,10 @@ def post_claim_homepage(self, response: homepage.Homepage) -> homepage.Homepage: return response def pre_get_homepage( - self, request: homepage.GetHomepageRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[homepage.GetHomepageRequest, Sequence[Tuple[str, str]]]: + 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 @@ -142,8 +152,10 @@ def post_get_homepage(self, response: homepage.Homepage) -> homepage.Homepage: def pre_unclaim_homepage( self, request: homepage.UnclaimHomepageRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[homepage.UnclaimHomepageRequest, Sequence[Tuple[str, str]]]: + 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 @@ -163,8 +175,10 @@ def post_unclaim_homepage(self, response: homepage.Homepage) -> homepage.Homepag def pre_update_homepage( self, request: gsma_homepage.UpdateHomepageRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[gsma_homepage.UpdateHomepageRequest, Sequence[Tuple[str, str]]]: + 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 @@ -305,7 +319,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> homepage.Homepage: r"""Call the claim homepage method over HTTP. @@ -315,8 +329,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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: @@ -326,6 +342,7 @@ def __call__( 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 @@ -340,6 +357,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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, @@ -361,7 +405,29 @@ def __call__( pb_resp = homepage.Homepage.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_claim_homepage(resp) + 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( @@ -398,7 +464,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> homepage.Homepage: r"""Call the get homepage method over HTTP. @@ -408,8 +474,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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: @@ -419,6 +487,7 @@ def __call__( 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 @@ -429,6 +498,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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, @@ -449,7 +545,29 @@ def __call__( pb_resp = homepage.Homepage.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_homepage(resp) + 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( @@ -487,7 +605,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> homepage.Homepage: r"""Call the unclaim homepage method over HTTP. @@ -497,8 +615,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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: @@ -508,6 +628,7 @@ def __call__( http_options = ( _BaseHomepageServiceRestTransport._BaseUnclaimHomepage._get_http_options() ) + request, metadata = self._interceptor.pre_unclaim_homepage( request, metadata ) @@ -524,6 +645,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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, @@ -545,7 +693,29 @@ def __call__( pb_resp = homepage.Homepage.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_unclaim_homepage(resp) + 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( @@ -583,7 +753,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> gsma_homepage.Homepage: r"""Call the update homepage method over HTTP. @@ -593,8 +763,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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: @@ -604,6 +776,7 @@ def __call__( 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 @@ -618,6 +791,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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, @@ -639,7 +839,29 @@ def __call__( 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) + 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 diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/async_client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/async_client.py index 8806d4a0a30f..eb71baa2a690 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/async_client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/async_client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import re from typing import ( Callable, @@ -51,6 +52,15 @@ 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 merchant's remorse @@ -278,6 +288,28 @@ def __init__( 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[ @@ -287,7 +319,7 @@ async def get_online_return_policy( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> online_return_policy.OnlineReturnPolicy: r"""Gets an existing return policy. @@ -332,8 +364,10 @@ async def sample_get_online_return_policy(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -397,7 +431,7 @@ async def list_online_return_policies( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListOnlineReturnPoliciesAsyncPager: r"""Lists all existing return policies. @@ -442,8 +476,10 @@ async def sample_list_online_return_policies(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/client.py index 9bf18f7a1713..893b5fcc9a31 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import os import re from typing import ( @@ -48,6 +49,15 @@ 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.online_return_policy_service import ( pagers, ) @@ -592,6 +602,10 @@ def __init__( # 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( @@ -658,6 +672,29 @@ def __init__( 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[ @@ -667,7 +704,7 @@ def get_online_return_policy( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> online_return_policy.OnlineReturnPolicy: r"""Gets an existing return policy. @@ -712,8 +749,10 @@ def sample_get_online_return_policy(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -774,7 +813,7 @@ def list_online_return_policies( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListOnlineReturnPoliciesPager: r"""Lists all existing return policies. @@ -819,8 +858,10 @@ def sample_list_online_return_policies(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/pagers.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/pagers.py index f52f0dba5a7c..455c80d91408 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/pagers.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/pagers.py @@ -67,7 +67,7 @@ def __init__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiate the pager. @@ -81,8 +81,10 @@ def __init__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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) @@ -143,7 +145,7 @@ def __init__( *, retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiates the pager. @@ -157,8 +159,10 @@ def __init__( 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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) diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/grpc.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/grpc.py index a8d881201cc9..204ded1e558c 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/grpc.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/grpc.py @@ -13,6 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import json +import logging as std_logging +import pickle from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -20,12 +23,90 @@ 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 online_return_policy 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 + +_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": 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. @@ -184,7 +265,12 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -261,7 +347,7 @@ def get_online_return_policy( # 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.grpc_channel.unary_unary( + 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, @@ -290,7 +376,9 @@ def list_online_return_policies( # 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.grpc_channel.unary_unary( + 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, @@ -298,7 +386,7 @@ def list_online_return_policies( return self._stubs["list_online_return_policies"] def close(self): - self.grpc_channel.close() + self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/grpc_asyncio.py index 1b0f450584ee..8e811e428e8d 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/grpc_asyncio.py @@ -14,6 +14,9 @@ # limitations under the License. # import inspect +import json +import logging as std_logging +import pickle from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -22,14 +25,93 @@ 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 from grpc.experimental import aio # type: ignore +import proto # type: ignore from google.shopping.merchant_accounts_v1beta.types import online_return_policy 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 + +_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. @@ -231,10 +313,13 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -269,7 +354,7 @@ def get_online_return_policy( # 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.grpc_channel.unary_unary( + 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, @@ -298,7 +383,9 @@ def list_online_return_policies( # 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.grpc_channel.unary_unary( + 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, @@ -326,7 +413,7 @@ def _wrap_method(self, func, *args, **kwargs): return gapic_v1.method_async.wrap_method(func, *args, **kwargs) def close(self): - return self.grpc_channel.close() + return self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/rest.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/rest.py index 61874b2f4e85..4efb4dd8e9eb 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/rest.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/rest.py @@ -13,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import dataclasses import json # type: ignore +import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings @@ -37,6 +37,14 @@ 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, @@ -85,9 +93,10 @@ def post_list_online_return_policies(self, response): def pre_get_online_return_policy( self, request: online_return_policy.GetOnlineReturnPolicyRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - online_return_policy.GetOnlineReturnPolicyRequest, Sequence[Tuple[str, str]] + online_return_policy.GetOnlineReturnPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for get_online_return_policy @@ -110,9 +119,10 @@ def post_get_online_return_policy( def pre_list_online_return_policies( self, request: online_return_policy.ListOnlineReturnPoliciesRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - online_return_policy.ListOnlineReturnPoliciesRequest, Sequence[Tuple[str, str]] + online_return_policy.ListOnlineReturnPoliciesRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for list_online_return_policies @@ -263,7 +273,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> online_return_policy.OnlineReturnPolicy: r"""Call the get online return policy method over HTTP. @@ -274,8 +284,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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: @@ -289,6 +301,7 @@ def __call__( http_options = ( _BaseOnlineReturnPolicyServiceRestTransport._BaseGetOnlineReturnPolicy._get_http_options() ) + request, metadata = self._interceptor.pre_get_online_return_policy( request, metadata ) @@ -301,6 +314,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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, @@ -321,7 +361,31 @@ def __call__( 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) + 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( @@ -361,7 +425,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> online_return_policy.ListOnlineReturnPoliciesResponse: r"""Call the list online return policies method over HTTP. @@ -373,8 +437,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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: @@ -386,6 +452,7 @@ def __call__( http_options = ( _BaseOnlineReturnPolicyServiceRestTransport._BaseListOnlineReturnPolicies._get_http_options() ) + request, metadata = self._interceptor.pre_list_online_return_policies( request, metadata ) @@ -398,6 +465,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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, @@ -418,7 +512,33 @@ def __call__( 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) + 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 @property diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/programs_service/async_client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/programs_service/async_client.py index 91f454d23bcc..ca68af8de955 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/programs_service/async_client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/programs_service/async_client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import re from typing import ( Callable, @@ -49,6 +50,15 @@ 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. @@ -267,6 +277,28 @@ def __init__( 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, @@ -274,7 +306,7 @@ async def get_program( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> programs.Program: r"""Retrieves the specified program for the account. @@ -318,8 +350,10 @@ async def sample_get_program(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -387,7 +421,7 @@ async def list_programs( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListProgramsAsyncPager: r"""Retrieves all programs for the account. @@ -432,8 +466,10 @@ async def sample_list_programs(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -508,7 +544,7 @@ async def enable_program( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + 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. @@ -554,8 +590,10 @@ async def sample_enable_program(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -623,7 +661,7 @@ async def disable_program( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> programs.Program: r"""Disable participation in the specified program for the account. Executing this method requires admin @@ -670,8 +708,10 @@ async def sample_disable_program(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/programs_service/client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/programs_service/client.py index 5f27afb0e040..d1c7f8a239c2 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/programs_service/client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/programs_service/client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import os import re from typing import ( @@ -48,6 +49,15 @@ 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 @@ -586,6 +596,10 @@ def __init__( # 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( @@ -651,6 +665,29 @@ def __init__( 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, @@ -658,7 +695,7 @@ def get_program( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> programs.Program: r"""Retrieves the specified program for the account. @@ -702,8 +739,10 @@ def sample_get_program(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -768,7 +807,7 @@ def list_programs( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListProgramsPager: r"""Retrieves all programs for the account. @@ -813,8 +852,10 @@ def sample_list_programs(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -886,7 +927,7 @@ def enable_program( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + 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. @@ -932,8 +973,10 @@ def sample_enable_program(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -998,7 +1041,7 @@ def disable_program( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> programs.Program: r"""Disable participation in the specified program for the account. Executing this method requires admin @@ -1045,8 +1088,10 @@ def sample_disable_program(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/programs_service/pagers.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/programs_service/pagers.py index 5c13da592ed3..497ad2f88007 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/programs_service/pagers.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/programs_service/pagers.py @@ -67,7 +67,7 @@ def __init__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiate the pager. @@ -81,8 +81,10 @@ def __init__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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) @@ -141,7 +143,7 @@ def __init__( *, retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiates the pager. @@ -155,8 +157,10 @@ def __init__( 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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) diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/grpc.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/grpc.py index 91b9f3bbdc5f..b060d02a4a3f 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/grpc.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/grpc.py @@ -13,6 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import json +import logging as std_logging +import pickle from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -20,12 +23,90 @@ 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 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 + +_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": 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. @@ -189,7 +270,12 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -261,7 +347,7 @@ def get_program(self) -> Callable[[programs.GetProgramRequest], programs.Program # 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.grpc_channel.unary_unary( + 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, @@ -287,7 +373,7 @@ def list_programs( # 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.grpc_channel.unary_unary( + 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, @@ -314,7 +400,7 @@ def enable_program( # 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.grpc_channel.unary_unary( + 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, @@ -342,7 +428,7 @@ def disable_program( # 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.grpc_channel.unary_unary( + 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, @@ -350,7 +436,7 @@ def disable_program( return self._stubs["disable_program"] def close(self): - self.grpc_channel.close() + self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/grpc_asyncio.py index aac76bd3629b..96a69767ca4e 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/grpc_asyncio.py @@ -14,6 +14,9 @@ # limitations under the License. # import inspect +import json +import logging as std_logging +import pickle from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -22,14 +25,93 @@ 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 from grpc.experimental import aio # type: ignore +import proto # type: ignore from google.shopping.merchant_accounts_v1beta.types import programs 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 + +_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. @@ -236,10 +318,13 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -271,7 +356,7 @@ def get_program( # 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.grpc_channel.unary_unary( + 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, @@ -299,7 +384,7 @@ def list_programs( # 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.grpc_channel.unary_unary( + 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, @@ -326,7 +411,7 @@ def enable_program( # 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.grpc_channel.unary_unary( + 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, @@ -354,7 +439,7 @@ def disable_program( # 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.grpc_channel.unary_unary( + 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, @@ -392,7 +477,7 @@ def _wrap_method(self, func, *args, **kwargs): return gapic_v1.method_async.wrap_method(func, *args, **kwargs) def close(self): - return self.grpc_channel.close() + return self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/rest.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/rest.py index 9b7a57ef5356..58a305791fd0 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/rest.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/rest.py @@ -13,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import dataclasses import json # type: ignore +import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings @@ -37,6 +37,14 @@ 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, @@ -101,8 +109,8 @@ def post_list_programs(self, response): def pre_disable_program( self, request: programs.DisableProgramRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[programs.DisableProgramRequest, Sequence[Tuple[str, str]]]: + 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 @@ -122,8 +130,8 @@ def post_disable_program(self, response: programs.Program) -> programs.Program: def pre_enable_program( self, request: programs.EnableProgramRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[programs.EnableProgramRequest, Sequence[Tuple[str, str]]]: + 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 @@ -141,8 +149,10 @@ def post_enable_program(self, response: programs.Program) -> programs.Program: return response def pre_get_program( - self, request: programs.GetProgramRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[programs.GetProgramRequest, Sequence[Tuple[str, str]]]: + 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 @@ -160,8 +170,10 @@ def post_get_program(self, response: programs.Program) -> programs.Program: return response def pre_list_programs( - self, request: programs.ListProgramsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[programs.ListProgramsRequest, Sequence[Tuple[str, str]]]: + 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 @@ -312,7 +324,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> programs.Program: r"""Call the disable program method over HTTP. @@ -323,8 +335,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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: @@ -343,6 +357,7 @@ def __call__( 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 @@ -357,6 +372,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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, @@ -378,7 +420,29 @@ def __call__( pb_resp = programs.Program.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_disable_program(resp) + 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( @@ -416,7 +480,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> programs.Program: r"""Call the enable program method over HTTP. @@ -427,8 +491,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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: @@ -447,6 +513,7 @@ def __call__( 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 @@ -461,6 +528,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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, @@ -482,7 +576,29 @@ def __call__( pb_resp = programs.Program.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_enable_program(resp) + 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( @@ -519,7 +635,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> programs.Program: r"""Call the get program method over HTTP. @@ -530,8 +646,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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: @@ -550,6 +668,7 @@ def __call__( 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 @@ -560,6 +679,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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, @@ -580,7 +726,29 @@ def __call__( pb_resp = programs.Program.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_program(resp) + 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( @@ -617,7 +785,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> programs.ListProgramsResponse: r"""Call the list programs method over HTTP. @@ -628,8 +796,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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: @@ -641,6 +811,7 @@ def __call__( 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 @@ -651,6 +822,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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, @@ -671,7 +869,29 @@ def __call__( pb_resp = programs.ListProgramsResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_programs(resp) + 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 diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/regions_service/async_client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/regions_service/async_client.py index 2ab9b5c1a99b..bb3cef1dc6bd 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/regions_service/async_client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/regions_service/async_client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import re from typing import ( Callable, @@ -52,6 +53,15 @@ 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. @@ -264,6 +274,28 @@ def __init__( 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, @@ -271,7 +303,7 @@ async def get_region( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> regions.Region: r"""Retrieves a region defined in your Merchant Center account. @@ -315,8 +347,10 @@ async def sample_get_region(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -384,7 +418,7 @@ async def create_region( region_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + 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. @@ -442,8 +476,10 @@ async def sample_create_region(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -514,7 +550,7 @@ async def update_region( 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, str]] = (), + 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. @@ -563,8 +599,10 @@ async def sample_update_region(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -634,7 +672,7 @@ async def delete_region( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: r"""Deletes a region definition from your Merchant Center account. Executing this method requires admin access. @@ -675,8 +713,10 @@ async def sample_delete_region(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 @@ -728,7 +768,7 @@ async def list_regions( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListRegionsAsyncPager: r"""Lists the regions in your Merchant Center account. @@ -772,8 +812,10 @@ async def sample_list_regions(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/regions_service/client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/regions_service/client.py index 82be07aff917..95d239f36e75 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/regions_service/client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/regions_service/client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import os import re from typing import ( @@ -48,6 +49,15 @@ 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 @@ -596,6 +606,10 @@ def __init__( # 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( @@ -661,6 +675,29 @@ def __init__( 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, @@ -668,7 +705,7 @@ def get_region( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> regions.Region: r"""Retrieves a region defined in your Merchant Center account. @@ -712,8 +749,10 @@ def sample_get_region(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -778,7 +817,7 @@ def create_region( region_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + 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. @@ -836,8 +875,10 @@ def sample_create_region(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -905,7 +946,7 @@ def update_region( 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, str]] = (), + 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. @@ -954,8 +995,10 @@ def sample_update_region(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -1022,7 +1065,7 @@ def delete_region( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: r"""Deletes a region definition from your Merchant Center account. Executing this method requires admin access. @@ -1063,8 +1106,10 @@ def sample_delete_region(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 @@ -1113,7 +1158,7 @@ def list_regions( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListRegionsPager: r"""Lists the regions in your Merchant Center account. @@ -1157,8 +1202,10 @@ def sample_list_regions(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/regions_service/pagers.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/regions_service/pagers.py index 3128bcdd68da..e9f44fc45b1c 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/regions_service/pagers.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/regions_service/pagers.py @@ -67,7 +67,7 @@ def __init__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiate the pager. @@ -81,8 +81,10 @@ def __init__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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) @@ -141,7 +143,7 @@ def __init__( *, retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiates the pager. @@ -155,8 +157,10 @@ def __init__( 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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) diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/grpc.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/grpc.py index 9f036a11198b..1b96cfdf085f 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/grpc.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/grpc.py @@ -13,6 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import json +import logging as std_logging +import pickle from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -21,12 +24,90 @@ 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.shopping.merchant_accounts_v1beta.types import regions 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 + +_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": 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. @@ -184,7 +265,12 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -257,7 +343,7 @@ def get_region(self) -> Callable[[regions.GetRegionRequest], regions.Region]: # 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.grpc_channel.unary_unary( + 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, @@ -282,7 +368,7 @@ def create_region(self) -> Callable[[regions.CreateRegionRequest], regions.Regio # 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.grpc_channel.unary_unary( + 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, @@ -307,7 +393,7 @@ def update_region(self) -> Callable[[regions.UpdateRegionRequest], regions.Regio # 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.grpc_channel.unary_unary( + 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, @@ -332,7 +418,7 @@ def delete_region(self) -> Callable[[regions.DeleteRegionRequest], empty_pb2.Emp # 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.grpc_channel.unary_unary( + 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, @@ -358,7 +444,7 @@ def list_regions( # 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.grpc_channel.unary_unary( + 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, @@ -366,7 +452,7 @@ def list_regions( return self._stubs["list_regions"] def close(self): - self.grpc_channel.close() + self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/grpc_asyncio.py index 630ee6332d7e..7818c26ac4d4 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/grpc_asyncio.py @@ -14,6 +14,9 @@ # limitations under the License. # import inspect +import json +import logging as std_logging +import pickle from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -23,14 +26,93 @@ 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 from grpc.experimental import aio # type: ignore +import proto # type: ignore from google.shopping.merchant_accounts_v1beta.types import regions 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 + +_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. @@ -231,10 +313,13 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -267,7 +352,7 @@ def get_region( # 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.grpc_channel.unary_unary( + 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, @@ -294,7 +379,7 @@ def create_region( # 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.grpc_channel.unary_unary( + 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, @@ -321,7 +406,7 @@ def update_region( # 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.grpc_channel.unary_unary( + 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, @@ -348,7 +433,7 @@ def delete_region( # 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.grpc_channel.unary_unary( + 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, @@ -374,7 +459,7 @@ def list_regions( # 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.grpc_channel.unary_unary( + 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, @@ -417,7 +502,7 @@ def _wrap_method(self, func, *args, **kwargs): return gapic_v1.method_async.wrap_method(func, *args, **kwargs) def close(self): - return self.grpc_channel.close() + return self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/rest.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/rest.py index a1928d09add4..c232076cad01 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/rest.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/rest.py @@ -13,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import dataclasses import json # type: ignore +import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings @@ -38,6 +38,14 @@ 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, @@ -104,8 +112,10 @@ def post_update_region(self, response): """ def pre_create_region( - self, request: regions.CreateRegionRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[regions.CreateRegionRequest, Sequence[Tuple[str, str]]]: + 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 @@ -123,8 +133,10 @@ def post_create_region(self, response: regions.Region) -> regions.Region: return response def pre_delete_region( - self, request: regions.DeleteRegionRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[regions.DeleteRegionRequest, Sequence[Tuple[str, str]]]: + 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 @@ -133,8 +145,10 @@ def pre_delete_region( return request, metadata def pre_get_region( - self, request: regions.GetRegionRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[regions.GetRegionRequest, Sequence[Tuple[str, str]]]: + 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 @@ -152,8 +166,10 @@ def post_get_region(self, response: regions.Region) -> regions.Region: return response def pre_list_regions( - self, request: regions.ListRegionsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[regions.ListRegionsRequest, Sequence[Tuple[str, str]]]: + 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 @@ -173,8 +189,10 @@ def post_list_regions( return response def pre_update_region( - self, request: regions.UpdateRegionRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[regions.UpdateRegionRequest, Sequence[Tuple[str, str]]]: + 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 @@ -317,7 +335,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> regions.Region: r"""Call the create region method over HTTP. @@ -327,8 +345,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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: @@ -346,6 +366,7 @@ def __call__( 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 @@ -360,6 +381,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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, @@ -381,7 +429,29 @@ def __call__( pb_resp = regions.Region.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_region(resp) + 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( @@ -418,7 +488,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ): r"""Call the delete region method over HTTP. @@ -428,13 +498,16 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 @@ -445,6 +518,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + 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, @@ -494,7 +594,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> regions.Region: r"""Call the get region method over HTTP. @@ -504,8 +604,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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: @@ -523,6 +625,7 @@ def __call__( http_options = ( _BaseRegionsServiceRestTransport._BaseGetRegion._get_http_options() ) + request, metadata = self._interceptor.pre_get_region(request, metadata) transcoded_request = ( _BaseRegionsServiceRestTransport._BaseGetRegion._get_transcoded_request( @@ -537,6 +640,33 @@ def __call__( ) ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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, @@ -557,7 +687,29 @@ def __call__( pb_resp = regions.Region.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_region(resp) + 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( @@ -594,7 +746,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> regions.ListRegionsResponse: r"""Call the list regions method over HTTP. @@ -604,8 +756,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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: @@ -615,6 +769,7 @@ def __call__( 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 @@ -625,6 +780,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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, @@ -645,7 +827,29 @@ def __call__( pb_resp = regions.ListRegionsResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_regions(resp) + 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( @@ -683,7 +887,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> regions.Region: r"""Call the update region method over HTTP. @@ -693,8 +897,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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: @@ -712,6 +918,7 @@ def __call__( 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 @@ -726,6 +933,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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, @@ -747,7 +981,29 @@ def __call__( pb_resp = regions.Region.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_region(resp) + 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 diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/async_client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/async_client.py index 6565278a30e3..1710d88baf73 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/async_client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/async_client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import re from typing import ( Callable, @@ -48,6 +49,15 @@ 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 @@ -269,6 +279,28 @@ def __init__( 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[ @@ -278,7 +310,7 @@ async def get_shipping_settings( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> shippingsettings.ShippingSettings: r"""Retrieve shipping setting information. @@ -321,8 +353,10 @@ async def sample_get_shipping_settings(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -384,7 +418,7 @@ async def insert_shipping_settings( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + 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 @@ -427,8 +461,10 @@ async def sample_insert_shipping_settings(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/client.py index 56db58577783..cbb279ef081c 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import os import re from typing import ( @@ -48,6 +49,15 @@ 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 DEFAULT_CLIENT_INFO, ShippingSettingsServiceTransport @@ -580,6 +590,10 @@ def __init__( # 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( @@ -646,6 +660,29 @@ def __init__( 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[ @@ -655,7 +692,7 @@ def get_shipping_settings( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> shippingsettings.ShippingSettings: r"""Retrieve shipping setting information. @@ -698,8 +735,10 @@ def sample_get_shipping_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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -758,7 +797,7 @@ def insert_shipping_settings( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + 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 @@ -801,8 +840,10 @@ def sample_insert_shipping_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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/grpc.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/grpc.py index 83842f03e326..03cb57db04c5 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/grpc.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/grpc.py @@ -13,6 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import json +import logging as std_logging +import pickle from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -20,12 +23,90 @@ 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 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 + +_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": 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. @@ -180,7 +261,12 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -256,7 +342,7 @@ def get_shipping_settings( # 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.grpc_channel.unary_unary( + 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, @@ -287,7 +373,7 @@ def insert_shipping_settings( # 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.grpc_channel.unary_unary( + 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, @@ -295,7 +381,7 @@ def insert_shipping_settings( return self._stubs["insert_shipping_settings"] def close(self): - self.grpc_channel.close() + self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/grpc_asyncio.py index 4afad31922bf..c250682ab226 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/grpc_asyncio.py @@ -14,6 +14,9 @@ # limitations under the License. # import inspect +import json +import logging as std_logging +import pickle from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -22,14 +25,93 @@ 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 from grpc.experimental import aio # type: ignore +import proto # type: ignore from google.shopping.merchant_accounts_v1beta.types import shippingsettings 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 + +_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. @@ -227,10 +309,13 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -265,7 +350,7 @@ def get_shipping_settings( # 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.grpc_channel.unary_unary( + 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, @@ -296,7 +381,7 @@ def insert_shipping_settings( # 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.grpc_channel.unary_unary( + 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, @@ -324,7 +409,7 @@ def _wrap_method(self, func, *args, **kwargs): return gapic_v1.method_async.wrap_method(func, *args, **kwargs) def close(self): - return self.grpc_channel.close() + return self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/rest.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/rest.py index 693d3bad2b85..da6b482e5420 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/rest.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/rest.py @@ -13,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import dataclasses import json # type: ignore +import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings @@ -37,6 +37,14 @@ 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, @@ -85,8 +93,11 @@ def post_insert_shipping_settings(self, response): def pre_get_shipping_settings( self, request: shippingsettings.GetShippingSettingsRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[shippingsettings.GetShippingSettingsRequest, Sequence[Tuple[str, str]]]: + 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 @@ -108,9 +119,10 @@ def post_get_shipping_settings( def pre_insert_shipping_settings( self, request: shippingsettings.InsertShippingSettingsRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - shippingsettings.InsertShippingSettingsRequest, Sequence[Tuple[str, str]] + shippingsettings.InsertShippingSettingsRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for insert_shipping_settings @@ -253,7 +265,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> shippingsettings.ShippingSettings: r"""Call the get shipping settings method over HTTP. @@ -263,8 +275,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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: @@ -276,6 +290,7 @@ def __call__( http_options = ( _BaseShippingSettingsServiceRestTransport._BaseGetShippingSettings._get_http_options() ) + request, metadata = self._interceptor.pre_get_shipping_settings( request, metadata ) @@ -288,6 +303,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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( @@ -310,7 +352,31 @@ def __call__( 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) + 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( @@ -349,7 +415,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> shippingsettings.ShippingSettings: r"""Call the insert shipping settings method over HTTP. @@ -360,8 +426,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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: @@ -373,6 +441,7 @@ def __call__( http_options = ( _BaseShippingSettingsServiceRestTransport._BaseInsertShippingSettings._get_http_options() ) + request, metadata = self._interceptor.pre_insert_shipping_settings( request, metadata ) @@ -389,6 +458,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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, @@ -410,7 +506,31 @@ def __call__( 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) + 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 diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/async_client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/async_client.py index 128ef18fec98..dd6234ab1da9 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/async_client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/async_client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import re from typing import ( Callable, @@ -56,6 +57,15 @@ 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.""" @@ -289,6 +299,28 @@ def __init__( 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[ @@ -301,7 +333,7 @@ async def get_terms_of_service_agreement_state( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> termsofserviceagreementstate.TermsOfServiceAgreementState: r"""Returns the state of a terms of service agreement. @@ -348,8 +380,10 @@ async def sample_get_terms_of_service_agreement_state(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -446,7 +480,7 @@ async def retrieve_for_application_terms_of_service_agreement_state( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> termsofserviceagreementstate.TermsOfServiceAgreementState: r"""Retrieves the state of the agreement for the application terms of service. @@ -493,8 +527,10 @@ async def sample_retrieve_for_application_terms_of_service_agreement_state(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/client.py index 774f9c6d3393..641416abee80 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import os import re from typing import ( @@ -48,6 +49,15 @@ 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, termsofservicekind, @@ -629,6 +639,10 @@ def __init__( # 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( @@ -702,6 +716,29 @@ def __init__( 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[ @@ -714,7 +751,7 @@ def get_terms_of_service_agreement_state( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> termsofserviceagreementstate.TermsOfServiceAgreementState: r"""Returns the state of a terms of service agreement. @@ -761,8 +798,10 @@ def sample_get_terms_of_service_agreement_state(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -858,7 +897,7 @@ def retrieve_for_application_terms_of_service_agreement_state( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> termsofserviceagreementstate.TermsOfServiceAgreementState: r"""Retrieves the state of the agreement for the application terms of service. @@ -905,8 +944,10 @@ def sample_retrieve_for_application_terms_of_service_agreement_state(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/grpc.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/grpc.py index f6e88b916fef..557f2da45991 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/grpc.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/grpc.py @@ -13,6 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import json +import logging as std_logging +import pickle from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -20,12 +23,90 @@ 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 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 + +_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": 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 @@ -181,7 +262,12 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -261,7 +347,7 @@ def get_terms_of_service_agreement_state( if "get_terms_of_service_agreement_state" not in self._stubs: self._stubs[ "get_terms_of_service_agreement_state" - ] = self.grpc_channel.unary_unary( + ] = self._logged_channel.unary_unary( "/google.shopping.merchant.accounts.v1beta.TermsOfServiceAgreementStateService/GetTermsOfServiceAgreementState", request_serializer=termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest.serialize, response_deserializer=termsofserviceagreementstate.TermsOfServiceAgreementState.deserialize, @@ -299,7 +385,7 @@ def retrieve_for_application_terms_of_service_agreement_state( ): self._stubs[ "retrieve_for_application_terms_of_service_agreement_state" - ] = self.grpc_channel.unary_unary( + ] = self._logged_channel.unary_unary( "/google.shopping.merchant.accounts.v1beta.TermsOfServiceAgreementStateService/RetrieveForApplicationTermsOfServiceAgreementState", request_serializer=termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest.serialize, response_deserializer=termsofserviceagreementstate.TermsOfServiceAgreementState.deserialize, @@ -307,7 +393,7 @@ def retrieve_for_application_terms_of_service_agreement_state( return self._stubs["retrieve_for_application_terms_of_service_agreement_state"] def close(self): - self.grpc_channel.close() + self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/grpc_asyncio.py index 7ed678041e1d..2e0fab7455fc 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/grpc_asyncio.py @@ -14,6 +14,9 @@ # limitations under the License. # import inspect +import json +import logging as std_logging +import pickle from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -22,14 +25,93 @@ 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 from grpc.experimental import aio # type: ignore +import proto # type: ignore from google.shopping.merchant_accounts_v1beta.types import termsofserviceagreementstate 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 + +_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 @@ -228,10 +310,13 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -269,7 +354,7 @@ def get_terms_of_service_agreement_state( if "get_terms_of_service_agreement_state" not in self._stubs: self._stubs[ "get_terms_of_service_agreement_state" - ] = self.grpc_channel.unary_unary( + ] = self._logged_channel.unary_unary( "/google.shopping.merchant.accounts.v1beta.TermsOfServiceAgreementStateService/GetTermsOfServiceAgreementState", request_serializer=termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest.serialize, response_deserializer=termsofserviceagreementstate.TermsOfServiceAgreementState.deserialize, @@ -307,7 +392,7 @@ def retrieve_for_application_terms_of_service_agreement_state( ): self._stubs[ "retrieve_for_application_terms_of_service_agreement_state" - ] = self.grpc_channel.unary_unary( + ] = self._logged_channel.unary_unary( "/google.shopping.merchant.accounts.v1beta.TermsOfServiceAgreementStateService/RetrieveForApplicationTermsOfServiceAgreementState", request_serializer=termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest.serialize, response_deserializer=termsofserviceagreementstate.TermsOfServiceAgreementState.deserialize, @@ -335,7 +420,7 @@ def _wrap_method(self, func, *args, **kwargs): return gapic_v1.method_async.wrap_method(func, *args, **kwargs) def close(self): - return self.grpc_channel.close() + return self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/rest.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/rest.py index c39b562df96c..d5b957f37f2d 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/rest.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/rest.py @@ -13,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import dataclasses import json # type: ignore +import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings @@ -37,6 +37,14 @@ 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, @@ -85,10 +93,10 @@ 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, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest, - Sequence[Tuple[str, str]], + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for get_terms_of_service_agreement_state @@ -111,10 +119,10 @@ def post_get_terms_of_service_agreement_state( def pre_retrieve_for_application_terms_of_service_agreement_state( self, request: termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest, - Sequence[Tuple[str, str]], + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for retrieve_for_application_terms_of_service_agreement_state @@ -264,7 +272,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> termsofserviceagreementstate.TermsOfServiceAgreementState: r"""Call the get terms of service agreement state method over HTTP. @@ -276,8 +284,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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: @@ -315,6 +325,7 @@ def __call__( http_options = ( _BaseTermsOfServiceAgreementStateServiceRestTransport._BaseGetTermsOfServiceAgreementState._get_http_options() ) + ( request, metadata, @@ -330,6 +341,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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, @@ -350,7 +388,31 @@ def __call__( 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) + 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( @@ -390,7 +452,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> termsofserviceagreementstate.TermsOfServiceAgreementState: r"""Call the retrieve for application terms of service agreement state method over HTTP. @@ -403,8 +465,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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: @@ -442,6 +506,7 @@ def __call__( http_options = ( _BaseTermsOfServiceAgreementStateServiceRestTransport._BaseRetrieveForApplicationTermsOfServiceAgreementState._get_http_options() ) + ( request, metadata, @@ -457,6 +522,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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, @@ -477,9 +569,33 @@ def __call__( 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 ) + 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 diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/async_client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/async_client.py index 601dd62bcbee..e0bc803e5d4d 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/async_client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/async_client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import re from typing import ( Callable, @@ -51,6 +52,15 @@ 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.""" @@ -268,6 +278,28 @@ def __init__( 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, @@ -275,7 +307,7 @@ async def get_terms_of_service( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> termsofservice.TermsOfService: r"""Retrieves the ``TermsOfService`` associated with the provided version. @@ -319,8 +351,10 @@ async def sample_get_terms_of_service(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -380,7 +414,7 @@ async def retrieve_latest_terms_of_service( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> termsofservice.TermsOfService: r"""Retrieves the latest version of the ``TermsOfService`` for a given ``kind`` and ``region_code``. @@ -419,8 +453,10 @@ async def sample_retrieve_latest_terms_of_service(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -461,7 +497,7 @@ async def accept_terms_of_service( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: r"""Accepts a ``TermsOfService``. Executing this method requires admin access. @@ -504,8 +540,10 @@ async def sample_accept_terms_of_service(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/client.py index 4d7e7c4c3ff1..fb2a75c1f566 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import os import re from typing import ( @@ -48,6 +49,15 @@ 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, termsofservicekind, @@ -594,6 +604,10 @@ def __init__( # 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( @@ -660,6 +674,29 @@ def __init__( 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, @@ -667,7 +704,7 @@ def get_terms_of_service( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> termsofservice.TermsOfService: r"""Retrieves the ``TermsOfService`` associated with the provided version. @@ -711,8 +748,10 @@ def sample_get_terms_of_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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -769,7 +808,7 @@ def retrieve_latest_terms_of_service( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> termsofservice.TermsOfService: r"""Retrieves the latest version of the ``TermsOfService`` for a given ``kind`` and ``region_code``. @@ -808,8 +847,10 @@ def sample_retrieve_latest_terms_of_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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -850,7 +891,7 @@ def accept_terms_of_service( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: r"""Accepts a ``TermsOfService``. Executing this method requires admin access. @@ -893,8 +934,10 @@ def sample_accept_terms_of_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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/grpc.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/grpc.py index 06e33647491d..5149dfcb2265 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/grpc.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/grpc.py @@ -13,6 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import json +import logging as std_logging +import pickle from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -21,12 +24,90 @@ 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.shopping.merchant_accounts_v1beta.types import termsofservice 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 + +_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": 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. @@ -180,7 +261,12 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -257,7 +343,7 @@ def get_terms_of_service( # 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.grpc_channel.unary_unary( + 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, @@ -290,7 +376,7 @@ def retrieve_latest_terms_of_service( if "retrieve_latest_terms_of_service" not in self._stubs: self._stubs[ "retrieve_latest_terms_of_service" - ] = self.grpc_channel.unary_unary( + ] = self._logged_channel.unary_unary( "/google.shopping.merchant.accounts.v1beta.TermsOfServiceService/RetrieveLatestTermsOfService", request_serializer=termsofservice.RetrieveLatestTermsOfServiceRequest.serialize, response_deserializer=termsofservice.TermsOfService.deserialize, @@ -317,7 +403,7 @@ def accept_terms_of_service( # 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.grpc_channel.unary_unary( + 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, @@ -325,7 +411,7 @@ def accept_terms_of_service( return self._stubs["accept_terms_of_service"] def close(self): - self.grpc_channel.close() + self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/grpc_asyncio.py index ac78365de479..ef269480e268 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/grpc_asyncio.py @@ -14,6 +14,9 @@ # limitations under the License. # import inspect +import json +import logging as std_logging +import pickle from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -23,14 +26,93 @@ 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 from grpc.experimental import aio # type: ignore +import proto # type: ignore from google.shopping.merchant_accounts_v1beta.types import termsofservice 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 + +_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. @@ -227,10 +309,13 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -266,7 +351,7 @@ def get_terms_of_service( # 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.grpc_channel.unary_unary( + 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, @@ -299,7 +384,7 @@ def retrieve_latest_terms_of_service( if "retrieve_latest_terms_of_service" not in self._stubs: self._stubs[ "retrieve_latest_terms_of_service" - ] = self.grpc_channel.unary_unary( + ] = self._logged_channel.unary_unary( "/google.shopping.merchant.accounts.v1beta.TermsOfServiceService/RetrieveLatestTermsOfService", request_serializer=termsofservice.RetrieveLatestTermsOfServiceRequest.serialize, response_deserializer=termsofservice.TermsOfService.deserialize, @@ -328,7 +413,7 @@ def accept_terms_of_service( # 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.grpc_channel.unary_unary( + 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, @@ -361,7 +446,7 @@ def _wrap_method(self, func, *args, **kwargs): return gapic_v1.method_async.wrap_method(func, *args, **kwargs) def close(self): - return self.grpc_channel.close() + return self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/rest.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/rest.py index ccafb072649b..152800891a4f 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/rest.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/rest.py @@ -13,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import dataclasses import json # type: ignore +import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings @@ -38,6 +38,14 @@ 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, @@ -90,8 +98,11 @@ def post_retrieve_latest_terms_of_service(self, response): def pre_accept_terms_of_service( self, request: termsofservice.AcceptTermsOfServiceRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[termsofservice.AcceptTermsOfServiceRequest, Sequence[Tuple[str, str]]]: + 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 @@ -102,8 +113,10 @@ def pre_accept_terms_of_service( def pre_get_terms_of_service( self, request: termsofservice.GetTermsOfServiceRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[termsofservice.GetTermsOfServiceRequest, Sequence[Tuple[str, str]]]: + 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 @@ -125,9 +138,10 @@ def post_get_terms_of_service( def pre_retrieve_latest_terms_of_service( self, request: termsofservice.RetrieveLatestTermsOfServiceRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - termsofservice.RetrieveLatestTermsOfServiceRequest, Sequence[Tuple[str, str]] + termsofservice.RetrieveLatestTermsOfServiceRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for retrieve_latest_terms_of_service @@ -269,7 +283,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ): r"""Call the accept terms of service method over HTTP. @@ -279,13 +293,16 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 ) @@ -298,6 +315,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + 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( @@ -350,7 +394,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> termsofservice.TermsOfService: r"""Call the get terms of service method over HTTP. @@ -360,8 +404,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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: @@ -371,6 +417,7 @@ def __call__( http_options = ( _BaseTermsOfServiceServiceRestTransport._BaseGetTermsOfService._get_http_options() ) + request, metadata = self._interceptor.pre_get_terms_of_service( request, metadata ) @@ -383,6 +430,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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( @@ -405,7 +479,29 @@ def __call__( 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) + 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( @@ -445,7 +541,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> termsofservice.TermsOfService: r"""Call the retrieve latest terms of service method over HTTP. @@ -457,8 +553,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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: @@ -468,6 +566,7 @@ def __call__( http_options = ( _BaseTermsOfServiceServiceRestTransport._BaseRetrieveLatestTermsOfService._get_http_options() ) + request, metadata = self._interceptor.pre_retrieve_latest_terms_of_service( request, metadata ) @@ -480,6 +579,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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, @@ -500,7 +626,29 @@ def __call__( 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) + 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 diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/user_service/async_client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/user_service/async_client.py index a984dec524c5..033623c2b0ce 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/user_service/async_client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/user_service/async_client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import re from typing import ( Callable, @@ -53,6 +54,15 @@ 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.""" @@ -256,6 +266,28 @@ def __init__( 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, @@ -263,7 +295,7 @@ async def get_user( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> user.User: r"""Retrieves a Merchant Center account user. @@ -310,8 +342,10 @@ async def sample_get_user(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -371,7 +405,7 @@ async def create_user( user: Optional[gsma_user.User] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> gsma_user.User: r"""Creates a Merchant Center account user. Executing this method requires admin access. @@ -421,8 +455,10 @@ async def sample_create_user(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -485,7 +521,7 @@ async def delete_user( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: r"""Deletes a Merchant Center account user. Executing this method requires admin access. @@ -530,8 +566,10 @@ async def sample_delete_user(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 @@ -584,7 +622,7 @@ async def update_user( 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, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> gsma_user.User: r"""Updates a Merchant Center account user. Executing this method requires admin access. @@ -636,8 +674,10 @@ async def sample_update_user(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -702,7 +742,7 @@ async def list_users( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListUsersAsyncPager: r"""Lists all users of a Merchant Center account. @@ -746,8 +786,10 @@ async def sample_list_users(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/user_service/client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/user_service/client.py index 3c005342b0a1..2a5d86474254 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/user_service/client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/user_service/client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import os import re from typing import ( @@ -48,6 +49,15 @@ 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 @@ -590,6 +600,10 @@ def __init__( # 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( @@ -652,6 +666,29 @@ def __init__( 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, @@ -659,7 +696,7 @@ def get_user( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> user.User: r"""Retrieves a Merchant Center account user. @@ -706,8 +743,10 @@ def sample_get_user(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -766,7 +805,7 @@ def create_user( user: Optional[gsma_user.User] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> gsma_user.User: r"""Creates a Merchant Center account user. Executing this method requires admin access. @@ -816,8 +855,10 @@ def sample_create_user(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -877,7 +918,7 @@ def delete_user( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: r"""Deletes a Merchant Center account user. Executing this method requires admin access. @@ -922,8 +963,10 @@ def sample_delete_user(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 @@ -973,7 +1016,7 @@ def update_user( 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, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> gsma_user.User: r"""Updates a Merchant Center account user. Executing this method requires admin access. @@ -1025,8 +1068,10 @@ def sample_update_user(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: @@ -1088,7 +1133,7 @@ def list_users( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListUsersPager: r"""Lists all users of a Merchant Center account. @@ -1132,8 +1177,10 @@ def sample_list_users(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of 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: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/user_service/pagers.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/user_service/pagers.py index 61701037173b..f6271e0a4c05 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/user_service/pagers.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/user_service/pagers.py @@ -67,7 +67,7 @@ def __init__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiate the pager. @@ -81,8 +81,10 @@ def __init__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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) @@ -141,7 +143,7 @@ def __init__( *, retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiates the pager. @@ -155,8 +157,10 @@ def __init__( 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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) diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/user_service/transports/grpc.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/user_service/transports/grpc.py index 521bc79dcb80..7379dcf1e361 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/user_service/transports/grpc.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/user_service/transports/grpc.py @@ -13,6 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import json +import logging as std_logging +import pickle from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -21,13 +24,91 @@ 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.shopping.merchant_accounts_v1beta.types import user from google.shopping.merchant_accounts_v1beta.types import user as gsma_user 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 + +_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": 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. @@ -181,7 +262,12 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -253,7 +339,7 @@ def get_user(self) -> Callable[[user.GetUserRequest], user.User]: # 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.grpc_channel.unary_unary( + 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, @@ -278,7 +364,7 @@ def create_user(self) -> Callable[[gsma_user.CreateUserRequest], gsma_user.User] # 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.grpc_channel.unary_unary( + 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, @@ -303,7 +389,7 @@ def delete_user(self) -> Callable[[user.DeleteUserRequest], empty_pb2.Empty]: # 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.grpc_channel.unary_unary( + 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, @@ -328,7 +414,7 @@ def update_user(self) -> Callable[[gsma_user.UpdateUserRequest], gsma_user.User] # 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.grpc_channel.unary_unary( + 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, @@ -352,7 +438,7 @@ def list_users(self) -> Callable[[user.ListUsersRequest], user.ListUsersResponse # 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.grpc_channel.unary_unary( + 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, @@ -360,7 +446,7 @@ def list_users(self) -> Callable[[user.ListUsersRequest], user.ListUsersResponse return self._stubs["list_users"] def close(self): - self.grpc_channel.close() + self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/user_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/user_service/transports/grpc_asyncio.py index a8bc96ed310b..6c21a8d7ac6d 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/user_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/user_service/transports/grpc_asyncio.py @@ -14,6 +14,9 @@ # limitations under the License. # import inspect +import json +import logging as std_logging +import pickle from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -23,8 +26,11 @@ 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 from grpc.experimental import aio # type: ignore +import proto # type: ignore from google.shopping.merchant_accounts_v1beta.types import user from google.shopping.merchant_accounts_v1beta.types import user as gsma_user @@ -32,6 +38,82 @@ 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 + +_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. @@ -228,10 +310,13 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -261,7 +346,7 @@ def get_user(self) -> Callable[[user.GetUserRequest], Awaitable[user.User]]: # 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.grpc_channel.unary_unary( + 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, @@ -288,7 +373,7 @@ def create_user( # 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.grpc_channel.unary_unary( + 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, @@ -315,7 +400,7 @@ def delete_user( # 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.grpc_channel.unary_unary( + 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, @@ -342,7 +427,7 @@ def update_user( # 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.grpc_channel.unary_unary( + 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, @@ -368,7 +453,7 @@ def list_users( # 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.grpc_channel.unary_unary( + 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, @@ -411,7 +496,7 @@ def _wrap_method(self, func, *args, **kwargs): return gapic_v1.method_async.wrap_method(func, *args, **kwargs) def close(self): - return self.grpc_channel.close() + return self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/user_service/transports/rest.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/user_service/transports/rest.py index ef09abb79ed8..4421b4cf14d2 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/user_service/transports/rest.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/user_service/transports/rest.py @@ -13,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import dataclasses import json # type: ignore +import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings @@ -39,6 +39,14 @@ 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, @@ -105,8 +113,10 @@ def post_update_user(self, response): """ def pre_create_user( - self, request: gsma_user.CreateUserRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[gsma_user.CreateUserRequest, Sequence[Tuple[str, str]]]: + 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 @@ -124,8 +134,10 @@ def post_create_user(self, response: gsma_user.User) -> gsma_user.User: return response def pre_delete_user( - self, request: user.DeleteUserRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[user.DeleteUserRequest, Sequence[Tuple[str, str]]]: + 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 @@ -134,8 +146,10 @@ def pre_delete_user( return request, metadata def pre_get_user( - self, request: user.GetUserRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[user.GetUserRequest, Sequence[Tuple[str, str]]]: + 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 @@ -153,8 +167,10 @@ def post_get_user(self, response: user.User) -> user.User: return response def pre_list_users( - self, request: user.ListUsersRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[user.ListUsersRequest, Sequence[Tuple[str, str]]]: + 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 @@ -174,8 +190,10 @@ def post_list_users( return response def pre_update_user( - self, request: gsma_user.UpdateUserRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[gsma_user.UpdateUserRequest, Sequence[Tuple[str, str]]]: + 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 @@ -314,7 +332,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> gsma_user.User: r"""Call the create user method over HTTP. @@ -324,8 +342,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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: @@ -337,6 +357,7 @@ def __call__( http_options = ( _BaseUserServiceRestTransport._BaseCreateUser._get_http_options() ) + request, metadata = self._interceptor.pre_create_user(request, metadata) transcoded_request = ( _BaseUserServiceRestTransport._BaseCreateUser._get_transcoded_request( @@ -355,6 +376,33 @@ def __call__( ) ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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, @@ -376,7 +424,29 @@ def __call__( 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) + 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( @@ -413,7 +483,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ): r"""Call the delete user method over HTTP. @@ -423,13 +493,16 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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( @@ -444,6 +517,33 @@ def __call__( ) ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + 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, @@ -491,7 +591,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> user.User: r"""Call the get user method over HTTP. @@ -501,8 +601,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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: @@ -514,6 +616,7 @@ def __call__( http_options = ( _BaseUserServiceRestTransport._BaseGetUser._get_http_options() ) + request, metadata = self._interceptor.pre_get_user(request, metadata) transcoded_request = ( _BaseUserServiceRestTransport._BaseGetUser._get_transcoded_request( @@ -528,6 +631,33 @@ def __call__( ) ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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, @@ -548,7 +678,29 @@ def __call__( pb_resp = user.User.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_user(resp) + 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): @@ -583,7 +735,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> user.ListUsersResponse: r"""Call the list users method over HTTP. @@ -593,8 +745,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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: @@ -604,6 +758,7 @@ def __call__( http_options = ( _BaseUserServiceRestTransport._BaseListUsers._get_http_options() ) + request, metadata = self._interceptor.pre_list_users(request, metadata) transcoded_request = ( _BaseUserServiceRestTransport._BaseListUsers._get_transcoded_request( @@ -618,6 +773,33 @@ def __call__( ) ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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, @@ -638,7 +820,29 @@ def __call__( pb_resp = user.ListUsersResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_users(resp) + 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( @@ -676,7 +880,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> gsma_user.User: r"""Call the update user method over HTTP. @@ -686,8 +890,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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: @@ -699,6 +905,7 @@ def __call__( http_options = ( _BaseUserServiceRestTransport._BaseUpdateUser._get_http_options() ) + request, metadata = self._interceptor.pre_update_user(request, metadata) transcoded_request = ( _BaseUserServiceRestTransport._BaseUpdateUser._get_transcoded_request( @@ -717,6 +924,33 @@ def __call__( ) ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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, @@ -738,7 +972,29 @@ def __call__( 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) + 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 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 1058eee916c7..c736f9d3c831 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.2.2" + "version": "0.1.0" }, "snippets": [ { @@ -47,7 +47,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.services.account_issue_service.pagers.ListAccountIssuesAsyncPager", @@ -127,7 +127,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.services.account_issue_service.pagers.ListAccountIssuesPager", @@ -208,7 +208,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.AccountTax", @@ -288,7 +288,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.AccountTax", @@ -369,7 +369,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.services.account_tax_service.pagers.ListAccountTaxAsyncPager", @@ -449,7 +449,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.services.account_tax_service.pagers.ListAccountTaxPager", @@ -534,7 +534,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.AccountTax", @@ -618,7 +618,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.AccountTax", @@ -695,7 +695,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.Account", @@ -771,7 +771,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.Account", @@ -852,7 +852,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "shortName": "delete_account" @@ -929,7 +929,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "shortName": "delete_account" @@ -1007,7 +1007,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.Account", @@ -1087,7 +1087,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.Account", @@ -1164,7 +1164,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.services.accounts_service.pagers.ListAccountsAsyncPager", @@ -1240,7 +1240,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.services.accounts_service.pagers.ListAccountsPager", @@ -1321,7 +1321,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.services.accounts_service.pagers.ListSubAccountsAsyncPager", @@ -1401,7 +1401,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.services.accounts_service.pagers.ListSubAccountsPager", @@ -1486,7 +1486,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.Account", @@ -1570,7 +1570,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.Account", @@ -1651,7 +1651,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.AutofeedSettings", @@ -1731,7 +1731,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.AutofeedSettings", @@ -1816,7 +1816,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.AutofeedSettings", @@ -1900,7 +1900,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.AutofeedSettings", @@ -1981,7 +1981,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.BusinessIdentity", @@ -2061,7 +2061,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.BusinessIdentity", @@ -2146,7 +2146,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.BusinessIdentity", @@ -2230,7 +2230,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.BusinessIdentity", @@ -2311,7 +2311,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.BusinessInfo", @@ -2391,7 +2391,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.BusinessInfo", @@ -2476,7 +2476,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.BusinessInfo", @@ -2560,7 +2560,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.BusinessInfo", @@ -2641,7 +2641,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.EmailPreferences", @@ -2721,7 +2721,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.EmailPreferences", @@ -2806,7 +2806,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.EmailPreferences", @@ -2890,7 +2890,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.EmailPreferences", @@ -2967,7 +2967,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.Homepage", @@ -3043,7 +3043,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.Homepage", @@ -3124,7 +3124,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.Homepage", @@ -3204,7 +3204,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.Homepage", @@ -3281,7 +3281,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.Homepage", @@ -3357,7 +3357,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.Homepage", @@ -3442,7 +3442,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.Homepage", @@ -3526,7 +3526,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.Homepage", @@ -3607,7 +3607,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy", @@ -3687,7 +3687,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy", @@ -3768,7 +3768,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.services.online_return_policy_service.pagers.ListOnlineReturnPoliciesAsyncPager", @@ -3848,7 +3848,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.services.online_return_policy_service.pagers.ListOnlineReturnPoliciesPager", @@ -3929,7 +3929,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.Program", @@ -4009,7 +4009,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.Program", @@ -4090,7 +4090,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.Program", @@ -4170,7 +4170,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.Program", @@ -4251,7 +4251,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.Program", @@ -4331,7 +4331,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.Program", @@ -4412,7 +4412,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.services.programs_service.pagers.ListProgramsAsyncPager", @@ -4492,7 +4492,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.services.programs_service.pagers.ListProgramsPager", @@ -4581,7 +4581,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.Region", @@ -4669,7 +4669,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.Region", @@ -4750,7 +4750,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "shortName": "delete_region" @@ -4827,7 +4827,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "shortName": "delete_region" @@ -4905,7 +4905,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.Region", @@ -4985,7 +4985,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.Region", @@ -5066,7 +5066,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.services.regions_service.pagers.ListRegionsAsyncPager", @@ -5146,7 +5146,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.services.regions_service.pagers.ListRegionsPager", @@ -5231,7 +5231,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.Region", @@ -5315,7 +5315,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.Region", @@ -5396,7 +5396,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.ShippingSettings", @@ -5476,7 +5476,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.ShippingSettings", @@ -5553,7 +5553,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.ShippingSettings", @@ -5629,7 +5629,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.ShippingSettings", @@ -5710,7 +5710,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.TermsOfServiceAgreementState", @@ -5790,7 +5790,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.TermsOfServiceAgreementState", @@ -5871,7 +5871,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.TermsOfServiceAgreementState", @@ -5951,7 +5951,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.TermsOfServiceAgreementState", @@ -6032,7 +6032,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "shortName": "accept_terms_of_service" @@ -6109,7 +6109,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "shortName": "accept_terms_of_service" @@ -6187,7 +6187,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.TermsOfService", @@ -6267,7 +6267,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.TermsOfService", @@ -6344,7 +6344,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.TermsOfService", @@ -6420,7 +6420,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.TermsOfService", @@ -6505,7 +6505,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.User", @@ -6589,7 +6589,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.User", @@ -6670,7 +6670,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "shortName": "delete_user" @@ -6747,7 +6747,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "shortName": "delete_user" @@ -6825,7 +6825,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.User", @@ -6905,7 +6905,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.User", @@ -6986,7 +6986,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.services.user_service.pagers.ListUsersAsyncPager", @@ -7066,7 +7066,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.services.user_service.pagers.ListUsersPager", @@ -7151,7 +7151,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.User", @@ -7235,7 +7235,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_accounts_v1beta.types.User", diff --git a/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_account_issue_service.py b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_account_issue_service.py index ce8b8b27c933..f55fae63fdf7 100644 --- a/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_account_issue_service.py +++ b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_account_issue_service.py @@ -1784,6 +1784,7 @@ def test_list_account_issues_rest_required_fields( response_value._content = json_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) @@ -1839,6 +1840,7 @@ def test_list_account_issues_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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) @@ -2130,6 +2132,7 @@ def test_list_account_issues_rest_bad_request( 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) @@ -2165,6 +2168,7 @@ def test_list_account_issues_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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. @@ -2205,6 +2209,7 @@ 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() ) diff --git a/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_account_tax_service.py b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_account_tax_service.py index 6e5d6b24a423..e219d7f3360f 100644 --- a/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_account_tax_service.py +++ b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_account_tax_service.py @@ -2407,6 +2407,7 @@ def test_get_account_tax_rest_required_fields( response_value._content = json_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) @@ -2452,6 +2453,7 @@ def test_get_account_tax_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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) @@ -2592,6 +2594,7 @@ def test_list_account_tax_rest_required_fields( response_value._content = json_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) @@ -2645,6 +2648,7 @@ def test_list_account_tax_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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) @@ -2841,6 +2845,7 @@ def test_update_account_tax_rest_required_fields( response_value._content = json_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) @@ -2889,6 +2894,7 @@ def test_update_account_tax_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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) @@ -3217,6 +3223,7 @@ def test_get_account_tax_rest_bad_request( 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) @@ -3253,6 +3260,7 @@ def test_get_account_tax_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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. @@ -3294,6 +3302,7 @@ def test_get_account_tax_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 = account_tax.AccountTax.to_json(account_tax.AccountTax()) req.return_value.content = return_value @@ -3338,6 +3347,7 @@ def test_list_account_tax_rest_bad_request( 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) @@ -3373,6 +3383,7 @@ def test_list_account_tax_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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. @@ -3413,6 +3424,7 @@ def test_list_account_tax_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 = account_tax.ListAccountTaxResponse.to_json( account_tax.ListAccountTaxResponse() ) @@ -3459,6 +3471,7 @@ def test_update_account_tax_rest_bad_request( 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) @@ -3580,6 +3593,7 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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. @@ -3621,6 +3635,7 @@ def test_update_account_tax_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_account_tax.AccountTax.to_json( gsma_account_tax.AccountTax() ) diff --git a/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_accounts_service.py b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_accounts_service.py index 951b0f3990c6..672309d4d693 100644 --- a/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_accounts_service.py +++ b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_accounts_service.py @@ -3310,6 +3310,7 @@ def test_get_account_rest_required_fields(request_type=accounts.GetAccountReques response_value._content = json_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) @@ -3355,6 +3356,7 @@ def test_get_account_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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) @@ -3485,6 +3487,7 @@ def test_create_and_configure_account_rest_required_fields( response_value._content = json_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) @@ -3611,6 +3614,7 @@ def test_delete_account_rest_required_fields( response_value._content = json_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) @@ -3654,6 +3658,7 @@ def test_delete_account_rest_flattened(): 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) @@ -3781,6 +3786,7 @@ def test_update_account_rest_required_fields( response_value._content = json_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) @@ -3835,6 +3841,7 @@ def test_update_account_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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) @@ -4072,6 +4079,7 @@ def test_list_sub_accounts_rest_required_fields( response_value._content = json_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) @@ -4125,6 +4133,7 @@ def test_list_sub_accounts_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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) @@ -4668,6 +4677,7 @@ def test_get_account_rest_bad_request(request_type=accounts.GetAccountRequest): 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) @@ -4708,6 +4718,7 @@ def test_get_account_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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. @@ -4751,6 +4762,7 @@ def test_get_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 = accounts.Account.to_json(accounts.Account()) req.return_value.content = return_value @@ -4795,6 +4807,7 @@ def test_create_and_configure_account_rest_bad_request( 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) @@ -4835,6 +4848,7 @@ def test_create_and_configure_account_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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. @@ -4880,6 +4894,7 @@ def test_create_and_configure_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 = accounts.Account.to_json(accounts.Account()) req.return_value.content = return_value @@ -4922,6 +4937,7 @@ def test_delete_account_rest_bad_request(request_type=accounts.DeleteAccountRequ 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) @@ -4952,6 +4968,7 @@ def test_delete_account_rest_call_success(request_type): 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. @@ -4986,6 +5003,7 @@ def test_delete_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"} request = accounts.DeleteAccountRequest() metadata = [ @@ -5024,6 +5042,7 @@ def test_update_account_rest_bad_request(request_type=accounts.UpdateAccountRequ 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) @@ -5140,6 +5159,7 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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. @@ -5183,6 +5203,7 @@ def test_update_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 = accounts.Account.to_json(accounts.Account()) req.return_value.content = return_value @@ -5225,6 +5246,7 @@ def test_list_accounts_rest_bad_request(request_type=accounts.ListAccountsReques 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) @@ -5260,6 +5282,7 @@ def test_list_accounts_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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. @@ -5298,6 +5321,7 @@ 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() ) @@ -5344,6 +5368,7 @@ def test_list_sub_accounts_rest_bad_request( 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) @@ -5379,6 +5404,7 @@ def test_list_sub_accounts_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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. @@ -5419,6 +5445,7 @@ 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() ) diff --git a/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_autofeed_settings_service.py b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_autofeed_settings_service.py index 32f10460d82a..27f14e47def8 100644 --- a/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_autofeed_settings_service.py +++ b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_autofeed_settings_service.py @@ -1939,6 +1939,7 @@ def test_get_autofeed_settings_rest_required_fields( response_value._content = json_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) @@ -1984,6 +1985,7 @@ def test_get_autofeed_settings_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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) @@ -2118,6 +2120,7 @@ def test_update_autofeed_settings_rest_required_fields( response_value._content = json_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) @@ -2174,6 +2177,7 @@ def test_update_autofeed_settings_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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) @@ -2460,6 +2464,7 @@ def test_get_autofeed_settings_rest_bad_request( 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) @@ -2497,6 +2502,7 @@ def test_get_autofeed_settings_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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. @@ -2539,6 +2545,7 @@ 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() ) @@ -2585,6 +2592,7 @@ def test_update_autofeed_settings_rest_bad_request( 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) @@ -2696,6 +2704,7 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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. @@ -2740,6 +2749,7 @@ 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() ) diff --git a/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_business_identity_service.py b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_business_identity_service.py index 34652d14ca8b..fda9d2bbbf68 100644 --- a/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_business_identity_service.py +++ b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_business_identity_service.py @@ -1943,6 +1943,7 @@ def test_get_business_identity_rest_required_fields( response_value._content = json_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) @@ -1988,6 +1989,7 @@ def test_get_business_identity_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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) @@ -2122,6 +2124,7 @@ def test_update_business_identity_rest_required_fields( response_value._content = json_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) @@ -2178,6 +2181,7 @@ def test_update_business_identity_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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) @@ -2462,6 +2466,7 @@ def test_get_business_identity_rest_bad_request( 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) @@ -2498,6 +2503,7 @@ def test_get_business_identity_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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. @@ -2542,6 +2548,7 @@ 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() ) @@ -2588,6 +2595,7 @@ def test_update_business_identity_rest_bad_request( 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) @@ -2702,6 +2710,7 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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. @@ -2748,6 +2757,7 @@ 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() ) diff --git a/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_business_info_service.py b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_business_info_service.py index fe9a65356193..55f233b43794 100644 --- a/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_business_info_service.py +++ b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_business_info_service.py @@ -1956,6 +1956,7 @@ def test_get_business_info_rest_required_fields( response_value._content = json_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) @@ -2001,6 +2002,7 @@ def test_get_business_info_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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) @@ -2134,6 +2136,7 @@ def test_update_business_info_rest_required_fields( response_value._content = json_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) @@ -2188,6 +2191,7 @@ def test_update_business_info_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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) @@ -2474,6 +2478,7 @@ def test_get_business_info_rest_bad_request( 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) @@ -2511,6 +2516,7 @@ def test_get_business_info_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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. @@ -2559,6 +2565,7 @@ def test_get_business_info_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 = businessinfo.BusinessInfo.to_json(businessinfo.BusinessInfo()) req.return_value.content = return_value @@ -2603,6 +2610,7 @@ def test_update_business_info_rest_bad_request( 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) @@ -2734,6 +2742,7 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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. @@ -2782,6 +2791,7 @@ def test_update_business_info_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 = businessinfo.BusinessInfo.to_json(businessinfo.BusinessInfo()) req.return_value.content = return_value diff --git a/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_email_preferences_service.py b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_email_preferences_service.py index 78d13efce5b5..aa20e576c90a 100644 --- a/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_email_preferences_service.py +++ b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_email_preferences_service.py @@ -1939,6 +1939,7 @@ def test_get_email_preferences_rest_required_fields( response_value._content = json_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) @@ -1984,6 +1985,7 @@ def test_get_email_preferences_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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) @@ -2118,6 +2120,7 @@ def test_update_email_preferences_rest_required_fields( response_value._content = json_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) @@ -2176,6 +2179,7 @@ def test_update_email_preferences_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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) @@ -2460,6 +2464,7 @@ def test_get_email_preferences_rest_bad_request( 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) @@ -2496,6 +2501,7 @@ def test_get_email_preferences_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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. @@ -2539,6 +2545,7 @@ 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() ) @@ -2587,6 +2594,7 @@ def test_update_email_preferences_rest_bad_request( 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) @@ -2698,6 +2706,7 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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. @@ -2743,6 +2752,7 @@ 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() ) diff --git a/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_homepage_service.py b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_homepage_service.py index 35711df444ea..3c1c890a3c77 100644 --- a/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_homepage_service.py +++ b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_homepage_service.py @@ -2345,6 +2345,7 @@ def test_get_homepage_rest_required_fields(request_type=homepage.GetHomepageRequ response_value._content = json_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) @@ -2390,6 +2391,7 @@ def test_get_homepage_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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) @@ -2518,6 +2520,7 @@ def test_update_homepage_rest_required_fields( response_value._content = json_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) @@ -2572,6 +2575,7 @@ def test_update_homepage_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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) @@ -2705,6 +2709,7 @@ def test_claim_homepage_rest_required_fields( response_value._content = json_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) @@ -2827,6 +2832,7 @@ def test_unclaim_homepage_rest_required_fields( response_value._content = json_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) @@ -3190,6 +3196,7 @@ def test_get_homepage_rest_bad_request(request_type=homepage.GetHomepageRequest) 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) @@ -3227,6 +3234,7 @@ def test_get_homepage_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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. @@ -3267,6 +3275,7 @@ def test_get_homepage_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 = homepage.Homepage.to_json(homepage.Homepage()) req.return_value.content = return_value @@ -3311,6 +3320,7 @@ def test_update_homepage_rest_bad_request( 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) @@ -3420,6 +3430,7 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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. @@ -3462,6 +3473,7 @@ def test_update_homepage_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_homepage.Homepage.to_json(gsma_homepage.Homepage()) req.return_value.content = return_value @@ -3504,6 +3516,7 @@ def test_claim_homepage_rest_bad_request(request_type=homepage.ClaimHomepageRequ 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) @@ -3541,6 +3554,7 @@ def test_claim_homepage_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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. @@ -3581,6 +3595,7 @@ def test_claim_homepage_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 = homepage.Homepage.to_json(homepage.Homepage()) req.return_value.content = return_value @@ -3625,6 +3640,7 @@ def test_unclaim_homepage_rest_bad_request( 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) @@ -3662,6 +3678,7 @@ def test_unclaim_homepage_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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. @@ -3704,6 +3721,7 @@ def test_unclaim_homepage_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 = homepage.Homepage.to_json(homepage.Homepage()) req.return_value.content = return_value diff --git a/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_online_return_policy_service.py b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_online_return_policy_service.py index 82c9f209acbf..2f65f8b7cb60 100644 --- a/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_online_return_policy_service.py +++ b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_online_return_policy_service.py @@ -2189,6 +2189,7 @@ def test_get_online_return_policy_rest_required_fields( response_value._content = json_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) @@ -2234,6 +2235,7 @@ def test_get_online_return_policy_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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) @@ -2379,6 +2381,7 @@ def test_list_online_return_policies_rest_required_fields( response_value._content = json_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) @@ -2434,6 +2437,7 @@ def test_list_online_return_policies_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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) @@ -2794,6 +2798,7 @@ def test_get_online_return_policy_rest_bad_request( 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) @@ -2840,6 +2845,7 @@ def test_get_online_return_policy_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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. @@ -2895,6 +2901,7 @@ 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() ) @@ -2941,6 +2948,7 @@ def test_list_online_return_policies_rest_bad_request( 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) @@ -2978,6 +2986,7 @@ def test_list_online_return_policies_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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. @@ -3020,6 +3029,7 @@ 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() ) diff --git a/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_programs_service.py b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_programs_service.py index 189a56eaaf44..efa73d73a38f 100644 --- a/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_programs_service.py +++ b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_programs_service.py @@ -2696,6 +2696,7 @@ def test_get_program_rest_required_fields(request_type=programs.GetProgramReques response_value._content = json_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) @@ -2741,6 +2742,7 @@ def test_get_program_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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) @@ -2876,6 +2878,7 @@ def test_list_programs_rest_required_fields(request_type=programs.ListProgramsRe response_value._content = json_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) @@ -2929,6 +2932,7 @@ def test_list_programs_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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) @@ -3121,6 +3125,7 @@ def test_enable_program_rest_required_fields( response_value._content = json_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) @@ -3166,6 +3171,7 @@ def test_enable_program_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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) @@ -3298,6 +3304,7 @@ def test_disable_program_rest_required_fields( response_value._content = json_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) @@ -3343,6 +3350,7 @@ def test_disable_program_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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) @@ -3719,6 +3727,7 @@ def test_get_program_rest_bad_request(request_type=programs.GetProgramRequest): 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) @@ -3757,6 +3766,7 @@ def test_get_program_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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. @@ -3798,6 +3808,7 @@ def test_get_program_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.Program.to_json(programs.Program()) req.return_value.content = return_value @@ -3840,6 +3851,7 @@ def test_list_programs_rest_bad_request(request_type=programs.ListProgramsReques 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) @@ -3875,6 +3887,7 @@ def test_list_programs_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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. @@ -3913,6 +3926,7 @@ 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() ) @@ -3957,6 +3971,7 @@ def test_enable_program_rest_bad_request(request_type=programs.EnableProgramRequ 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) @@ -3995,6 +4010,7 @@ def test_enable_program_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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. @@ -4036,6 +4052,7 @@ def test_enable_program_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.Program.to_json(programs.Program()) req.return_value.content = return_value @@ -4078,6 +4095,7 @@ def test_disable_program_rest_bad_request(request_type=programs.DisableProgramRe 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) @@ -4116,6 +4134,7 @@ def test_disable_program_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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. @@ -4157,6 +4176,7 @@ def test_disable_program_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.Program.to_json(programs.Program()) req.return_value.content = return_value diff --git a/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_regions_service.py b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_regions_service.py index 3680f3e0ea32..9a2f58394544 100644 --- a/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_regions_service.py +++ b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_regions_service.py @@ -2987,6 +2987,7 @@ def test_get_region_rest_required_fields(request_type=regions.GetRegionRequest): response_value._content = json_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) @@ -3032,6 +3033,7 @@ def test_get_region_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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) @@ -3170,6 +3172,7 @@ def test_create_region_rest_required_fields(request_type=regions.CreateRegionReq response_value._content = json_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) @@ -3232,6 +3235,7 @@ def test_create_region_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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) @@ -3360,6 +3364,7 @@ def test_update_region_rest_required_fields(request_type=regions.UpdateRegionReq response_value._content = json_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) @@ -3406,6 +3411,7 @@ def test_update_region_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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) @@ -3533,6 +3539,7 @@ def test_delete_region_rest_required_fields(request_type=regions.DeleteRegionReq response_value._content = json_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) @@ -3576,6 +3583,7 @@ def test_delete_region_rest_flattened(): 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) @@ -3711,6 +3719,7 @@ def test_list_regions_rest_required_fields(request_type=regions.ListRegionsReque response_value._content = json_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) @@ -3764,6 +3773,7 @@ def test_list_regions_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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) @@ -4238,6 +4248,7 @@ def test_get_region_rest_bad_request(request_type=regions.GetRegionRequest): 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) @@ -4274,6 +4285,7 @@ def test_get_region_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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. @@ -4313,6 +4325,7 @@ def test_get_region_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.Region.to_json(regions.Region()) req.return_value.content = return_value @@ -4355,6 +4368,7 @@ def test_create_region_rest_bad_request(request_type=regions.CreateRegionRequest 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) @@ -4469,6 +4483,7 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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. @@ -4508,6 +4523,7 @@ def test_create_region_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.Region.to_json(regions.Region()) req.return_value.content = return_value @@ -4550,6 +4566,7 @@ def test_update_region_rest_bad_request(request_type=regions.UpdateRegionRequest 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) @@ -4664,6 +4681,7 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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. @@ -4703,6 +4721,7 @@ def test_update_region_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.Region.to_json(regions.Region()) req.return_value.content = return_value @@ -4745,6 +4764,7 @@ def test_delete_region_rest_bad_request(request_type=regions.DeleteRegionRequest 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) @@ -4775,6 +4795,7 @@ def test_delete_region_rest_call_success(request_type): 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. @@ -4809,6 +4830,7 @@ def test_delete_region_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"} request = regions.DeleteRegionRequest() metadata = [ @@ -4847,6 +4869,7 @@ def test_list_regions_rest_bad_request(request_type=regions.ListRegionsRequest): 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) @@ -4882,6 +4905,7 @@ def test_list_regions_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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. @@ -4920,6 +4944,7 @@ 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() ) diff --git a/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_shipping_settings_service.py b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_shipping_settings_service.py index 216144bcb0eb..c1e7127471a3 100644 --- a/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_shipping_settings_service.py +++ b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_shipping_settings_service.py @@ -1839,6 +1839,7 @@ def test_get_shipping_settings_rest_required_fields( response_value._content = json_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) @@ -1884,6 +1885,7 @@ def test_get_shipping_settings_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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) @@ -2021,6 +2023,7 @@ def test_insert_shipping_settings_rest_required_fields( response_value._content = json_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) @@ -2300,6 +2303,7 @@ def test_get_shipping_settings_rest_bad_request( 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) @@ -2336,6 +2340,7 @@ def test_get_shipping_settings_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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. @@ -2377,6 +2382,7 @@ 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() ) @@ -2423,6 +2429,7 @@ def test_insert_shipping_settings_rest_bad_request( 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) @@ -2676,6 +2683,7 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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. @@ -2719,6 +2727,7 @@ 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() ) diff --git a/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_terms_of_service_agreement_state_service.py b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_terms_of_service_agreement_state_service.py index 883eb63e8267..e4d378bac349 100644 --- a/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_terms_of_service_agreement_state_service.py +++ b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_terms_of_service_agreement_state_service.py @@ -2043,6 +2043,7 @@ def test_get_terms_of_service_agreement_state_rest_required_fields( response_value._content = json_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) @@ -2094,6 +2095,7 @@ def test_get_terms_of_service_agreement_state_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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) @@ -2238,6 +2240,7 @@ def test_retrieve_for_application_terms_of_service_agreement_state_rest_required response_value._content = json_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 @@ -2289,6 +2292,7 @@ def test_retrieve_for_application_terms_of_service_agreement_state_rest_flattene json_return_value = json_format.MessageToJson(return_value) response_value._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) @@ -2592,6 +2596,7 @@ def test_get_terms_of_service_agreement_state_rest_bad_request( 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) @@ -2631,6 +2636,7 @@ def test_get_terms_of_service_agreement_state_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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. @@ -2682,6 +2688,7 @@ 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() @@ -2730,6 +2737,7 @@ def test_retrieve_for_application_terms_of_service_agreement_state_rest_bad_requ 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) @@ -2771,6 +2779,7 @@ def test_retrieve_for_application_terms_of_service_agreement_state_rest_call_suc json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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 ) @@ -2824,6 +2833,7 @@ 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() diff --git a/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_terms_of_service_service.py b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_terms_of_service_service.py index 231ce2fb4c85..4ef61688bdb6 100644 --- a/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_terms_of_service_service.py +++ b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_terms_of_service_service.py @@ -2133,6 +2133,7 @@ def test_get_terms_of_service_rest_required_fields( response_value._content = json_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) @@ -2178,6 +2179,7 @@ def test_get_terms_of_service_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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) @@ -2323,6 +2325,7 @@ def test_retrieve_latest_terms_of_service_rest_required_fields( response_value._content = json_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) @@ -2486,6 +2489,7 @@ def test_accept_terms_of_service_rest_required_fields( response_value._content = json_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) @@ -2553,6 +2557,7 @@ def test_accept_terms_of_service_rest_flattened(): 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) @@ -2890,6 +2895,7 @@ def test_get_terms_of_service_rest_bad_request( 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) @@ -2929,6 +2935,7 @@ def test_get_terms_of_service_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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. @@ -2973,6 +2980,7 @@ 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() ) @@ -3019,6 +3027,7 @@ def test_retrieve_latest_terms_of_service_rest_bad_request( 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) @@ -3058,6 +3067,7 @@ def test_retrieve_latest_terms_of_service_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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. @@ -3104,6 +3114,7 @@ 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() ) @@ -3150,6 +3161,7 @@ def test_accept_terms_of_service_rest_bad_request( 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) @@ -3180,6 +3192,7 @@ def test_accept_terms_of_service_rest_call_success(request_type): 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. @@ -3216,6 +3229,7 @@ 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"} request = termsofservice.AcceptTermsOfServiceRequest() metadata = [ diff --git a/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_user_service.py b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_user_service.py index 717391fcc580..79b7be920ccc 100644 --- a/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_user_service.py +++ b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1beta/test_user_service.py @@ -2951,6 +2951,7 @@ def test_get_user_rest_required_fields(request_type=user.GetUserRequest): response_value._content = json_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) @@ -2996,6 +2997,7 @@ def test_get_user_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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) @@ -3134,6 +3136,7 @@ def test_create_user_rest_required_fields(request_type=gsma_user.CreateUserReque response_value._content = json_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) @@ -3195,6 +3198,7 @@ def test_create_user_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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) @@ -3321,6 +3325,7 @@ def test_delete_user_rest_required_fields(request_type=user.DeleteUserRequest): response_value._content = json_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) @@ -3364,6 +3369,7 @@ def test_delete_user_rest_flattened(): 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) @@ -3490,6 +3496,7 @@ def test_update_user_rest_required_fields(request_type=gsma_user.UpdateUserReque response_value._content = json_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) @@ -3544,6 +3551,7 @@ def test_update_user_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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) @@ -3681,6 +3689,7 @@ def test_list_users_rest_required_fields(request_type=user.ListUsersRequest): response_value._content = json_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) @@ -3734,6 +3743,7 @@ def test_list_users_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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) @@ -4211,6 +4221,7 @@ def test_get_user_rest_bad_request(request_type=user.GetUserRequest): 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) @@ -4248,6 +4259,7 @@ def test_get_user_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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. @@ -4288,6 +4300,7 @@ def test_get_user_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 = user.User.to_json(user.User()) req.return_value.content = return_value @@ -4330,6 +4343,7 @@ def test_create_user_rest_bad_request(request_type=gsma_user.CreateUserRequest): 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) @@ -4435,6 +4449,7 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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. @@ -4475,6 +4490,7 @@ def test_create_user_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_user.User.to_json(gsma_user.User()) req.return_value.content = return_value @@ -4517,6 +4533,7 @@ def test_delete_user_rest_bad_request(request_type=user.DeleteUserRequest): 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) @@ -4547,6 +4564,7 @@ def test_delete_user_rest_call_success(request_type): 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. @@ -4581,6 +4599,7 @@ def test_delete_user_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"} request = user.DeleteUserRequest() metadata = [ @@ -4619,6 +4638,7 @@ def test_update_user_rest_bad_request(request_type=gsma_user.UpdateUserRequest): 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) @@ -4728,6 +4748,7 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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. @@ -4768,6 +4789,7 @@ def test_update_user_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_user.User.to_json(gsma_user.User()) req.return_value.content = return_value @@ -4810,6 +4832,7 @@ def test_list_users_rest_bad_request(request_type=user.ListUsersRequest): 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) @@ -4845,6 +4868,7 @@ def test_list_users_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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. @@ -4883,6 +4907,7 @@ def test_list_users_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 = user.ListUsersResponse.to_json(user.ListUsersResponse()) req.return_value.content = return_value diff --git a/packages/google-shopping-merchant-conversions/google/shopping/merchant_conversions/gapic_version.py b/packages/google-shopping-merchant-conversions/google/shopping/merchant_conversions/gapic_version.py index e9c4bb5650f3..558c8aab67c5 100644 --- a/packages/google-shopping-merchant-conversions/google/shopping/merchant_conversions/gapic_version.py +++ b/packages/google-shopping-merchant-conversions/google/shopping/merchant_conversions/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.5" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-shopping-merchant-conversions/google/shopping/merchant_conversions_v1beta/gapic_version.py b/packages/google-shopping-merchant-conversions/google/shopping/merchant_conversions_v1beta/gapic_version.py index e9c4bb5650f3..558c8aab67c5 100644 --- a/packages/google-shopping-merchant-conversions/google/shopping/merchant_conversions_v1beta/gapic_version.py +++ b/packages/google-shopping-merchant-conversions/google/shopping/merchant_conversions_v1beta/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.5" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-shopping-merchant-conversions/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/async_client.py b/packages/google-shopping-merchant-conversions/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/async_client.py index d3c1bcfc9094..4029d24bcafb 100644 --- a/packages/google-shopping-merchant-conversions/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/async_client.py +++ b/packages/google-shopping-merchant-conversions/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/async_client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import re from typing import ( Callable, @@ -54,6 +55,15 @@ from .transports.base import DEFAULT_CLIENT_INFO, ConversionSourcesServiceTransport from .transports.grpc_asyncio import ConversionSourcesServiceGrpcAsyncIOTransport +try: + from google.api_core import client_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 ConversionSourcesServiceAsyncClient: """Service for managing conversion sources for a merchant @@ -275,6 +285,28 @@ def __init__( client_info=client_info, ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.shopping.merchant.conversions_v1beta.ConversionSourcesServiceAsyncClient`.", + extra={ + "serviceName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", + "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.conversions.v1beta.ConversionSourcesService", + "credentialsType": None, + }, + ) + async def create_conversion_source( self, request: Optional[ @@ -285,7 +317,7 @@ async def create_conversion_source( conversion_source: Optional[conversionsources.ConversionSource] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> conversionsources.ConversionSource: r"""Creates a new conversion source. @@ -343,8 +375,10 @@ async def sample_create_conversion_source(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_conversions_v1beta.types.ConversionSource: @@ -412,7 +446,7 @@ async def update_conversion_source( 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, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> conversionsources.ConversionSource: r"""Updates information of an existing conversion source. Available only for Merchant Center Destination @@ -469,8 +503,10 @@ async def sample_update_conversion_source(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_conversions_v1beta.types.ConversionSource: @@ -539,7 +575,7 @@ async def delete_conversion_source( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: r"""Archives an existing conversion source. If the conversion source is a Merchant Center Destination, it @@ -585,8 +621,10 @@ async def sample_delete_conversion_source(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 @@ -639,7 +677,7 @@ async def undelete_conversion_source( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> conversionsources.ConversionSource: r"""Re-enables an archived conversion source. Only Available for Merchant Center Destination conversion @@ -678,8 +716,10 @@ async def sample_undelete_conversion_source(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_conversions_v1beta.types.ConversionSource: @@ -730,7 +770,7 @@ async def get_conversion_source( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> conversionsources.ConversionSource: r"""Fetches a conversion source. @@ -775,8 +815,10 @@ async def sample_get_conversion_source(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_conversions_v1beta.types.ConversionSource: @@ -841,7 +883,7 @@ async def list_conversion_sources( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListConversionSourcesAsyncPager: r"""Retrieves the list of conversion sources the caller has access to. @@ -888,8 +930,10 @@ async def sample_list_conversion_sources(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_conversions_v1beta.services.conversion_sources_service.pagers.ListConversionSourcesAsyncPager: diff --git a/packages/google-shopping-merchant-conversions/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/client.py b/packages/google-shopping-merchant-conversions/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/client.py index b2bdc63a6116..980bba28a6dc 100644 --- a/packages/google-shopping-merchant-conversions/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/client.py +++ b/packages/google-shopping-merchant-conversions/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import os import re from typing import ( @@ -48,6 +49,15 @@ 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 timestamp_pb2 # type: ignore @@ -591,6 +601,10 @@ def __init__( # 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( @@ -657,6 +671,29 @@ def __init__( 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.conversions_v1beta.ConversionSourcesServiceClient`.", + extra={ + "serviceName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", + "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.conversions.v1beta.ConversionSourcesService", + "credentialsType": None, + }, + ) + def create_conversion_source( self, request: Optional[ @@ -667,7 +704,7 @@ def create_conversion_source( conversion_source: Optional[conversionsources.ConversionSource] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> conversionsources.ConversionSource: r"""Creates a new conversion source. @@ -725,8 +762,10 @@ def sample_create_conversion_source(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_conversions_v1beta.types.ConversionSource: @@ -791,7 +830,7 @@ def update_conversion_source( 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, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> conversionsources.ConversionSource: r"""Updates information of an existing conversion source. Available only for Merchant Center Destination @@ -848,8 +887,10 @@ def sample_update_conversion_source(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_conversions_v1beta.types.ConversionSource: @@ -915,7 +956,7 @@ def delete_conversion_source( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: r"""Archives an existing conversion source. If the conversion source is a Merchant Center Destination, it @@ -961,8 +1002,10 @@ def sample_delete_conversion_source(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 @@ -1012,7 +1055,7 @@ def undelete_conversion_source( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> conversionsources.ConversionSource: r"""Re-enables an archived conversion source. Only Available for Merchant Center Destination conversion @@ -1051,8 +1094,10 @@ def sample_undelete_conversion_source(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_conversions_v1beta.types.ConversionSource: @@ -1103,7 +1148,7 @@ def get_conversion_source( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> conversionsources.ConversionSource: r"""Fetches a conversion source. @@ -1148,8 +1193,10 @@ def sample_get_conversion_source(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_conversions_v1beta.types.ConversionSource: @@ -1211,7 +1258,7 @@ def list_conversion_sources( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListConversionSourcesPager: r"""Retrieves the list of conversion sources the caller has access to. @@ -1258,8 +1305,10 @@ def sample_list_conversion_sources(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_conversions_v1beta.services.conversion_sources_service.pagers.ListConversionSourcesPager: diff --git a/packages/google-shopping-merchant-conversions/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/pagers.py b/packages/google-shopping-merchant-conversions/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/pagers.py index 0673a126f913..6ed9744f1466 100644 --- a/packages/google-shopping-merchant-conversions/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/pagers.py +++ b/packages/google-shopping-merchant-conversions/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/pagers.py @@ -67,7 +67,7 @@ def __init__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiate the pager. @@ -81,8 +81,10 @@ def __init__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 = conversionsources.ListConversionSourcesRequest(request) @@ -143,7 +145,7 @@ def __init__( *, retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiates the pager. @@ -157,8 +159,10 @@ def __init__( 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 = conversionsources.ListConversionSourcesRequest(request) diff --git a/packages/google-shopping-merchant-conversions/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/grpc.py b/packages/google-shopping-merchant-conversions/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/grpc.py index f46de3fcccda..0cc21aa5b952 100644 --- a/packages/google-shopping-merchant-conversions/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/grpc.py +++ b/packages/google-shopping-merchant-conversions/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/grpc.py @@ -13,6 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import json +import logging as std_logging +import pickle from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -21,12 +24,90 @@ 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.shopping.merchant_conversions_v1beta.types import conversionsources from .base import DEFAULT_CLIENT_INFO, ConversionSourcesServiceTransport +try: + from google.api_core import client_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.conversions.v1beta.ConversionSourcesService", + "rpcName": 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.conversions.v1beta.ConversionSourcesService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + class ConversionSourcesServiceGrpcTransport(ConversionSourcesServiceTransport): """gRPC backend transport for ConversionSourcesService. @@ -181,7 +262,12 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -258,7 +344,7 @@ def create_conversion_source( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "create_conversion_source" not in self._stubs: - self._stubs["create_conversion_source"] = self.grpc_channel.unary_unary( + self._stubs["create_conversion_source"] = self._logged_channel.unary_unary( "/google.shopping.merchant.conversions.v1beta.ConversionSourcesService/CreateConversionSource", request_serializer=conversionsources.CreateConversionSourceRequest.serialize, response_deserializer=conversionsources.ConversionSource.deserialize, @@ -289,7 +375,7 @@ def update_conversion_source( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "update_conversion_source" not in self._stubs: - self._stubs["update_conversion_source"] = self.grpc_channel.unary_unary( + self._stubs["update_conversion_source"] = self._logged_channel.unary_unary( "/google.shopping.merchant.conversions.v1beta.ConversionSourcesService/UpdateConversionSource", request_serializer=conversionsources.UpdateConversionSourceRequest.serialize, response_deserializer=conversionsources.ConversionSource.deserialize, @@ -319,7 +405,7 @@ def delete_conversion_source( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "delete_conversion_source" not in self._stubs: - self._stubs["delete_conversion_source"] = self.grpc_channel.unary_unary( + self._stubs["delete_conversion_source"] = self._logged_channel.unary_unary( "/google.shopping.merchant.conversions.v1beta.ConversionSourcesService/DeleteConversionSource", request_serializer=conversionsources.DeleteConversionSourceRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -350,7 +436,9 @@ def undelete_conversion_source( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "undelete_conversion_source" not in self._stubs: - self._stubs["undelete_conversion_source"] = self.grpc_channel.unary_unary( + self._stubs[ + "undelete_conversion_source" + ] = self._logged_channel.unary_unary( "/google.shopping.merchant.conversions.v1beta.ConversionSourcesService/UndeleteConversionSource", request_serializer=conversionsources.UndeleteConversionSourceRequest.serialize, response_deserializer=conversionsources.ConversionSource.deserialize, @@ -379,7 +467,7 @@ def get_conversion_source( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_conversion_source" not in self._stubs: - self._stubs["get_conversion_source"] = self.grpc_channel.unary_unary( + self._stubs["get_conversion_source"] = self._logged_channel.unary_unary( "/google.shopping.merchant.conversions.v1beta.ConversionSourcesService/GetConversionSource", request_serializer=conversionsources.GetConversionSourceRequest.serialize, response_deserializer=conversionsources.ConversionSource.deserialize, @@ -409,7 +497,7 @@ def list_conversion_sources( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_conversion_sources" not in self._stubs: - self._stubs["list_conversion_sources"] = self.grpc_channel.unary_unary( + self._stubs["list_conversion_sources"] = self._logged_channel.unary_unary( "/google.shopping.merchant.conversions.v1beta.ConversionSourcesService/ListConversionSources", request_serializer=conversionsources.ListConversionSourcesRequest.serialize, response_deserializer=conversionsources.ListConversionSourcesResponse.deserialize, @@ -417,7 +505,7 @@ def list_conversion_sources( return self._stubs["list_conversion_sources"] def close(self): - self.grpc_channel.close() + self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-conversions/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-conversions/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/grpc_asyncio.py index 4da59395d836..50c0f6409ce7 100644 --- a/packages/google-shopping-merchant-conversions/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-conversions/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/grpc_asyncio.py @@ -14,6 +14,9 @@ # limitations under the License. # import inspect +import json +import logging as std_logging +import pickle from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -23,14 +26,93 @@ 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 from grpc.experimental import aio # type: ignore +import proto # type: ignore from google.shopping.merchant_conversions_v1beta.types import conversionsources from .base import DEFAULT_CLIENT_INFO, ConversionSourcesServiceTransport from .grpc import ConversionSourcesServiceGrpcTransport +try: + from google.api_core import client_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.conversions.v1beta.ConversionSourcesService", + "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.conversions.v1beta.ConversionSourcesService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + class ConversionSourcesServiceGrpcAsyncIOTransport(ConversionSourcesServiceTransport): """gRPC AsyncIO backend transport for ConversionSourcesService. @@ -228,10 +310,13 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -266,7 +351,7 @@ def create_conversion_source( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "create_conversion_source" not in self._stubs: - self._stubs["create_conversion_source"] = self.grpc_channel.unary_unary( + self._stubs["create_conversion_source"] = self._logged_channel.unary_unary( "/google.shopping.merchant.conversions.v1beta.ConversionSourcesService/CreateConversionSource", request_serializer=conversionsources.CreateConversionSourceRequest.serialize, response_deserializer=conversionsources.ConversionSource.deserialize, @@ -297,7 +382,7 @@ def update_conversion_source( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "update_conversion_source" not in self._stubs: - self._stubs["update_conversion_source"] = self.grpc_channel.unary_unary( + self._stubs["update_conversion_source"] = self._logged_channel.unary_unary( "/google.shopping.merchant.conversions.v1beta.ConversionSourcesService/UpdateConversionSource", request_serializer=conversionsources.UpdateConversionSourceRequest.serialize, response_deserializer=conversionsources.ConversionSource.deserialize, @@ -329,7 +414,7 @@ def delete_conversion_source( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "delete_conversion_source" not in self._stubs: - self._stubs["delete_conversion_source"] = self.grpc_channel.unary_unary( + self._stubs["delete_conversion_source"] = self._logged_channel.unary_unary( "/google.shopping.merchant.conversions.v1beta.ConversionSourcesService/DeleteConversionSource", request_serializer=conversionsources.DeleteConversionSourceRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -360,7 +445,9 @@ def undelete_conversion_source( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "undelete_conversion_source" not in self._stubs: - self._stubs["undelete_conversion_source"] = self.grpc_channel.unary_unary( + self._stubs[ + "undelete_conversion_source" + ] = self._logged_channel.unary_unary( "/google.shopping.merchant.conversions.v1beta.ConversionSourcesService/UndeleteConversionSource", request_serializer=conversionsources.UndeleteConversionSourceRequest.serialize, response_deserializer=conversionsources.ConversionSource.deserialize, @@ -389,7 +476,7 @@ def get_conversion_source( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_conversion_source" not in self._stubs: - self._stubs["get_conversion_source"] = self.grpc_channel.unary_unary( + self._stubs["get_conversion_source"] = self._logged_channel.unary_unary( "/google.shopping.merchant.conversions.v1beta.ConversionSourcesService/GetConversionSource", request_serializer=conversionsources.GetConversionSourceRequest.serialize, response_deserializer=conversionsources.ConversionSource.deserialize, @@ -419,7 +506,7 @@ def list_conversion_sources( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_conversion_sources" not in self._stubs: - self._stubs["list_conversion_sources"] = self.grpc_channel.unary_unary( + self._stubs["list_conversion_sources"] = self._logged_channel.unary_unary( "/google.shopping.merchant.conversions.v1beta.ConversionSourcesService/ListConversionSources", request_serializer=conversionsources.ListConversionSourcesRequest.serialize, response_deserializer=conversionsources.ListConversionSourcesResponse.deserialize, @@ -467,7 +554,7 @@ def _wrap_method(self, func, *args, **kwargs): return gapic_v1.method_async.wrap_method(func, *args, **kwargs) def close(self): - return self.grpc_channel.close() + return self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-conversions/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/rest.py b/packages/google-shopping-merchant-conversions/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/rest.py index 0aeab813fb6a..93fb6bd34cd2 100644 --- a/packages/google-shopping-merchant-conversions/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/rest.py +++ b/packages/google-shopping-merchant-conversions/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/transports/rest.py @@ -13,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import dataclasses import json # type: ignore +import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings @@ -38,6 +38,14 @@ 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, @@ -114,9 +122,10 @@ def post_update_conversion_source(self, response): def pre_create_conversion_source( self, request: conversionsources.CreateConversionSourceRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - conversionsources.CreateConversionSourceRequest, Sequence[Tuple[str, str]] + conversionsources.CreateConversionSourceRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for create_conversion_source @@ -139,9 +148,10 @@ def post_create_conversion_source( def pre_delete_conversion_source( self, request: conversionsources.DeleteConversionSourceRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - conversionsources.DeleteConversionSourceRequest, Sequence[Tuple[str, str]] + conversionsources.DeleteConversionSourceRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for delete_conversion_source @@ -153,8 +163,11 @@ def pre_delete_conversion_source( def pre_get_conversion_source( self, request: conversionsources.GetConversionSourceRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[conversionsources.GetConversionSourceRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + conversionsources.GetConversionSourceRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for get_conversion_source Override in a subclass to manipulate the request or metadata @@ -176,9 +189,10 @@ def post_get_conversion_source( def pre_list_conversion_sources( self, request: conversionsources.ListConversionSourcesRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - conversionsources.ListConversionSourcesRequest, Sequence[Tuple[str, str]] + conversionsources.ListConversionSourcesRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for list_conversion_sources @@ -201,9 +215,10 @@ def post_list_conversion_sources( def pre_undelete_conversion_source( self, request: conversionsources.UndeleteConversionSourceRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - conversionsources.UndeleteConversionSourceRequest, Sequence[Tuple[str, str]] + conversionsources.UndeleteConversionSourceRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for undelete_conversion_source @@ -226,9 +241,10 @@ def post_undelete_conversion_source( def pre_update_conversion_source( self, request: conversionsources.UpdateConversionSourceRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - conversionsources.UpdateConversionSourceRequest, Sequence[Tuple[str, str]] + conversionsources.UpdateConversionSourceRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for update_conversion_source @@ -372,7 +388,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> conversionsources.ConversionSource: r"""Call the create conversion source method over HTTP. @@ -383,8 +399,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.conversionsources.ConversionSource: @@ -398,6 +416,7 @@ def __call__( http_options = ( _BaseConversionSourcesServiceRestTransport._BaseCreateConversionSource._get_http_options() ) + request, metadata = self._interceptor.pre_create_conversion_source( request, metadata ) @@ -414,6 +433,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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.conversions_v1beta.ConversionSourcesServiceClient.CreateConversionSource", + extra={ + "serviceName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", + "rpcName": "CreateConversionSource", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = ConversionSourcesServiceRestTransport._CreateConversionSource._get_response( self._host, @@ -435,7 +481,31 @@ def __call__( pb_resp = conversionsources.ConversionSource.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_conversion_source(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = conversionsources.ConversionSource.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.conversions_v1beta.ConversionSourcesServiceClient.create_conversion_source", + extra={ + "serviceName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", + "rpcName": "CreateConversionSource", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _DeleteConversionSource( @@ -473,7 +543,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ): r"""Call the delete conversion source method over HTTP. @@ -484,13 +554,16 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 = ( _BaseConversionSourcesServiceRestTransport._BaseDeleteConversionSource._get_http_options() ) + request, metadata = self._interceptor.pre_delete_conversion_source( request, metadata ) @@ -503,6 +576,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + 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.conversions_v1beta.ConversionSourcesServiceClient.DeleteConversionSource", + extra={ + "serviceName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", + "rpcName": "DeleteConversionSource", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = ConversionSourcesServiceRestTransport._DeleteConversionSource._get_response( self._host, @@ -553,7 +653,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> conversionsources.ConversionSource: r"""Call the get conversion source method over HTTP. @@ -564,8 +664,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.conversionsources.ConversionSource: @@ -579,6 +681,7 @@ def __call__( http_options = ( _BaseConversionSourcesServiceRestTransport._BaseGetConversionSource._get_http_options() ) + request, metadata = self._interceptor.pre_get_conversion_source( request, metadata ) @@ -591,6 +694,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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.conversions_v1beta.ConversionSourcesServiceClient.GetConversionSource", + extra={ + "serviceName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", + "rpcName": "GetConversionSource", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = ConversionSourcesServiceRestTransport._GetConversionSource._get_response( self._host, @@ -611,7 +741,31 @@ def __call__( pb_resp = conversionsources.ConversionSource.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_conversion_source(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = conversionsources.ConversionSource.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.conversions_v1beta.ConversionSourcesServiceClient.get_conversion_source", + extra={ + "serviceName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", + "rpcName": "GetConversionSource", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _ListConversionSources( @@ -649,7 +803,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> conversionsources.ListConversionSourcesResponse: r"""Call the list conversion sources method over HTTP. @@ -660,8 +814,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.conversionsources.ListConversionSourcesResponse: @@ -673,6 +829,7 @@ def __call__( http_options = ( _BaseConversionSourcesServiceRestTransport._BaseListConversionSources._get_http_options() ) + request, metadata = self._interceptor.pre_list_conversion_sources( request, metadata ) @@ -685,6 +842,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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.conversions_v1beta.ConversionSourcesServiceClient.ListConversionSources", + extra={ + "serviceName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", + "rpcName": "ListConversionSources", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = ConversionSourcesServiceRestTransport._ListConversionSources._get_response( self._host, @@ -705,7 +889,33 @@ def __call__( pb_resp = conversionsources.ListConversionSourcesResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_conversion_sources(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + conversionsources.ListConversionSourcesResponse.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.conversions_v1beta.ConversionSourcesServiceClient.list_conversion_sources", + extra={ + "serviceName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", + "rpcName": "ListConversionSources", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _UndeleteConversionSource( @@ -746,7 +956,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> conversionsources.ConversionSource: r"""Call the undelete conversion source method over HTTP. @@ -758,8 +968,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.conversionsources.ConversionSource: @@ -773,6 +985,7 @@ def __call__( http_options = ( _BaseConversionSourcesServiceRestTransport._BaseUndeleteConversionSource._get_http_options() ) + request, metadata = self._interceptor.pre_undelete_conversion_source( request, metadata ) @@ -789,6 +1002,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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.conversions_v1beta.ConversionSourcesServiceClient.UndeleteConversionSource", + extra={ + "serviceName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", + "rpcName": "UndeleteConversionSource", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = ConversionSourcesServiceRestTransport._UndeleteConversionSource._get_response( self._host, @@ -810,7 +1050,31 @@ def __call__( pb_resp = conversionsources.ConversionSource.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_undelete_conversion_source(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = conversionsources.ConversionSource.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.conversions_v1beta.ConversionSourcesServiceClient.undelete_conversion_source", + extra={ + "serviceName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", + "rpcName": "UndeleteConversionSource", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _UpdateConversionSource( @@ -849,7 +1113,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> conversionsources.ConversionSource: r"""Call the update conversion source method over HTTP. @@ -860,8 +1124,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.conversionsources.ConversionSource: @@ -875,6 +1141,7 @@ def __call__( http_options = ( _BaseConversionSourcesServiceRestTransport._BaseUpdateConversionSource._get_http_options() ) + request, metadata = self._interceptor.pre_update_conversion_source( request, metadata ) @@ -891,6 +1158,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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.conversions_v1beta.ConversionSourcesServiceClient.UpdateConversionSource", + extra={ + "serviceName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", + "rpcName": "UpdateConversionSource", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = ConversionSourcesServiceRestTransport._UpdateConversionSource._get_response( self._host, @@ -912,7 +1206,31 @@ def __call__( pb_resp = conversionsources.ConversionSource.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_conversion_source(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = conversionsources.ConversionSource.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.conversions_v1beta.ConversionSourcesServiceClient.update_conversion_source", + extra={ + "serviceName": "google.shopping.merchant.conversions.v1beta.ConversionSourcesService", + "rpcName": "UpdateConversionSource", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp @property diff --git a/packages/google-shopping-merchant-conversions/samples/generated_samples/snippet_metadata_google.shopping.merchant.conversions.v1beta.json b/packages/google-shopping-merchant-conversions/samples/generated_samples/snippet_metadata_google.shopping.merchant.conversions.v1beta.json index f4c02f3b5464..7b979a5c445b 100644 --- a/packages/google-shopping-merchant-conversions/samples/generated_samples/snippet_metadata_google.shopping.merchant.conversions.v1beta.json +++ b/packages/google-shopping-merchant-conversions/samples/generated_samples/snippet_metadata_google.shopping.merchant.conversions.v1beta.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-shopping-merchant-conversions", - "version": "0.1.5" + "version": "0.1.0" }, "snippets": [ { @@ -51,7 +51,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_conversions_v1beta.types.ConversionSource", @@ -135,7 +135,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_conversions_v1beta.types.ConversionSource", @@ -216,7 +216,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "shortName": "delete_conversion_source" @@ -293,7 +293,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "shortName": "delete_conversion_source" @@ -371,7 +371,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_conversions_v1beta.types.ConversionSource", @@ -451,7 +451,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_conversions_v1beta.types.ConversionSource", @@ -532,7 +532,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_conversions_v1beta.services.conversion_sources_service.pagers.ListConversionSourcesAsyncPager", @@ -612,7 +612,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_conversions_v1beta.services.conversion_sources_service.pagers.ListConversionSourcesPager", @@ -689,7 +689,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_conversions_v1beta.types.ConversionSource", @@ -765,7 +765,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_conversions_v1beta.types.ConversionSource", @@ -850,7 +850,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_conversions_v1beta.types.ConversionSource", @@ -934,7 +934,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_conversions_v1beta.types.ConversionSource", diff --git a/packages/google-shopping-merchant-conversions/tests/unit/gapic/merchant_conversions_v1beta/test_conversion_sources_service.py b/packages/google-shopping-merchant-conversions/tests/unit/gapic/merchant_conversions_v1beta/test_conversion_sources_service.py index e014561c7cb8..740d263c45c6 100644 --- a/packages/google-shopping-merchant-conversions/tests/unit/gapic/merchant_conversions_v1beta/test_conversion_sources_service.py +++ b/packages/google-shopping-merchant-conversions/tests/unit/gapic/merchant_conversions_v1beta/test_conversion_sources_service.py @@ -3500,6 +3500,7 @@ def test_create_conversion_source_rest_required_fields( response_value._content = json_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_conversion_source(request) @@ -3558,6 +3559,7 @@ def test_create_conversion_source_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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_conversion_source(**mock_args) @@ -3697,6 +3699,7 @@ def test_update_conversion_source_rest_required_fields( response_value._content = json_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_conversion_source(request) @@ -3757,6 +3760,7 @@ def test_update_conversion_source_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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_conversion_source(**mock_args) @@ -3895,6 +3899,7 @@ def test_delete_conversion_source_rest_required_fields( response_value._content = json_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_conversion_source(request) @@ -3938,6 +3943,7 @@ def test_delete_conversion_source_rest_flattened(): 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_conversion_source(**mock_args) @@ -4075,6 +4081,7 @@ def test_undelete_conversion_source_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.undelete_conversion_source(request) @@ -4199,6 +4206,7 @@ def test_get_conversion_source_rest_required_fields( response_value._content = json_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_conversion_source(request) @@ -4244,6 +4252,7 @@ def test_get_conversion_source_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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_conversion_source(**mock_args) @@ -4390,6 +4399,7 @@ def test_list_conversion_sources_rest_required_fields( response_value._content = json_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_conversion_sources(request) @@ -4444,6 +4454,7 @@ def test_list_conversion_sources_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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_conversion_sources(**mock_args) @@ -5000,6 +5011,7 @@ def test_create_conversion_source_rest_bad_request( 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_conversion_source(request) @@ -5127,6 +5139,7 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_conversion_source(request) # Establish that the response is the type that we expect. @@ -5171,6 +5184,7 @@ def test_create_conversion_source_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 = conversionsources.ConversionSource.to_json( conversionsources.ConversionSource() ) @@ -5219,6 +5233,7 @@ def test_update_conversion_source_rest_bad_request( 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_conversion_source(request) @@ -5348,6 +5363,7 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_conversion_source(request) # Establish that the response is the type that we expect. @@ -5392,6 +5408,7 @@ def test_update_conversion_source_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 = conversionsources.ConversionSource.to_json( conversionsources.ConversionSource() ) @@ -5438,6 +5455,7 @@ def test_delete_conversion_source_rest_bad_request( 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_conversion_source(request) @@ -5468,6 +5486,7 @@ def test_delete_conversion_source_rest_call_success(request_type): 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_conversion_source(request) # Establish that the response is the type that we expect. @@ -5505,6 +5524,7 @@ def test_delete_conversion_source_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"} request = conversionsources.DeleteConversionSourceRequest() metadata = [ @@ -5545,6 +5565,7 @@ def test_undelete_conversion_source_rest_bad_request( 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.undelete_conversion_source(request) @@ -5582,6 +5603,7 @@ def test_undelete_conversion_source_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.undelete_conversion_source(request) # Establish that the response is the type that we expect. @@ -5626,6 +5648,7 @@ def test_undelete_conversion_source_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 = conversionsources.ConversionSource.to_json( conversionsources.ConversionSource() ) @@ -5672,6 +5695,7 @@ def test_get_conversion_source_rest_bad_request( 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_conversion_source(request) @@ -5709,6 +5733,7 @@ def test_get_conversion_source_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_conversion_source(request) # Establish that the response is the type that we expect. @@ -5751,6 +5776,7 @@ def test_get_conversion_source_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 = conversionsources.ConversionSource.to_json( conversionsources.ConversionSource() ) @@ -5797,6 +5823,7 @@ def test_list_conversion_sources_rest_bad_request( 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_conversion_sources(request) @@ -5832,6 +5859,7 @@ def test_list_conversion_sources_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_conversion_sources(request) # Establish that the response is the type that we expect. @@ -5874,6 +5902,7 @@ def test_list_conversion_sources_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 = conversionsources.ListConversionSourcesResponse.to_json( conversionsources.ListConversionSourcesResponse() ) diff --git a/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources/gapic_version.py b/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources/gapic_version.py index e9c4bb5650f3..558c8aab67c5 100644 --- a/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources/gapic_version.py +++ b/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.5" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/gapic_version.py b/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/gapic_version.py index e9c4bb5650f3..558c8aab67c5 100644 --- a/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/gapic_version.py +++ b/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.5" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/services/data_sources_service/async_client.py b/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/services/data_sources_service/async_client.py index 89103d087586..f7d44f13c10e 100644 --- a/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/services/data_sources_service/async_client.py +++ b/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/services/data_sources_service/async_client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import re from typing import ( Callable, @@ -57,6 +58,15 @@ from .transports.base import DEFAULT_CLIENT_INFO, DataSourcesServiceTransport from .transports.grpc_asyncio import DataSourcesServiceGrpcAsyncIOTransport +try: + from google.api_core import client_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 DataSourcesServiceAsyncClient: """Service to manage primary, supplemental, inventory and other data @@ -272,6 +282,28 @@ def __init__( client_info=client_info, ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.shopping.merchant.datasources_v1beta.DataSourcesServiceAsyncClient`.", + extra={ + "serviceName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", + "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.datasources.v1beta.DataSourcesService", + "credentialsType": None, + }, + ) + async def get_data_source( self, request: Optional[Union[datasources.GetDataSourceRequest, dict]] = None, @@ -279,7 +311,7 @@ async def get_data_source( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> datasources.DataSource: r"""Retrieves the data source configuration for the given account. @@ -324,8 +356,10 @@ async def sample_get_data_source(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_datasources_v1beta.types.DataSource: @@ -386,7 +420,7 @@ async def list_data_sources( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListDataSourcesAsyncPager: r"""Lists the configurations for data sources for the given account. @@ -432,8 +466,10 @@ async def sample_list_data_sources(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_datasources_v1beta.services.data_sources_service.pagers.ListDataSourcesAsyncPager: @@ -509,7 +545,7 @@ async def create_data_source( data_source: Optional[datasources.DataSource] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> datasources.DataSource: r"""Creates the new data source configuration for the given account. @@ -564,8 +600,10 @@ async def sample_create_data_source(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_datasources_v1beta.types.DataSource: @@ -629,7 +667,7 @@ async def update_data_source( 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, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> datasources.DataSource: r"""Updates the existing data source configuration. The fields that are set in the update mask but not provided @@ -692,8 +730,10 @@ async def sample_update_data_source(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_datasources_v1beta.types.DataSource: @@ -758,7 +798,7 @@ async def delete_data_source( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: r"""Deletes a data source from your Merchant Center account. @@ -800,8 +840,10 @@ async def sample_delete_data_source(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 @@ -852,7 +894,7 @@ async def fetch_data_source( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: r"""Performs the data fetch immediately (even outside fetch schedule) on a data source from your Merchant @@ -892,8 +934,10 @@ async def sample_fetch_data_source(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 diff --git a/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/services/data_sources_service/client.py b/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/services/data_sources_service/client.py index 19366f1171b2..e3b7638db779 100644 --- a/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/services/data_sources_service/client.py +++ b/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/services/data_sources_service/client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import os import re from typing import ( @@ -48,6 +49,15 @@ 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_datasources_v1beta.services.data_sources_service import ( @@ -591,6 +601,10 @@ def __init__( # 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( @@ -657,6 +671,29 @@ def __init__( 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.datasources_v1beta.DataSourcesServiceClient`.", + extra={ + "serviceName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", + "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.datasources.v1beta.DataSourcesService", + "credentialsType": None, + }, + ) + def get_data_source( self, request: Optional[Union[datasources.GetDataSourceRequest, dict]] = None, @@ -664,7 +701,7 @@ def get_data_source( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> datasources.DataSource: r"""Retrieves the data source configuration for the given account. @@ -709,8 +746,10 @@ def sample_get_data_source(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_datasources_v1beta.types.DataSource: @@ -768,7 +807,7 @@ def list_data_sources( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListDataSourcesPager: r"""Lists the configurations for data sources for the given account. @@ -814,8 +853,10 @@ def sample_list_data_sources(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_datasources_v1beta.services.data_sources_service.pagers.ListDataSourcesPager: @@ -888,7 +929,7 @@ def create_data_source( data_source: Optional[datasources.DataSource] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> datasources.DataSource: r"""Creates the new data source configuration for the given account. @@ -943,8 +984,10 @@ def sample_create_data_source(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_datasources_v1beta.types.DataSource: @@ -1005,7 +1048,7 @@ def update_data_source( 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, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> datasources.DataSource: r"""Updates the existing data source configuration. The fields that are set in the update mask but not provided @@ -1068,8 +1111,10 @@ def sample_update_data_source(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_datasources_v1beta.types.DataSource: @@ -1131,7 +1176,7 @@ def delete_data_source( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: r"""Deletes a data source from your Merchant Center account. @@ -1173,8 +1218,10 @@ def sample_delete_data_source(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 @@ -1222,7 +1269,7 @@ def fetch_data_source( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: r"""Performs the data fetch immediately (even outside fetch schedule) on a data source from your Merchant @@ -1262,8 +1309,10 @@ def sample_fetch_data_source(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 diff --git a/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/services/data_sources_service/pagers.py b/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/services/data_sources_service/pagers.py index 1f983ce9a916..f368c1829f65 100644 --- a/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/services/data_sources_service/pagers.py +++ b/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/services/data_sources_service/pagers.py @@ -67,7 +67,7 @@ def __init__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiate the pager. @@ -81,8 +81,10 @@ def __init__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 = datasources.ListDataSourcesRequest(request) @@ -141,7 +143,7 @@ def __init__( *, retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiates the pager. @@ -155,8 +157,10 @@ def __init__( 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 = datasources.ListDataSourcesRequest(request) diff --git a/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/grpc.py b/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/grpc.py index e944ad0bfa64..c204d470bbf3 100644 --- a/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/grpc.py +++ b/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/grpc.py @@ -13,6 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import json +import logging as std_logging +import pickle from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -21,12 +24,90 @@ 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.shopping.merchant_datasources_v1beta.types import datasources from .base import DEFAULT_CLIENT_INFO, DataSourcesServiceTransport +try: + from google.api_core import client_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.datasources.v1beta.DataSourcesService", + "rpcName": 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.datasources.v1beta.DataSourcesService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + class DataSourcesServiceGrpcTransport(DataSourcesServiceTransport): """gRPC backend transport for DataSourcesService. @@ -183,7 +264,12 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -258,7 +344,7 @@ def get_data_source( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_data_source" not in self._stubs: - self._stubs["get_data_source"] = self.grpc_channel.unary_unary( + self._stubs["get_data_source"] = self._logged_channel.unary_unary( "/google.shopping.merchant.datasources.v1beta.DataSourcesService/GetDataSource", request_serializer=datasources.GetDataSourceRequest.serialize, response_deserializer=datasources.DataSource.deserialize, @@ -287,7 +373,7 @@ def list_data_sources( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_data_sources" not in self._stubs: - self._stubs["list_data_sources"] = self.grpc_channel.unary_unary( + self._stubs["list_data_sources"] = self._logged_channel.unary_unary( "/google.shopping.merchant.datasources.v1beta.DataSourcesService/ListDataSources", request_serializer=datasources.ListDataSourcesRequest.serialize, response_deserializer=datasources.ListDataSourcesResponse.deserialize, @@ -314,7 +400,7 @@ def create_data_source( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "create_data_source" not in self._stubs: - self._stubs["create_data_source"] = self.grpc_channel.unary_unary( + self._stubs["create_data_source"] = self._logged_channel.unary_unary( "/google.shopping.merchant.datasources.v1beta.DataSourcesService/CreateDataSource", request_serializer=datasources.CreateDataSourceRequest.serialize, response_deserializer=datasources.DataSource.deserialize, @@ -342,7 +428,7 @@ def update_data_source( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "update_data_source" not in self._stubs: - self._stubs["update_data_source"] = self.grpc_channel.unary_unary( + self._stubs["update_data_source"] = self._logged_channel.unary_unary( "/google.shopping.merchant.datasources.v1beta.DataSourcesService/UpdateDataSource", request_serializer=datasources.UpdateDataSourceRequest.serialize, response_deserializer=datasources.DataSource.deserialize, @@ -369,7 +455,7 @@ def delete_data_source( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "delete_data_source" not in self._stubs: - self._stubs["delete_data_source"] = self.grpc_channel.unary_unary( + self._stubs["delete_data_source"] = self._logged_channel.unary_unary( "/google.shopping.merchant.datasources.v1beta.DataSourcesService/DeleteDataSource", request_serializer=datasources.DeleteDataSourceRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -401,7 +487,7 @@ def fetch_data_source( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "fetch_data_source" not in self._stubs: - self._stubs["fetch_data_source"] = self.grpc_channel.unary_unary( + self._stubs["fetch_data_source"] = self._logged_channel.unary_unary( "/google.shopping.merchant.datasources.v1beta.DataSourcesService/FetchDataSource", request_serializer=datasources.FetchDataSourceRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -409,7 +495,7 @@ def fetch_data_source( return self._stubs["fetch_data_source"] def close(self): - self.grpc_channel.close() + self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/grpc_asyncio.py index 77dcf8525878..958181bd7a14 100644 --- a/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/grpc_asyncio.py @@ -14,6 +14,9 @@ # limitations under the License. # import inspect +import json +import logging as std_logging +import pickle from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -23,14 +26,93 @@ 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 from grpc.experimental import aio # type: ignore +import proto # type: ignore from google.shopping.merchant_datasources_v1beta.types import datasources from .base import DEFAULT_CLIENT_INFO, DataSourcesServiceTransport from .grpc import DataSourcesServiceGrpcTransport +try: + from google.api_core import client_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.datasources.v1beta.DataSourcesService", + "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.datasources.v1beta.DataSourcesService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + class DataSourcesServiceGrpcAsyncIOTransport(DataSourcesServiceTransport): """gRPC AsyncIO backend transport for DataSourcesService. @@ -230,10 +312,13 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -268,7 +353,7 @@ def get_data_source( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_data_source" not in self._stubs: - self._stubs["get_data_source"] = self.grpc_channel.unary_unary( + self._stubs["get_data_source"] = self._logged_channel.unary_unary( "/google.shopping.merchant.datasources.v1beta.DataSourcesService/GetDataSource", request_serializer=datasources.GetDataSourceRequest.serialize, response_deserializer=datasources.DataSource.deserialize, @@ -298,7 +383,7 @@ def list_data_sources( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_data_sources" not in self._stubs: - self._stubs["list_data_sources"] = self.grpc_channel.unary_unary( + self._stubs["list_data_sources"] = self._logged_channel.unary_unary( "/google.shopping.merchant.datasources.v1beta.DataSourcesService/ListDataSources", request_serializer=datasources.ListDataSourcesRequest.serialize, response_deserializer=datasources.ListDataSourcesResponse.deserialize, @@ -327,7 +412,7 @@ def create_data_source( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "create_data_source" not in self._stubs: - self._stubs["create_data_source"] = self.grpc_channel.unary_unary( + self._stubs["create_data_source"] = self._logged_channel.unary_unary( "/google.shopping.merchant.datasources.v1beta.DataSourcesService/CreateDataSource", request_serializer=datasources.CreateDataSourceRequest.serialize, response_deserializer=datasources.DataSource.deserialize, @@ -357,7 +442,7 @@ def update_data_source( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "update_data_source" not in self._stubs: - self._stubs["update_data_source"] = self.grpc_channel.unary_unary( + self._stubs["update_data_source"] = self._logged_channel.unary_unary( "/google.shopping.merchant.datasources.v1beta.DataSourcesService/UpdateDataSource", request_serializer=datasources.UpdateDataSourceRequest.serialize, response_deserializer=datasources.DataSource.deserialize, @@ -384,7 +469,7 @@ def delete_data_source( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "delete_data_source" not in self._stubs: - self._stubs["delete_data_source"] = self.grpc_channel.unary_unary( + self._stubs["delete_data_source"] = self._logged_channel.unary_unary( "/google.shopping.merchant.datasources.v1beta.DataSourcesService/DeleteDataSource", request_serializer=datasources.DeleteDataSourceRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -416,7 +501,7 @@ def fetch_data_source( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "fetch_data_source" not in self._stubs: - self._stubs["fetch_data_source"] = self.grpc_channel.unary_unary( + self._stubs["fetch_data_source"] = self._logged_channel.unary_unary( "/google.shopping.merchant.datasources.v1beta.DataSourcesService/FetchDataSource", request_serializer=datasources.FetchDataSourceRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -464,7 +549,7 @@ def _wrap_method(self, func, *args, **kwargs): return gapic_v1.method_async.wrap_method(func, *args, **kwargs) def close(self): - return self.grpc_channel.close() + return self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/rest.py b/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/rest.py index e864db17089a..b523758bc8fb 100644 --- a/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/rest.py +++ b/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/services/data_sources_service/transports/rest.py @@ -13,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import dataclasses import json # type: ignore +import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings @@ -38,6 +38,14 @@ 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, @@ -110,8 +118,10 @@ def post_update_data_source(self, response): def pre_create_data_source( self, request: datasources.CreateDataSourceRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[datasources.CreateDataSourceRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + datasources.CreateDataSourceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for create_data_source Override in a subclass to manipulate the request or metadata @@ -133,8 +143,10 @@ def post_create_data_source( def pre_delete_data_source( self, request: datasources.DeleteDataSourceRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[datasources.DeleteDataSourceRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + datasources.DeleteDataSourceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for delete_data_source Override in a subclass to manipulate the request or metadata @@ -145,8 +157,10 @@ def pre_delete_data_source( def pre_fetch_data_source( self, request: datasources.FetchDataSourceRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[datasources.FetchDataSourceRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + datasources.FetchDataSourceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for fetch_data_source Override in a subclass to manipulate the request or metadata @@ -157,8 +171,10 @@ def pre_fetch_data_source( def pre_get_data_source( self, request: datasources.GetDataSourceRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[datasources.GetDataSourceRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + datasources.GetDataSourceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_data_source Override in a subclass to manipulate the request or metadata @@ -180,8 +196,10 @@ def post_get_data_source( def pre_list_data_sources( self, request: datasources.ListDataSourcesRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[datasources.ListDataSourcesRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + datasources.ListDataSourcesRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for list_data_sources Override in a subclass to manipulate the request or metadata @@ -203,8 +221,10 @@ def post_list_data_sources( def pre_update_data_source( self, request: datasources.UpdateDataSourceRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[datasources.UpdateDataSourceRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + datasources.UpdateDataSourceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for update_data_source Override in a subclass to manipulate the request or metadata @@ -349,7 +369,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> datasources.DataSource: r"""Call the create data source method over HTTP. @@ -360,8 +380,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.datasources.DataSource: @@ -374,6 +396,7 @@ def __call__( http_options = ( _BaseDataSourcesServiceRestTransport._BaseCreateDataSource._get_http_options() ) + request, metadata = self._interceptor.pre_create_data_source( request, metadata ) @@ -390,6 +413,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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.datasources_v1beta.DataSourcesServiceClient.CreateDataSource", + extra={ + "serviceName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", + "rpcName": "CreateDataSource", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = DataSourcesServiceRestTransport._CreateDataSource._get_response( self._host, @@ -411,7 +461,29 @@ def __call__( pb_resp = datasources.DataSource.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_data_source(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = datasources.DataSource.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.datasources_v1beta.DataSourcesServiceClient.create_data_source", + extra={ + "serviceName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", + "rpcName": "CreateDataSource", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _DeleteDataSource( @@ -449,7 +521,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ): r"""Call the delete data source method over HTTP. @@ -460,13 +532,16 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 = ( _BaseDataSourcesServiceRestTransport._BaseDeleteDataSource._get_http_options() ) + request, metadata = self._interceptor.pre_delete_data_source( request, metadata ) @@ -479,6 +554,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + 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.datasources_v1beta.DataSourcesServiceClient.DeleteDataSource", + extra={ + "serviceName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", + "rpcName": "DeleteDataSource", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = DataSourcesServiceRestTransport._DeleteDataSource._get_response( self._host, @@ -530,7 +632,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ): r"""Call the fetch data source method over HTTP. @@ -541,13 +643,16 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 = ( _BaseDataSourcesServiceRestTransport._BaseFetchDataSource._get_http_options() ) + request, metadata = self._interceptor.pre_fetch_data_source( request, metadata ) @@ -564,6 +669,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + 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.datasources_v1beta.DataSourcesServiceClient.FetchDataSource", + extra={ + "serviceName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", + "rpcName": "FetchDataSource", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = DataSourcesServiceRestTransport._FetchDataSource._get_response( self._host, @@ -615,7 +747,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> datasources.DataSource: r"""Call the get data source method over HTTP. @@ -626,8 +758,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.datasources.DataSource: @@ -640,6 +774,7 @@ def __call__( http_options = ( _BaseDataSourcesServiceRestTransport._BaseGetDataSource._get_http_options() ) + request, metadata = self._interceptor.pre_get_data_source(request, metadata) transcoded_request = _BaseDataSourcesServiceRestTransport._BaseGetDataSource._get_transcoded_request( http_options, request @@ -650,6 +785,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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.datasources_v1beta.DataSourcesServiceClient.GetDataSource", + extra={ + "serviceName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", + "rpcName": "GetDataSource", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = DataSourcesServiceRestTransport._GetDataSource._get_response( self._host, @@ -670,7 +832,29 @@ def __call__( pb_resp = datasources.DataSource.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_data_source(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = datasources.DataSource.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.datasources_v1beta.DataSourcesServiceClient.get_data_source", + extra={ + "serviceName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", + "rpcName": "GetDataSource", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _ListDataSources( @@ -708,7 +892,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> datasources.ListDataSourcesResponse: r"""Call the list data sources method over HTTP. @@ -719,8 +903,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.datasources.ListDataSourcesResponse: @@ -732,6 +918,7 @@ def __call__( http_options = ( _BaseDataSourcesServiceRestTransport._BaseListDataSources._get_http_options() ) + request, metadata = self._interceptor.pre_list_data_sources( request, metadata ) @@ -744,6 +931,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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.datasources_v1beta.DataSourcesServiceClient.ListDataSources", + extra={ + "serviceName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", + "rpcName": "ListDataSources", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = DataSourcesServiceRestTransport._ListDataSources._get_response( self._host, @@ -764,7 +978,31 @@ def __call__( pb_resp = datasources.ListDataSourcesResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_data_sources(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = datasources.ListDataSourcesResponse.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.datasources_v1beta.DataSourcesServiceClient.list_data_sources", + extra={ + "serviceName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", + "rpcName": "ListDataSources", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _UpdateDataSource( @@ -803,7 +1041,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> datasources.DataSource: r"""Call the update data source method over HTTP. @@ -814,8 +1052,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.datasources.DataSource: @@ -828,6 +1068,7 @@ def __call__( http_options = ( _BaseDataSourcesServiceRestTransport._BaseUpdateDataSource._get_http_options() ) + request, metadata = self._interceptor.pre_update_data_source( request, metadata ) @@ -844,6 +1085,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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.datasources_v1beta.DataSourcesServiceClient.UpdateDataSource", + extra={ + "serviceName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", + "rpcName": "UpdateDataSource", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = DataSourcesServiceRestTransport._UpdateDataSource._get_response( self._host, @@ -865,7 +1133,29 @@ def __call__( pb_resp = datasources.DataSource.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_data_source(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = datasources.DataSource.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.datasources_v1beta.DataSourcesServiceClient.update_data_source", + extra={ + "serviceName": "google.shopping.merchant.datasources.v1beta.DataSourcesService", + "rpcName": "UpdateDataSource", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp @property diff --git a/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/async_client.py b/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/async_client.py index 909683366907..bc468c249336 100644 --- a/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/async_client.py +++ b/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/async_client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import re from typing import ( Callable, @@ -50,6 +51,15 @@ from .transports.base import DEFAULT_CLIENT_INFO, FileUploadsServiceTransport from .transports.grpc_asyncio import FileUploadsServiceGrpcAsyncIOTransport +try: + from google.api_core import client_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 FileUploadsServiceAsyncClient: """Service to manage data source file uploads.""" @@ -261,6 +271,28 @@ def __init__( client_info=client_info, ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.shopping.merchant.datasources_v1beta.FileUploadsServiceAsyncClient`.", + extra={ + "serviceName": "google.shopping.merchant.datasources.v1beta.FileUploadsService", + "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.datasources.v1beta.FileUploadsService", + "credentialsType": None, + }, + ) + async def get_file_upload( self, request: Optional[Union[fileuploads.GetFileUploadRequest, dict]] = None, @@ -268,7 +300,7 @@ async def get_file_upload( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> fileuploads.FileUpload: r"""Gets the latest data source file upload. Only the ``latest`` alias is accepted for a file upload. @@ -314,8 +346,10 @@ async def sample_get_file_upload(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_datasources_v1beta.types.FileUpload: diff --git a/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/client.py b/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/client.py index 58989eaff667..370ed30093ca 100644 --- a/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/client.py +++ b/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import os import re from typing import ( @@ -48,6 +49,15 @@ 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 timestamp_pb2 # type: ignore from google.shopping.merchant_datasources_v1beta.types import fileuploads @@ -583,6 +593,10 @@ def __init__( # 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( @@ -649,6 +663,29 @@ def __init__( 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.datasources_v1beta.FileUploadsServiceClient`.", + extra={ + "serviceName": "google.shopping.merchant.datasources.v1beta.FileUploadsService", + "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.datasources.v1beta.FileUploadsService", + "credentialsType": None, + }, + ) + def get_file_upload( self, request: Optional[Union[fileuploads.GetFileUploadRequest, dict]] = None, @@ -656,7 +693,7 @@ def get_file_upload( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> fileuploads.FileUpload: r"""Gets the latest data source file upload. Only the ``latest`` alias is accepted for a file upload. @@ -702,8 +739,10 @@ def sample_get_file_upload(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_datasources_v1beta.types.FileUpload: diff --git a/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/grpc.py b/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/grpc.py index 7bbea5efafca..acb6bef134d5 100644 --- a/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/grpc.py +++ b/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/grpc.py @@ -13,6 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import json +import logging as std_logging +import pickle from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -20,12 +23,90 @@ 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_datasources_v1beta.types import fileuploads from .base import DEFAULT_CLIENT_INFO, FileUploadsServiceTransport +try: + from google.api_core import client_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.datasources.v1beta.FileUploadsService", + "rpcName": 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.datasources.v1beta.FileUploadsService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + class FileUploadsServiceGrpcTransport(FileUploadsServiceTransport): """gRPC backend transport for FileUploadsService. @@ -179,7 +260,12 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -254,7 +340,7 @@ def get_file_upload( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_file_upload" not in self._stubs: - self._stubs["get_file_upload"] = self.grpc_channel.unary_unary( + self._stubs["get_file_upload"] = self._logged_channel.unary_unary( "/google.shopping.merchant.datasources.v1beta.FileUploadsService/GetFileUpload", request_serializer=fileuploads.GetFileUploadRequest.serialize, response_deserializer=fileuploads.FileUpload.deserialize, @@ -262,7 +348,7 @@ def get_file_upload( return self._stubs["get_file_upload"] def close(self): - self.grpc_channel.close() + self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/grpc_asyncio.py index 5ef15b13b560..dd64312f7a48 100644 --- a/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/grpc_asyncio.py @@ -14,6 +14,9 @@ # limitations under the License. # import inspect +import json +import logging as std_logging +import pickle from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -22,14 +25,93 @@ 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 from grpc.experimental import aio # type: ignore +import proto # type: ignore from google.shopping.merchant_datasources_v1beta.types import fileuploads from .base import DEFAULT_CLIENT_INFO, FileUploadsServiceTransport from .grpc import FileUploadsServiceGrpcTransport +try: + from google.api_core import client_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.datasources.v1beta.FileUploadsService", + "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.datasources.v1beta.FileUploadsService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + class FileUploadsServiceGrpcAsyncIOTransport(FileUploadsServiceTransport): """gRPC AsyncIO backend transport for FileUploadsService. @@ -226,10 +308,13 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -264,7 +349,7 @@ def get_file_upload( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_file_upload" not in self._stubs: - self._stubs["get_file_upload"] = self.grpc_channel.unary_unary( + self._stubs["get_file_upload"] = self._logged_channel.unary_unary( "/google.shopping.merchant.datasources.v1beta.FileUploadsService/GetFileUpload", request_serializer=fileuploads.GetFileUploadRequest.serialize, response_deserializer=fileuploads.FileUpload.deserialize, @@ -287,7 +372,7 @@ def _wrap_method(self, func, *args, **kwargs): return gapic_v1.method_async.wrap_method(func, *args, **kwargs) def close(self): - return self.grpc_channel.close() + return self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/rest.py b/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/rest.py index e54b65f178a1..2619a225f56a 100644 --- a/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/rest.py +++ b/packages/google-shopping-merchant-datasources/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/transports/rest.py @@ -13,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import dataclasses import json # type: ignore +import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings @@ -37,6 +37,14 @@ 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, @@ -77,8 +85,10 @@ def post_get_file_upload(self, response): def pre_get_file_upload( self, request: fileuploads.GetFileUploadRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[fileuploads.GetFileUploadRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + fileuploads.GetFileUploadRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_file_upload Override in a subclass to manipulate the request or metadata @@ -219,7 +229,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> fileuploads.FileUpload: r"""Call the get file upload method over HTTP. @@ -230,8 +240,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.fileuploads.FileUpload: @@ -248,6 +260,7 @@ def __call__( http_options = ( _BaseFileUploadsServiceRestTransport._BaseGetFileUpload._get_http_options() ) + request, metadata = self._interceptor.pre_get_file_upload(request, metadata) transcoded_request = _BaseFileUploadsServiceRestTransport._BaseGetFileUpload._get_transcoded_request( http_options, request @@ -258,6 +271,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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.datasources_v1beta.FileUploadsServiceClient.GetFileUpload", + extra={ + "serviceName": "google.shopping.merchant.datasources.v1beta.FileUploadsService", + "rpcName": "GetFileUpload", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = FileUploadsServiceRestTransport._GetFileUpload._get_response( self._host, @@ -278,7 +318,29 @@ def __call__( pb_resp = fileuploads.FileUpload.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_file_upload(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = fileuploads.FileUpload.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.datasources_v1beta.FileUploadsServiceClient.get_file_upload", + extra={ + "serviceName": "google.shopping.merchant.datasources.v1beta.FileUploadsService", + "rpcName": "GetFileUpload", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp @property diff --git a/packages/google-shopping-merchant-datasources/samples/generated_samples/snippet_metadata_google.shopping.merchant.datasources.v1beta.json b/packages/google-shopping-merchant-datasources/samples/generated_samples/snippet_metadata_google.shopping.merchant.datasources.v1beta.json index bc99eab63257..992de0dc6fb0 100644 --- a/packages/google-shopping-merchant-datasources/samples/generated_samples/snippet_metadata_google.shopping.merchant.datasources.v1beta.json +++ b/packages/google-shopping-merchant-datasources/samples/generated_samples/snippet_metadata_google.shopping.merchant.datasources.v1beta.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-shopping-merchant-datasources", - "version": "0.1.5" + "version": "0.1.0" }, "snippets": [ { @@ -51,7 +51,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_datasources_v1beta.types.DataSource", @@ -135,7 +135,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_datasources_v1beta.types.DataSource", @@ -216,7 +216,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "shortName": "delete_data_source" @@ -293,7 +293,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "shortName": "delete_data_source" @@ -367,7 +367,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "shortName": "fetch_data_source" @@ -440,7 +440,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "shortName": "fetch_data_source" @@ -518,7 +518,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_datasources_v1beta.types.DataSource", @@ -598,7 +598,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_datasources_v1beta.types.DataSource", @@ -679,7 +679,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_datasources_v1beta.services.data_sources_service.pagers.ListDataSourcesAsyncPager", @@ -759,7 +759,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_datasources_v1beta.services.data_sources_service.pagers.ListDataSourcesPager", @@ -844,7 +844,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_datasources_v1beta.types.DataSource", @@ -928,7 +928,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_datasources_v1beta.types.DataSource", @@ -1009,7 +1009,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_datasources_v1beta.types.FileUpload", @@ -1089,7 +1089,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_datasources_v1beta.types.FileUpload", diff --git a/packages/google-shopping-merchant-datasources/tests/unit/gapic/merchant_datasources_v1beta/test_data_sources_service.py b/packages/google-shopping-merchant-datasources/tests/unit/gapic/merchant_datasources_v1beta/test_data_sources_service.py index a736f6e241c0..a91284b58312 100644 --- a/packages/google-shopping-merchant-datasources/tests/unit/gapic/merchant_datasources_v1beta/test_data_sources_service.py +++ b/packages/google-shopping-merchant-datasources/tests/unit/gapic/merchant_datasources_v1beta/test_data_sources_service.py @@ -3431,6 +3431,7 @@ def test_get_data_source_rest_required_fields( response_value._content = json_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_data_source(request) @@ -3476,6 +3477,7 @@ def test_get_data_source_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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_data_source(**mock_args) @@ -3616,6 +3618,7 @@ def test_list_data_sources_rest_required_fields( response_value._content = json_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_data_sources(request) @@ -3669,6 +3672,7 @@ def test_list_data_sources_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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_data_sources(**mock_args) @@ -3868,6 +3872,7 @@ def test_create_data_source_rest_required_fields( response_value._content = json_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_data_source(request) @@ -3926,6 +3931,7 @@ def test_create_data_source_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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_data_source(**mock_args) @@ -4064,6 +4070,7 @@ def test_update_data_source_rest_required_fields( response_value._content = json_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_data_source(request) @@ -4124,6 +4131,7 @@ def test_update_data_source_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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_data_source(**mock_args) @@ -4261,6 +4269,7 @@ def test_delete_data_source_rest_required_fields( response_value._content = json_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_data_source(request) @@ -4304,6 +4313,7 @@ def test_delete_data_source_rest_flattened(): 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_data_source(**mock_args) @@ -4435,6 +4445,7 @@ def test_fetch_data_source_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.fetch_data_source(request) @@ -4909,6 +4920,7 @@ def test_get_data_source_rest_bad_request( 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_data_source(request) @@ -4947,6 +4959,7 @@ def test_get_data_source_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_data_source(request) # Establish that the response is the type that we expect. @@ -4990,6 +5003,7 @@ def test_get_data_source_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 = datasources.DataSource.to_json(datasources.DataSource()) req.return_value.content = return_value @@ -5034,6 +5048,7 @@ def test_list_data_sources_rest_bad_request( 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_data_sources(request) @@ -5069,6 +5084,7 @@ def test_list_data_sources_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_data_sources(request) # Establish that the response is the type that we expect. @@ -5109,6 +5125,7 @@ def test_list_data_sources_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 = datasources.ListDataSourcesResponse.to_json( datasources.ListDataSourcesResponse() ) @@ -5155,6 +5172,7 @@ def test_create_data_source_rest_bad_request( 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_data_source(request) @@ -5318,6 +5336,7 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_data_source(request) # Establish that the response is the type that we expect. @@ -5361,6 +5380,7 @@ def test_create_data_source_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 = datasources.DataSource.to_json(datasources.DataSource()) req.return_value.content = return_value @@ -5405,6 +5425,7 @@ def test_update_data_source_rest_bad_request( 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_data_source(request) @@ -5568,6 +5589,7 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_data_source(request) # Establish that the response is the type that we expect. @@ -5611,6 +5633,7 @@ def test_update_data_source_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 = datasources.DataSource.to_json(datasources.DataSource()) req.return_value.content = return_value @@ -5655,6 +5678,7 @@ def test_delete_data_source_rest_bad_request( 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_data_source(request) @@ -5685,6 +5709,7 @@ def test_delete_data_source_rest_call_success(request_type): 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_data_source(request) # Establish that the response is the type that we expect. @@ -5721,6 +5746,7 @@ def test_delete_data_source_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"} request = datasources.DeleteDataSourceRequest() metadata = [ @@ -5761,6 +5787,7 @@ def test_fetch_data_source_rest_bad_request( 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.fetch_data_source(request) @@ -5791,6 +5818,7 @@ def test_fetch_data_source_rest_call_success(request_type): 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.fetch_data_source(request) # Establish that the response is the type that we expect. @@ -5827,6 +5855,7 @@ def test_fetch_data_source_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"} request = datasources.FetchDataSourceRequest() metadata = [ diff --git a/packages/google-shopping-merchant-datasources/tests/unit/gapic/merchant_datasources_v1beta/test_file_uploads_service.py b/packages/google-shopping-merchant-datasources/tests/unit/gapic/merchant_datasources_v1beta/test_file_uploads_service.py index 30b7da6ff9dd..1d9ea6845d70 100644 --- a/packages/google-shopping-merchant-datasources/tests/unit/gapic/merchant_datasources_v1beta/test_file_uploads_service.py +++ b/packages/google-shopping-merchant-datasources/tests/unit/gapic/merchant_datasources_v1beta/test_file_uploads_service.py @@ -1547,6 +1547,7 @@ def test_get_file_upload_rest_required_fields( response_value._content = json_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_file_upload(request) @@ -1594,6 +1595,7 @@ def test_get_file_upload_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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_file_upload(**mock_args) @@ -1824,6 +1826,7 @@ def test_get_file_upload_rest_bad_request( 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_file_upload(request) @@ -1864,6 +1867,7 @@ def test_get_file_upload_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_file_upload(request) # Establish that the response is the type that we expect. @@ -1909,6 +1913,7 @@ def test_get_file_upload_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 = fileuploads.FileUpload.to_json(fileuploads.FileUpload()) req.return_value.content = return_value diff --git a/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories/gapic_version.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories/gapic_version.py index 4b834789ba9e..558c8aab67c5 100644 --- a/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories/gapic_version.py +++ b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.11" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/gapic_version.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/gapic_version.py index 4b834789ba9e..558c8aab67c5 100644 --- a/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/gapic_version.py +++ b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.11" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/async_client.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/async_client.py index 5aee1badcfa4..5a47dd695a65 100644 --- a/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/async_client.py +++ b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/async_client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import re from typing import ( Callable, @@ -54,6 +55,15 @@ from .transports.base import DEFAULT_CLIENT_INFO, LocalInventoryServiceTransport from .transports.grpc_asyncio import LocalInventoryServiceGrpcAsyncIOTransport +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + class LocalInventoryServiceAsyncClient: """Service to manage local inventory for products""" @@ -269,6 +279,28 @@ def __init__( client_info=client_info, ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.shopping.merchant.inventories_v1beta.LocalInventoryServiceAsyncClient`.", + extra={ + "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "credentialsType": None, + }, + ) + async def list_local_inventories( self, request: Optional[ @@ -278,7 +310,7 @@ async def list_local_inventories( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListLocalInventoriesAsyncPager: r"""Lists the ``LocalInventory`` resources for the given product in your merchant account. The response might contain fewer items @@ -329,8 +361,10 @@ async def sample_list_local_inventories(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_inventories_v1beta.services.local_inventory_service.pagers.ListLocalInventoriesAsyncPager: @@ -405,7 +439,7 @@ async def insert_local_inventory( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> localinventory.LocalInventory: r"""Inserts a ``LocalInventory`` resource to a product in your merchant account. @@ -454,8 +488,10 @@ async def sample_insert_local_inventory(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_inventories_v1beta.types.LocalInventory: @@ -508,7 +544,7 @@ async def delete_local_inventory( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: r"""Deletes the specified ``LocalInventory`` from the given product in your merchant account. It might take a up to an hour for the @@ -553,8 +589,10 @@ async def sample_delete_local_inventory(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 diff --git a/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/client.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/client.py index 21e8370f3816..29fa40212482 100644 --- a/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/client.py +++ b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import os import re from typing import ( @@ -48,6 +49,15 @@ 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.type.types import types from google.type import interval_pb2 # type: ignore @@ -589,6 +599,10 @@ def __init__( # 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( @@ -655,6 +669,29 @@ def __init__( api_audience=self._client_options.api_audience, ) + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.shopping.merchant.inventories_v1beta.LocalInventoryServiceClient`.", + extra={ + "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "credentialsType": None, + }, + ) + def list_local_inventories( self, request: Optional[ @@ -664,7 +701,7 @@ def list_local_inventories( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListLocalInventoriesPager: r"""Lists the ``LocalInventory`` resources for the given product in your merchant account. The response might contain fewer items @@ -715,8 +752,10 @@ def sample_list_local_inventories(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_inventories_v1beta.services.local_inventory_service.pagers.ListLocalInventoriesPager: @@ -788,7 +827,7 @@ def insert_local_inventory( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> localinventory.LocalInventory: r"""Inserts a ``LocalInventory`` resource to a product in your merchant account. @@ -837,8 +876,10 @@ def sample_insert_local_inventory(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_inventories_v1beta.types.LocalInventory: @@ -889,7 +930,7 @@ def delete_local_inventory( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: r"""Deletes the specified ``LocalInventory`` from the given product in your merchant account. It might take a up to an hour for the @@ -934,8 +975,10 @@ def sample_delete_local_inventory(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 diff --git a/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/pagers.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/pagers.py index f406baae6275..ab034e14e8bd 100644 --- a/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/pagers.py +++ b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/pagers.py @@ -67,7 +67,7 @@ def __init__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiate the pager. @@ -81,8 +81,10 @@ def __init__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = localinventory.ListLocalInventoriesRequest(request) @@ -141,7 +143,7 @@ def __init__( *, retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiates the pager. @@ -155,8 +157,10 @@ def __init__( 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = localinventory.ListLocalInventoriesRequest(request) diff --git a/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/grpc.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/grpc.py index 1a0d7e9d3bf7..e9f818913484 100644 --- a/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/grpc.py +++ b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/grpc.py @@ -13,6 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import json +import logging as std_logging +import pickle from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -21,12 +24,90 @@ 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.shopping.merchant_inventories_v1beta.types import localinventory from .base import DEFAULT_CLIENT_INFO, LocalInventoryServiceTransport +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "rpcName": client_call_details.method, + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + class LocalInventoryServiceGrpcTransport(LocalInventoryServiceTransport): """gRPC backend transport for LocalInventoryService. @@ -180,7 +261,12 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -263,7 +349,7 @@ def list_local_inventories( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_local_inventories" not in self._stubs: - self._stubs["list_local_inventories"] = self.grpc_channel.unary_unary( + self._stubs["list_local_inventories"] = self._logged_channel.unary_unary( "/google.shopping.merchant.inventories.v1beta.LocalInventoryService/ListLocalInventories", request_serializer=localinventory.ListLocalInventoriesRequest.serialize, response_deserializer=localinventory.ListLocalInventoriesResponse.deserialize, @@ -300,7 +386,7 @@ def insert_local_inventory( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "insert_local_inventory" not in self._stubs: - self._stubs["insert_local_inventory"] = self.grpc_channel.unary_unary( + self._stubs["insert_local_inventory"] = self._logged_channel.unary_unary( "/google.shopping.merchant.inventories.v1beta.LocalInventoryService/InsertLocalInventory", request_serializer=localinventory.InsertLocalInventoryRequest.serialize, response_deserializer=localinventory.LocalInventory.deserialize, @@ -330,7 +416,7 @@ def delete_local_inventory( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "delete_local_inventory" not in self._stubs: - self._stubs["delete_local_inventory"] = self.grpc_channel.unary_unary( + self._stubs["delete_local_inventory"] = self._logged_channel.unary_unary( "/google.shopping.merchant.inventories.v1beta.LocalInventoryService/DeleteLocalInventory", request_serializer=localinventory.DeleteLocalInventoryRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -338,7 +424,7 @@ def delete_local_inventory( return self._stubs["delete_local_inventory"] def close(self): - self.grpc_channel.close() + self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/grpc_asyncio.py index 8a71b2ecadb1..7b73b7edebb5 100644 --- a/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/grpc_asyncio.py @@ -14,6 +14,9 @@ # limitations under the License. # import inspect +import json +import logging as std_logging +import pickle from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -23,14 +26,93 @@ 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 from grpc.experimental import aio # type: ignore +import proto # type: ignore from google.shopping.merchant_inventories_v1beta.types import localinventory from .base import DEFAULT_CLIENT_INFO, LocalInventoryServiceTransport from .grpc import LocalInventoryServiceGrpcTransport +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + class LocalInventoryServiceGrpcAsyncIOTransport(LocalInventoryServiceTransport): """gRPC AsyncIO backend transport for LocalInventoryService. @@ -227,10 +309,13 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -271,7 +356,7 @@ def list_local_inventories( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_local_inventories" not in self._stubs: - self._stubs["list_local_inventories"] = self.grpc_channel.unary_unary( + self._stubs["list_local_inventories"] = self._logged_channel.unary_unary( "/google.shopping.merchant.inventories.v1beta.LocalInventoryService/ListLocalInventories", request_serializer=localinventory.ListLocalInventoriesRequest.serialize, response_deserializer=localinventory.ListLocalInventoriesResponse.deserialize, @@ -309,7 +394,7 @@ def insert_local_inventory( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "insert_local_inventory" not in self._stubs: - self._stubs["insert_local_inventory"] = self.grpc_channel.unary_unary( + self._stubs["insert_local_inventory"] = self._logged_channel.unary_unary( "/google.shopping.merchant.inventories.v1beta.LocalInventoryService/InsertLocalInventory", request_serializer=localinventory.InsertLocalInventoryRequest.serialize, response_deserializer=localinventory.LocalInventory.deserialize, @@ -341,7 +426,7 @@ def delete_local_inventory( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "delete_local_inventory" not in self._stubs: - self._stubs["delete_local_inventory"] = self.grpc_channel.unary_unary( + self._stubs["delete_local_inventory"] = self._logged_channel.unary_unary( "/google.shopping.merchant.inventories.v1beta.LocalInventoryService/DeleteLocalInventory", request_serializer=localinventory.DeleteLocalInventoryRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -374,7 +459,7 @@ def _wrap_method(self, func, *args, **kwargs): return gapic_v1.method_async.wrap_method(func, *args, **kwargs) def close(self): - return self.grpc_channel.close() + return self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/rest.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/rest.py index ec939a04a0c4..30a453c86e38 100644 --- a/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/rest.py +++ b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/rest.py @@ -13,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import dataclasses import json # type: ignore +import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings @@ -38,6 +38,14 @@ 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, @@ -90,8 +98,11 @@ def post_list_local_inventories(self, response): def pre_delete_local_inventory( self, request: localinventory.DeleteLocalInventoryRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[localinventory.DeleteLocalInventoryRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + localinventory.DeleteLocalInventoryRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for delete_local_inventory Override in a subclass to manipulate the request or metadata @@ -102,8 +113,11 @@ def pre_delete_local_inventory( def pre_insert_local_inventory( self, request: localinventory.InsertLocalInventoryRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[localinventory.InsertLocalInventoryRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + localinventory.InsertLocalInventoryRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for insert_local_inventory Override in a subclass to manipulate the request or metadata @@ -125,8 +139,11 @@ def post_insert_local_inventory( def pre_list_local_inventories( self, request: localinventory.ListLocalInventoriesRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[localinventory.ListLocalInventoriesRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + localinventory.ListLocalInventoriesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for list_local_inventories Override in a subclass to manipulate the request or metadata @@ -267,7 +284,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ): r"""Call the delete local inventory method over HTTP. @@ -277,13 +294,16 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ http_options = ( _BaseLocalInventoryServiceRestTransport._BaseDeleteLocalInventory._get_http_options() ) + request, metadata = self._interceptor.pre_delete_local_inventory( request, metadata ) @@ -296,6 +316,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.shopping.merchant.inventories_v1beta.LocalInventoryServiceClient.DeleteLocalInventory", + extra={ + "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "rpcName": "DeleteLocalInventory", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = ( LocalInventoryServiceRestTransport._DeleteLocalInventory._get_response( @@ -349,7 +396,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> localinventory.LocalInventory: r"""Call the insert local inventory method over HTTP. @@ -359,8 +406,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.localinventory.LocalInventory: @@ -377,6 +426,7 @@ def __call__( http_options = ( _BaseLocalInventoryServiceRestTransport._BaseInsertLocalInventory._get_http_options() ) + request, metadata = self._interceptor.pre_insert_local_inventory( request, metadata ) @@ -393,6 +443,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.shopping.merchant.inventories_v1beta.LocalInventoryServiceClient.InsertLocalInventory", + extra={ + "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "rpcName": "InsertLocalInventory", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = ( LocalInventoryServiceRestTransport._InsertLocalInventory._get_response( @@ -416,7 +493,29 @@ def __call__( pb_resp = localinventory.LocalInventory.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_insert_local_inventory(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = localinventory.LocalInventory.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.shopping.merchant.inventories_v1beta.LocalInventoryServiceClient.insert_local_inventory", + extra={ + "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "rpcName": "InsertLocalInventory", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _ListLocalInventories( @@ -454,7 +553,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> localinventory.ListLocalInventoriesResponse: r"""Call the list local inventories method over HTTP. @@ -464,8 +563,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.localinventory.ListLocalInventoriesResponse: @@ -477,6 +578,7 @@ def __call__( http_options = ( _BaseLocalInventoryServiceRestTransport._BaseListLocalInventories._get_http_options() ) + request, metadata = self._interceptor.pre_list_local_inventories( request, metadata ) @@ -489,6 +591,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.shopping.merchant.inventories_v1beta.LocalInventoryServiceClient.ListLocalInventories", + extra={ + "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "rpcName": "ListLocalInventories", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = ( LocalInventoryServiceRestTransport._ListLocalInventories._get_response( @@ -511,7 +640,31 @@ def __call__( pb_resp = localinventory.ListLocalInventoriesResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_local_inventories(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + localinventory.ListLocalInventoriesResponse.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.shopping.merchant.inventories_v1beta.LocalInventoryServiceClient.list_local_inventories", + extra={ + "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "rpcName": "ListLocalInventories", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp @property diff --git a/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/async_client.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/async_client.py index bd282b0768bb..7ce92f97ef97 100644 --- a/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/async_client.py +++ b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/async_client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import re from typing import ( Callable, @@ -54,6 +55,15 @@ from .transports.base import DEFAULT_CLIENT_INFO, RegionalInventoryServiceTransport from .transports.grpc_asyncio import RegionalInventoryServiceGrpcAsyncIOTransport +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + class RegionalInventoryServiceAsyncClient: """Service to manage regional inventory for products. There is also @@ -275,6 +285,28 @@ def __init__( client_info=client_info, ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.shopping.merchant.inventories_v1beta.RegionalInventoryServiceAsyncClient`.", + extra={ + "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "credentialsType": None, + }, + ) + async def list_regional_inventories( self, request: Optional[ @@ -284,7 +316,7 @@ async def list_regional_inventories( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListRegionalInventoriesAsyncPager: r"""Lists the ``RegionalInventory`` resources for the given product in your merchant account. The response might contain fewer items @@ -336,8 +368,10 @@ async def sample_list_regional_inventories(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.pagers.ListRegionalInventoriesAsyncPager: @@ -412,7 +446,7 @@ async def insert_regional_inventory( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> regionalinventory.RegionalInventory: r"""Inserts a ``RegionalInventory`` to a given product in your merchant account. @@ -462,8 +496,10 @@ async def sample_insert_regional_inventory(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_inventories_v1beta.types.RegionalInventory: @@ -517,7 +553,7 @@ async def delete_regional_inventory( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: r"""Deletes the specified ``RegionalInventory`` resource from the given product in your merchant account. It might take up to an @@ -563,8 +599,10 @@ async def sample_delete_regional_inventory(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 diff --git a/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/client.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/client.py index 6498c4d3b7dc..907abc8f8165 100644 --- a/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/client.py +++ b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import os import re from typing import ( @@ -48,6 +49,15 @@ 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.type.types import types from google.type import interval_pb2 # type: ignore @@ -595,6 +605,10 @@ def __init__( # 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( @@ -661,6 +675,29 @@ def __init__( api_audience=self._client_options.api_audience, ) + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.shopping.merchant.inventories_v1beta.RegionalInventoryServiceClient`.", + extra={ + "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "credentialsType": None, + }, + ) + def list_regional_inventories( self, request: Optional[ @@ -670,7 +707,7 @@ def list_regional_inventories( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListRegionalInventoriesPager: r"""Lists the ``RegionalInventory`` resources for the given product in your merchant account. The response might contain fewer items @@ -722,8 +759,10 @@ def sample_list_regional_inventories(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.pagers.ListRegionalInventoriesPager: @@ -797,7 +836,7 @@ def insert_regional_inventory( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> regionalinventory.RegionalInventory: r"""Inserts a ``RegionalInventory`` to a given product in your merchant account. @@ -847,8 +886,10 @@ def sample_insert_regional_inventory(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_inventories_v1beta.types.RegionalInventory: @@ -902,7 +943,7 @@ def delete_regional_inventory( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: r"""Deletes the specified ``RegionalInventory`` resource from the given product in your merchant account. It might take up to an @@ -948,8 +989,10 @@ def sample_delete_regional_inventory(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 diff --git a/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/pagers.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/pagers.py index bf4c7bbb459c..4f4a49429075 100644 --- a/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/pagers.py +++ b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/pagers.py @@ -67,7 +67,7 @@ def __init__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiate the pager. @@ -81,8 +81,10 @@ def __init__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = regionalinventory.ListRegionalInventoriesRequest(request) @@ -143,7 +145,7 @@ def __init__( *, retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiates the pager. @@ -157,8 +159,10 @@ def __init__( 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = regionalinventory.ListRegionalInventoriesRequest(request) diff --git a/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/grpc.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/grpc.py index 5215b94b2081..b4aabbb32b38 100644 --- a/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/grpc.py +++ b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/grpc.py @@ -13,6 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import json +import logging as std_logging +import pickle from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -21,12 +24,90 @@ 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.shopping.merchant_inventories_v1beta.types import regionalinventory from .base import DEFAULT_CLIENT_INFO, RegionalInventoryServiceTransport +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "rpcName": client_call_details.method, + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + class RegionalInventoryServiceGrpcTransport(RegionalInventoryServiceTransport): """gRPC backend transport for RegionalInventoryService. @@ -181,7 +262,12 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -264,7 +350,7 @@ def list_regional_inventories( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_regional_inventories" not in self._stubs: - self._stubs["list_regional_inventories"] = self.grpc_channel.unary_unary( + self._stubs["list_regional_inventories"] = self._logged_channel.unary_unary( "/google.shopping.merchant.inventories.v1beta.RegionalInventoryService/ListRegionalInventories", request_serializer=regionalinventory.ListRegionalInventoriesRequest.serialize, response_deserializer=regionalinventory.ListRegionalInventoriesResponse.deserialize, @@ -302,7 +388,7 @@ def insert_regional_inventory( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "insert_regional_inventory" not in self._stubs: - self._stubs["insert_regional_inventory"] = self.grpc_channel.unary_unary( + self._stubs["insert_regional_inventory"] = self._logged_channel.unary_unary( "/google.shopping.merchant.inventories.v1beta.RegionalInventoryService/InsertRegionalInventory", request_serializer=regionalinventory.InsertRegionalInventoryRequest.serialize, response_deserializer=regionalinventory.RegionalInventory.deserialize, @@ -332,7 +418,7 @@ def delete_regional_inventory( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "delete_regional_inventory" not in self._stubs: - self._stubs["delete_regional_inventory"] = self.grpc_channel.unary_unary( + self._stubs["delete_regional_inventory"] = self._logged_channel.unary_unary( "/google.shopping.merchant.inventories.v1beta.RegionalInventoryService/DeleteRegionalInventory", request_serializer=regionalinventory.DeleteRegionalInventoryRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -340,7 +426,7 @@ def delete_regional_inventory( return self._stubs["delete_regional_inventory"] def close(self): - self.grpc_channel.close() + self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/grpc_asyncio.py index ee343ccd46f6..2c924edda86b 100644 --- a/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/grpc_asyncio.py @@ -14,6 +14,9 @@ # limitations under the License. # import inspect +import json +import logging as std_logging +import pickle from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -23,14 +26,93 @@ 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 from grpc.experimental import aio # type: ignore +import proto # type: ignore from google.shopping.merchant_inventories_v1beta.types import regionalinventory from .base import DEFAULT_CLIENT_INFO, RegionalInventoryServiceTransport from .grpc import RegionalInventoryServiceGrpcTransport +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + class RegionalInventoryServiceGrpcAsyncIOTransport(RegionalInventoryServiceTransport): """gRPC AsyncIO backend transport for RegionalInventoryService. @@ -228,10 +310,13 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -272,7 +357,7 @@ def list_regional_inventories( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_regional_inventories" not in self._stubs: - self._stubs["list_regional_inventories"] = self.grpc_channel.unary_unary( + self._stubs["list_regional_inventories"] = self._logged_channel.unary_unary( "/google.shopping.merchant.inventories.v1beta.RegionalInventoryService/ListRegionalInventories", request_serializer=regionalinventory.ListRegionalInventoriesRequest.serialize, response_deserializer=regionalinventory.ListRegionalInventoriesResponse.deserialize, @@ -310,7 +395,7 @@ def insert_regional_inventory( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "insert_regional_inventory" not in self._stubs: - self._stubs["insert_regional_inventory"] = self.grpc_channel.unary_unary( + self._stubs["insert_regional_inventory"] = self._logged_channel.unary_unary( "/google.shopping.merchant.inventories.v1beta.RegionalInventoryService/InsertRegionalInventory", request_serializer=regionalinventory.InsertRegionalInventoryRequest.serialize, response_deserializer=regionalinventory.RegionalInventory.deserialize, @@ -342,7 +427,7 @@ def delete_regional_inventory( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "delete_regional_inventory" not in self._stubs: - self._stubs["delete_regional_inventory"] = self.grpc_channel.unary_unary( + self._stubs["delete_regional_inventory"] = self._logged_channel.unary_unary( "/google.shopping.merchant.inventories.v1beta.RegionalInventoryService/DeleteRegionalInventory", request_serializer=regionalinventory.DeleteRegionalInventoryRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -375,7 +460,7 @@ def _wrap_method(self, func, *args, **kwargs): return gapic_v1.method_async.wrap_method(func, *args, **kwargs) def close(self): - return self.grpc_channel.close() + return self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/rest.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/rest.py index 9c4f8f69ed40..e03a5e4fa4ec 100644 --- a/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/rest.py +++ b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/rest.py @@ -13,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import dataclasses import json # type: ignore +import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings @@ -38,6 +38,14 @@ 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, @@ -90,9 +98,10 @@ def post_list_regional_inventories(self, response): def pre_delete_regional_inventory( self, request: regionalinventory.DeleteRegionalInventoryRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - regionalinventory.DeleteRegionalInventoryRequest, Sequence[Tuple[str, str]] + regionalinventory.DeleteRegionalInventoryRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for delete_regional_inventory @@ -104,9 +113,10 @@ def pre_delete_regional_inventory( def pre_insert_regional_inventory( self, request: regionalinventory.InsertRegionalInventoryRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - regionalinventory.InsertRegionalInventoryRequest, Sequence[Tuple[str, str]] + regionalinventory.InsertRegionalInventoryRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for insert_regional_inventory @@ -129,9 +139,10 @@ def post_insert_regional_inventory( def pre_list_regional_inventories( self, request: regionalinventory.ListRegionalInventoriesRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - regionalinventory.ListRegionalInventoriesRequest, Sequence[Tuple[str, str]] + regionalinventory.ListRegionalInventoriesRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for list_regional_inventories @@ -274,7 +285,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ): r"""Call the delete regional inventory method over HTTP. @@ -285,13 +296,16 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ http_options = ( _BaseRegionalInventoryServiceRestTransport._BaseDeleteRegionalInventory._get_http_options() ) + request, metadata = self._interceptor.pre_delete_regional_inventory( request, metadata ) @@ -304,6 +318,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.shopping.merchant.inventories_v1beta.RegionalInventoryServiceClient.DeleteRegionalInventory", + extra={ + "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "rpcName": "DeleteRegionalInventory", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = RegionalInventoryServiceRestTransport._DeleteRegionalInventory._get_response( self._host, @@ -355,7 +396,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> regionalinventory.RegionalInventory: r"""Call the insert regional inventory method over HTTP. @@ -366,8 +407,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.regionalinventory.RegionalInventory: @@ -384,6 +427,7 @@ def __call__( http_options = ( _BaseRegionalInventoryServiceRestTransport._BaseInsertRegionalInventory._get_http_options() ) + request, metadata = self._interceptor.pre_insert_regional_inventory( request, metadata ) @@ -400,6 +444,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.shopping.merchant.inventories_v1beta.RegionalInventoryServiceClient.InsertRegionalInventory", + extra={ + "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "rpcName": "InsertRegionalInventory", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = RegionalInventoryServiceRestTransport._InsertRegionalInventory._get_response( self._host, @@ -421,7 +492,31 @@ def __call__( pb_resp = regionalinventory.RegionalInventory.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_insert_regional_inventory(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = regionalinventory.RegionalInventory.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.shopping.merchant.inventories_v1beta.RegionalInventoryServiceClient.insert_regional_inventory", + extra={ + "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "rpcName": "InsertRegionalInventory", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _ListRegionalInventories( @@ -459,7 +554,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> regionalinventory.ListRegionalInventoriesResponse: r"""Call the list regional inventories method over HTTP. @@ -470,8 +565,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.regionalinventory.ListRegionalInventoriesResponse: @@ -483,6 +580,7 @@ def __call__( http_options = ( _BaseRegionalInventoryServiceRestTransport._BaseListRegionalInventories._get_http_options() ) + request, metadata = self._interceptor.pre_list_regional_inventories( request, metadata ) @@ -495,6 +593,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.shopping.merchant.inventories_v1beta.RegionalInventoryServiceClient.ListRegionalInventories", + extra={ + "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "rpcName": "ListRegionalInventories", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = RegionalInventoryServiceRestTransport._ListRegionalInventories._get_response( self._host, @@ -515,7 +640,33 @@ def __call__( pb_resp = regionalinventory.ListRegionalInventoriesResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_regional_inventories(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + regionalinventory.ListRegionalInventoriesResponse.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.shopping.merchant.inventories_v1beta.RegionalInventoryServiceClient.list_regional_inventories", + extra={ + "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "rpcName": "ListRegionalInventories", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp @property diff --git a/packages/google-shopping-merchant-inventories/samples/generated_samples/snippet_metadata_google.shopping.merchant.inventories.v1beta.json b/packages/google-shopping-merchant-inventories/samples/generated_samples/snippet_metadata_google.shopping.merchant.inventories.v1beta.json index 7366fa8519af..73ddfcf94070 100644 --- a/packages/google-shopping-merchant-inventories/samples/generated_samples/snippet_metadata_google.shopping.merchant.inventories.v1beta.json +++ b/packages/google-shopping-merchant-inventories/samples/generated_samples/snippet_metadata_google.shopping.merchant.inventories.v1beta.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-shopping-merchant-inventories", - "version": "0.1.11" + "version": "0.1.0" }, "snippets": [ { @@ -47,7 +47,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "shortName": "delete_local_inventory" @@ -124,7 +124,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "shortName": "delete_local_inventory" @@ -198,7 +198,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_inventories_v1beta.types.LocalInventory", @@ -274,7 +274,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_inventories_v1beta.types.LocalInventory", @@ -355,7 +355,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_inventories_v1beta.services.local_inventory_service.pagers.ListLocalInventoriesAsyncPager", @@ -435,7 +435,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_inventories_v1beta.services.local_inventory_service.pagers.ListLocalInventoriesPager", @@ -516,7 +516,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "shortName": "delete_regional_inventory" @@ -593,7 +593,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "shortName": "delete_regional_inventory" @@ -667,7 +667,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_inventories_v1beta.types.RegionalInventory", @@ -743,7 +743,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_inventories_v1beta.types.RegionalInventory", @@ -824,7 +824,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.pagers.ListRegionalInventoriesAsyncPager", @@ -904,7 +904,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.pagers.ListRegionalInventoriesPager", diff --git a/packages/google-shopping-merchant-inventories/tests/unit/gapic/merchant_inventories_v1beta/test_local_inventory_service.py b/packages/google-shopping-merchant-inventories/tests/unit/gapic/merchant_inventories_v1beta/test_local_inventory_service.py index b62c5e6296cc..12a25e57fe34 100644 --- a/packages/google-shopping-merchant-inventories/tests/unit/gapic/merchant_inventories_v1beta/test_local_inventory_service.py +++ b/packages/google-shopping-merchant-inventories/tests/unit/gapic/merchant_inventories_v1beta/test_local_inventory_service.py @@ -2402,6 +2402,7 @@ def test_list_local_inventories_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_local_inventories(request) @@ -2455,6 +2456,7 @@ def test_list_local_inventories_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.list_local_inventories(**mock_args) @@ -2655,6 +2657,7 @@ def test_insert_local_inventory_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.insert_local_inventory(request) @@ -2784,6 +2787,7 @@ def test_delete_local_inventory_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.delete_local_inventory(request) @@ -2829,6 +2833,7 @@ def test_delete_local_inventory_rest_flattened(): json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.delete_local_inventory(**mock_args) @@ -3165,6 +3170,7 @@ def test_list_local_inventories_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.list_local_inventories(request) @@ -3200,6 +3206,7 @@ def test_list_local_inventories_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_local_inventories(request) # Establish that the response is the type that we expect. @@ -3240,6 +3247,7 @@ def test_list_local_inventories_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = localinventory.ListLocalInventoriesResponse.to_json( localinventory.ListLocalInventoriesResponse() ) @@ -3286,6 +3294,7 @@ def test_insert_local_inventory_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.insert_local_inventory(request) @@ -3416,6 +3425,7 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.insert_local_inventory(request) # Establish that the response is the type that we expect. @@ -3463,6 +3473,7 @@ def test_insert_local_inventory_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = localinventory.LocalInventory.to_json( localinventory.LocalInventory() ) @@ -3511,6 +3522,7 @@ def test_delete_local_inventory_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.delete_local_inventory(request) @@ -3543,6 +3555,7 @@ def test_delete_local_inventory_rest_call_success(request_type): json_return_value = "" response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.delete_local_inventory(request) # Establish that the response is the type that we expect. @@ -3579,6 +3592,7 @@ def test_delete_local_inventory_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} request = localinventory.DeleteLocalInventoryRequest() metadata = [ diff --git a/packages/google-shopping-merchant-inventories/tests/unit/gapic/merchant_inventories_v1beta/test_regional_inventory_service.py b/packages/google-shopping-merchant-inventories/tests/unit/gapic/merchant_inventories_v1beta/test_regional_inventory_service.py index f6137265258b..ca08ede3303e 100644 --- a/packages/google-shopping-merchant-inventories/tests/unit/gapic/merchant_inventories_v1beta/test_regional_inventory_service.py +++ b/packages/google-shopping-merchant-inventories/tests/unit/gapic/merchant_inventories_v1beta/test_regional_inventory_service.py @@ -2400,6 +2400,7 @@ def test_list_regional_inventories_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_regional_inventories(request) @@ -2455,6 +2456,7 @@ def test_list_regional_inventories_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.list_regional_inventories(**mock_args) @@ -2656,6 +2658,7 @@ def test_insert_regional_inventory_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.insert_regional_inventory(request) @@ -2785,6 +2788,7 @@ def test_delete_regional_inventory_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.delete_regional_inventory(request) @@ -2830,6 +2834,7 @@ def test_delete_regional_inventory_rest_flattened(): json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.delete_regional_inventory(**mock_args) @@ -3162,6 +3167,7 @@ def test_list_regional_inventories_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.list_regional_inventories(request) @@ -3199,6 +3205,7 @@ def test_list_regional_inventories_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_regional_inventories(request) # Establish that the response is the type that we expect. @@ -3241,6 +3248,7 @@ def test_list_regional_inventories_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = regionalinventory.ListRegionalInventoriesResponse.to_json( regionalinventory.ListRegionalInventoriesResponse() ) @@ -3287,6 +3295,7 @@ def test_insert_regional_inventory_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.insert_regional_inventory(request) @@ -3409,6 +3418,7 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.insert_regional_inventory(request) # Establish that the response is the type that we expect. @@ -3454,6 +3464,7 @@ def test_insert_regional_inventory_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = regionalinventory.RegionalInventory.to_json( regionalinventory.RegionalInventory() ) @@ -3502,6 +3513,7 @@ def test_delete_regional_inventory_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.delete_regional_inventory(request) @@ -3534,6 +3546,7 @@ def test_delete_regional_inventory_rest_call_success(request_type): json_return_value = "" response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.delete_regional_inventory(request) # Establish that the response is the type that we expect. @@ -3571,6 +3584,7 @@ def test_delete_regional_inventory_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} request = regionalinventory.DeleteRegionalInventoryRequest() metadata = [ diff --git a/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp/gapic_version.py b/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp/gapic_version.py index e9c4bb5650f3..558c8aab67c5 100644 --- a/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp/gapic_version.py +++ b/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.5" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/gapic_version.py b/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/gapic_version.py index e9c4bb5650f3..558c8aab67c5 100644 --- a/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/gapic_version.py +++ b/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.5" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/async_client.py b/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/async_client.py index 58e49da98983..acc3b3c969da 100644 --- a/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/async_client.py +++ b/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/async_client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import re from typing import ( Callable, @@ -51,6 +52,15 @@ from .transports.base import DEFAULT_CLIENT_INFO, LfpInventoryServiceTransport from .transports.grpc_asyncio import LfpInventoryServiceGrpcAsyncIOTransport +try: + from google.api_core import client_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 LfpInventoryServiceAsyncClient: """Service for a `LFP @@ -265,13 +275,35 @@ def __init__( client_info=client_info, ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.shopping.merchant.lfp_v1beta.LfpInventoryServiceAsyncClient`.", + extra={ + "serviceName": "google.shopping.merchant.lfp.v1beta.LfpInventoryService", + "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.lfp.v1beta.LfpInventoryService", + "credentialsType": None, + }, + ) + async def insert_lfp_inventory( self, request: Optional[Union[lfpinventory.InsertLfpInventoryRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> lfpinventory.LfpInventory: r"""Inserts a ``LfpInventory`` resource for the given target merchant account. If the resource already exists, it will be @@ -318,8 +350,10 @@ async def sample_insert_lfp_inventory(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_lfp_v1beta.types.LfpInventory: diff --git a/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/client.py b/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/client.py index 0004840ef92b..08c5e1569a61 100644 --- a/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/client.py +++ b/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import os import re from typing import ( @@ -48,6 +49,15 @@ 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 timestamp_pb2 # type: ignore from google.shopping.type.types import types @@ -589,6 +599,10 @@ def __init__( # 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( @@ -655,13 +669,36 @@ def __init__( 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.lfp_v1beta.LfpInventoryServiceClient`.", + extra={ + "serviceName": "google.shopping.merchant.lfp.v1beta.LfpInventoryService", + "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.lfp.v1beta.LfpInventoryService", + "credentialsType": None, + }, + ) + def insert_lfp_inventory( self, request: Optional[Union[lfpinventory.InsertLfpInventoryRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> lfpinventory.LfpInventory: r"""Inserts a ``LfpInventory`` resource for the given target merchant account. If the resource already exists, it will be @@ -708,8 +745,10 @@ def sample_insert_lfp_inventory(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_lfp_v1beta.types.LfpInventory: diff --git a/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/grpc.py b/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/grpc.py index 24517af1b5fd..3215cd86350a 100644 --- a/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/grpc.py +++ b/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/grpc.py @@ -13,6 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import json +import logging as std_logging +import pickle from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -20,12 +23,90 @@ 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_lfp_v1beta.types import lfpinventory from .base import DEFAULT_CLIENT_INFO, LfpInventoryServiceTransport +try: + from google.api_core import client_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.lfp.v1beta.LfpInventoryService", + "rpcName": 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.lfp.v1beta.LfpInventoryService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + class LfpInventoryServiceGrpcTransport(LfpInventoryServiceTransport): """gRPC backend transport for LfpInventoryService. @@ -181,7 +262,12 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -257,7 +343,7 @@ def insert_lfp_inventory( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "insert_lfp_inventory" not in self._stubs: - self._stubs["insert_lfp_inventory"] = self.grpc_channel.unary_unary( + self._stubs["insert_lfp_inventory"] = self._logged_channel.unary_unary( "/google.shopping.merchant.lfp.v1beta.LfpInventoryService/InsertLfpInventory", request_serializer=lfpinventory.InsertLfpInventoryRequest.serialize, response_deserializer=lfpinventory.LfpInventory.deserialize, @@ -265,7 +351,7 @@ def insert_lfp_inventory( return self._stubs["insert_lfp_inventory"] def close(self): - self.grpc_channel.close() + self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/grpc_asyncio.py index 5aed7328c0f1..815c271b8ebd 100644 --- a/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/grpc_asyncio.py @@ -14,6 +14,9 @@ # limitations under the License. # import inspect +import json +import logging as std_logging +import pickle from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -22,14 +25,93 @@ 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 from grpc.experimental import aio # type: ignore +import proto # type: ignore from google.shopping.merchant_lfp_v1beta.types import lfpinventory from .base import DEFAULT_CLIENT_INFO, LfpInventoryServiceTransport from .grpc import LfpInventoryServiceGrpcTransport +try: + from google.api_core import client_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.lfp.v1beta.LfpInventoryService", + "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.lfp.v1beta.LfpInventoryService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + class LfpInventoryServiceGrpcAsyncIOTransport(LfpInventoryServiceTransport): """gRPC AsyncIO backend transport for LfpInventoryService. @@ -228,10 +310,13 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -267,7 +352,7 @@ def insert_lfp_inventory( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "insert_lfp_inventory" not in self._stubs: - self._stubs["insert_lfp_inventory"] = self.grpc_channel.unary_unary( + self._stubs["insert_lfp_inventory"] = self._logged_channel.unary_unary( "/google.shopping.merchant.lfp.v1beta.LfpInventoryService/InsertLfpInventory", request_serializer=lfpinventory.InsertLfpInventoryRequest.serialize, response_deserializer=lfpinventory.LfpInventory.deserialize, @@ -290,7 +375,7 @@ def _wrap_method(self, func, *args, **kwargs): return gapic_v1.method_async.wrap_method(func, *args, **kwargs) def close(self): - return self.grpc_channel.close() + return self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/rest.py b/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/rest.py index f123a2fa4f5e..3db7ac1e849a 100644 --- a/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/rest.py +++ b/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/transports/rest.py @@ -13,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import dataclasses import json # type: ignore +import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings @@ -37,6 +37,14 @@ 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, @@ -77,8 +85,10 @@ def post_insert_lfp_inventory(self, response): def pre_insert_lfp_inventory( self, request: lfpinventory.InsertLfpInventoryRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[lfpinventory.InsertLfpInventoryRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + lfpinventory.InsertLfpInventoryRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for insert_lfp_inventory Override in a subclass to manipulate the request or metadata @@ -222,7 +232,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> lfpinventory.LfpInventory: r"""Call the insert lfp inventory method over HTTP. @@ -232,8 +242,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.lfpinventory.LfpInventory: @@ -243,6 +255,7 @@ def __call__( http_options = ( _BaseLfpInventoryServiceRestTransport._BaseInsertLfpInventory._get_http_options() ) + request, metadata = self._interceptor.pre_insert_lfp_inventory( request, metadata ) @@ -259,6 +272,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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.lfp_v1beta.LfpInventoryServiceClient.InsertLfpInventory", + extra={ + "serviceName": "google.shopping.merchant.lfp.v1beta.LfpInventoryService", + "rpcName": "InsertLfpInventory", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = ( LfpInventoryServiceRestTransport._InsertLfpInventory._get_response( @@ -282,7 +322,29 @@ def __call__( pb_resp = lfpinventory.LfpInventory.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_insert_lfp_inventory(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = lfpinventory.LfpInventory.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.lfp_v1beta.LfpInventoryServiceClient.insert_lfp_inventory", + extra={ + "serviceName": "google.shopping.merchant.lfp.v1beta.LfpInventoryService", + "rpcName": "InsertLfpInventory", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp @property diff --git a/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/async_client.py b/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/async_client.py index 57a52a52191d..6d6d8c5425e4 100644 --- a/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/async_client.py +++ b/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/async_client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import re from typing import ( Callable, @@ -51,6 +52,15 @@ from .transports.base import DEFAULT_CLIENT_INFO, LfpSaleServiceTransport from .transports.grpc_asyncio import LfpSaleServiceGrpcAsyncIOTransport +try: + from google.api_core import client_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 LfpSaleServiceAsyncClient: """Service for a `LFP @@ -259,13 +269,35 @@ def __init__( client_info=client_info, ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.shopping.merchant.lfp_v1beta.LfpSaleServiceAsyncClient`.", + extra={ + "serviceName": "google.shopping.merchant.lfp.v1beta.LfpSaleService", + "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.lfp.v1beta.LfpSaleService", + "credentialsType": None, + }, + ) + async def insert_lfp_sale( self, request: Optional[Union[lfpsale.InsertLfpSaleRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> lfpsale.LfpSale: r"""Inserts a ``LfpSale`` for the given merchant. @@ -312,8 +344,10 @@ async def sample_insert_lfp_sale(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_lfp_v1beta.types.LfpSale: diff --git a/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/client.py b/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/client.py index 8d9680438f32..ffc314249a51 100644 --- a/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/client.py +++ b/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import os import re from typing import ( @@ -48,6 +49,15 @@ 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 timestamp_pb2 # type: ignore from google.shopping.type.types import types @@ -578,6 +588,10 @@ def __init__( # 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( @@ -643,13 +657,36 @@ def __init__( 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.lfp_v1beta.LfpSaleServiceClient`.", + extra={ + "serviceName": "google.shopping.merchant.lfp.v1beta.LfpSaleService", + "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.lfp.v1beta.LfpSaleService", + "credentialsType": None, + }, + ) + def insert_lfp_sale( self, request: Optional[Union[lfpsale.InsertLfpSaleRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> lfpsale.LfpSale: r"""Inserts a ``LfpSale`` for the given merchant. @@ -696,8 +733,10 @@ def sample_insert_lfp_sale(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_lfp_v1beta.types.LfpSale: diff --git a/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/grpc.py b/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/grpc.py index c2b62f09e328..acd05e27962d 100644 --- a/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/grpc.py +++ b/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/grpc.py @@ -13,6 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import json +import logging as std_logging +import pickle from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -20,12 +23,90 @@ 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_lfp_v1beta.types import lfpsale from .base import DEFAULT_CLIENT_INFO, LfpSaleServiceTransport +try: + from google.api_core import client_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.lfp.v1beta.LfpSaleService", + "rpcName": 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.lfp.v1beta.LfpSaleService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + class LfpSaleServiceGrpcTransport(LfpSaleServiceTransport): """gRPC backend transport for LfpSaleService. @@ -181,7 +262,12 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -255,7 +341,7 @@ def insert_lfp_sale( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "insert_lfp_sale" not in self._stubs: - self._stubs["insert_lfp_sale"] = self.grpc_channel.unary_unary( + self._stubs["insert_lfp_sale"] = self._logged_channel.unary_unary( "/google.shopping.merchant.lfp.v1beta.LfpSaleService/InsertLfpSale", request_serializer=lfpsale.InsertLfpSaleRequest.serialize, response_deserializer=lfpsale.LfpSale.deserialize, @@ -263,7 +349,7 @@ def insert_lfp_sale( return self._stubs["insert_lfp_sale"] def close(self): - self.grpc_channel.close() + self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/grpc_asyncio.py index f8df8912c3a0..7b17a78c8367 100644 --- a/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/grpc_asyncio.py @@ -14,6 +14,9 @@ # limitations under the License. # import inspect +import json +import logging as std_logging +import pickle from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -22,14 +25,93 @@ 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 from grpc.experimental import aio # type: ignore +import proto # type: ignore from google.shopping.merchant_lfp_v1beta.types import lfpsale from .base import DEFAULT_CLIENT_INFO, LfpSaleServiceTransport from .grpc import LfpSaleServiceGrpcTransport +try: + from google.api_core import client_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.lfp.v1beta.LfpSaleService", + "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.lfp.v1beta.LfpSaleService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + class LfpSaleServiceGrpcAsyncIOTransport(LfpSaleServiceTransport): """gRPC AsyncIO backend transport for LfpSaleService. @@ -228,10 +310,13 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -263,7 +348,7 @@ def insert_lfp_sale( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "insert_lfp_sale" not in self._stubs: - self._stubs["insert_lfp_sale"] = self.grpc_channel.unary_unary( + self._stubs["insert_lfp_sale"] = self._logged_channel.unary_unary( "/google.shopping.merchant.lfp.v1beta.LfpSaleService/InsertLfpSale", request_serializer=lfpsale.InsertLfpSaleRequest.serialize, response_deserializer=lfpsale.LfpSale.deserialize, @@ -286,7 +371,7 @@ def _wrap_method(self, func, *args, **kwargs): return gapic_v1.method_async.wrap_method(func, *args, **kwargs) def close(self): - return self.grpc_channel.close() + return self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/rest.py b/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/rest.py index e0078cda11d2..e80adff4996a 100644 --- a/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/rest.py +++ b/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/transports/rest.py @@ -13,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import dataclasses import json # type: ignore +import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings @@ -37,6 +37,14 @@ 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, @@ -75,8 +83,10 @@ def post_insert_lfp_sale(self, response): """ def pre_insert_lfp_sale( - self, request: lfpsale.InsertLfpSaleRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[lfpsale.InsertLfpSaleRequest, Sequence[Tuple[str, str]]]: + self, + request: lfpsale.InsertLfpSaleRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[lfpsale.InsertLfpSaleRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for insert_lfp_sale Override in a subclass to manipulate the request or metadata @@ -217,7 +227,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> lfpsale.LfpSale: r"""Call the insert lfp sale method over HTTP. @@ -228,8 +238,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.lfpsale.LfpSale: @@ -239,6 +251,7 @@ def __call__( http_options = ( _BaseLfpSaleServiceRestTransport._BaseInsertLfpSale._get_http_options() ) + request, metadata = self._interceptor.pre_insert_lfp_sale(request, metadata) transcoded_request = _BaseLfpSaleServiceRestTransport._BaseInsertLfpSale._get_transcoded_request( http_options, request @@ -253,6 +266,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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.lfp_v1beta.LfpSaleServiceClient.InsertLfpSale", + extra={ + "serviceName": "google.shopping.merchant.lfp.v1beta.LfpSaleService", + "rpcName": "InsertLfpSale", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = LfpSaleServiceRestTransport._InsertLfpSale._get_response( self._host, @@ -274,7 +314,29 @@ def __call__( pb_resp = lfpsale.LfpSale.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_insert_lfp_sale(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = lfpsale.LfpSale.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.lfp_v1beta.LfpSaleServiceClient.insert_lfp_sale", + extra={ + "serviceName": "google.shopping.merchant.lfp.v1beta.LfpSaleService", + "rpcName": "InsertLfpSale", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp @property diff --git a/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/async_client.py b/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/async_client.py index 5dce7e0b8308..dec2590e5004 100644 --- a/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/async_client.py +++ b/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/async_client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import re from typing import ( Callable, @@ -49,6 +50,15 @@ from .transports.base import DEFAULT_CLIENT_INFO, LfpStoreServiceTransport from .transports.grpc_asyncio import LfpStoreServiceGrpcAsyncIOTransport +try: + from google.api_core import client_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 LfpStoreServiceAsyncClient: """Service for a `LFP @@ -259,6 +269,28 @@ def __init__( client_info=client_info, ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.shopping.merchant.lfp_v1beta.LfpStoreServiceAsyncClient`.", + extra={ + "serviceName": "google.shopping.merchant.lfp.v1beta.LfpStoreService", + "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.lfp.v1beta.LfpStoreService", + "credentialsType": None, + }, + ) + async def get_lfp_store( self, request: Optional[Union[lfpstore.GetLfpStoreRequest, dict]] = None, @@ -266,7 +298,7 @@ async def get_lfp_store( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> lfpstore.LfpStore: r"""Retrieves information about a store. @@ -309,8 +341,10 @@ async def sample_get_lfp_store(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_lfp_v1beta.types.LfpStore: @@ -377,7 +411,7 @@ async def insert_lfp_store( lfp_store: Optional[lfpstore.LfpStore] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> lfpstore.LfpStore: r"""Inserts a store for the target merchant. If the store with the same store code already exists, it will be @@ -434,8 +468,10 @@ async def sample_insert_lfp_store(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_lfp_v1beta.types.LfpStore: @@ -503,7 +539,7 @@ async def delete_lfp_store( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: r"""Deletes a store for a target merchant. @@ -545,8 +581,10 @@ async def sample_delete_lfp_store(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 @@ -598,7 +636,7 @@ async def list_lfp_stores( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListLfpStoresAsyncPager: r"""Lists the stores of the target merchant, specified by the filter in ``ListLfpStoresRequest``. @@ -645,8 +683,10 @@ async def sample_list_lfp_stores(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_lfp_v1beta.services.lfp_store_service.pagers.ListLfpStoresAsyncPager: diff --git a/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/client.py b/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/client.py index 215a690fa986..8cfbe2326013 100644 --- a/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/client.py +++ b/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import os import re from typing import ( @@ -48,6 +49,15 @@ 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_lfp_v1beta.services.lfp_store_service import pagers from google.shopping.merchant_lfp_v1beta.types import lfpstore @@ -583,6 +593,10 @@ def __init__( # 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( @@ -648,6 +662,29 @@ def __init__( 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.lfp_v1beta.LfpStoreServiceClient`.", + extra={ + "serviceName": "google.shopping.merchant.lfp.v1beta.LfpStoreService", + "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.lfp.v1beta.LfpStoreService", + "credentialsType": None, + }, + ) + def get_lfp_store( self, request: Optional[Union[lfpstore.GetLfpStoreRequest, dict]] = None, @@ -655,7 +692,7 @@ def get_lfp_store( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> lfpstore.LfpStore: r"""Retrieves information about a store. @@ -698,8 +735,10 @@ def sample_get_lfp_store(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_lfp_v1beta.types.LfpStore: @@ -763,7 +802,7 @@ def insert_lfp_store( lfp_store: Optional[lfpstore.LfpStore] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> lfpstore.LfpStore: r"""Inserts a store for the target merchant. If the store with the same store code already exists, it will be @@ -820,8 +859,10 @@ def sample_insert_lfp_store(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_lfp_v1beta.types.LfpStore: @@ -886,7 +927,7 @@ def delete_lfp_store( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: r"""Deletes a store for a target merchant. @@ -928,8 +969,10 @@ def sample_delete_lfp_store(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 @@ -978,7 +1021,7 @@ def list_lfp_stores( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListLfpStoresPager: r"""Lists the stores of the target merchant, specified by the filter in ``ListLfpStoresRequest``. @@ -1025,8 +1068,10 @@ def sample_list_lfp_stores(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_lfp_v1beta.services.lfp_store_service.pagers.ListLfpStoresPager: diff --git a/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/pagers.py b/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/pagers.py index c44b51d871ce..b0ab17b0610d 100644 --- a/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/pagers.py +++ b/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/pagers.py @@ -67,7 +67,7 @@ def __init__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiate the pager. @@ -81,8 +81,10 @@ def __init__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 = lfpstore.ListLfpStoresRequest(request) @@ -141,7 +143,7 @@ def __init__( *, retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiates the pager. @@ -155,8 +157,10 @@ def __init__( 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 = lfpstore.ListLfpStoresRequest(request) diff --git a/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/grpc.py b/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/grpc.py index 5ca5fc03a6dc..4a92a3d5663b 100644 --- a/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/grpc.py +++ b/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/grpc.py @@ -13,6 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import json +import logging as std_logging +import pickle from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -21,12 +24,90 @@ 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.shopping.merchant_lfp_v1beta.types import lfpstore from .base import DEFAULT_CLIENT_INFO, LfpStoreServiceTransport +try: + from google.api_core import client_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.lfp.v1beta.LfpStoreService", + "rpcName": 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.lfp.v1beta.LfpStoreService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + class LfpStoreServiceGrpcTransport(LfpStoreServiceTransport): """gRPC backend transport for LfpStoreService. @@ -182,7 +263,12 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -256,7 +342,7 @@ def get_lfp_store( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_lfp_store" not in self._stubs: - self._stubs["get_lfp_store"] = self.grpc_channel.unary_unary( + self._stubs["get_lfp_store"] = self._logged_channel.unary_unary( "/google.shopping.merchant.lfp.v1beta.LfpStoreService/GetLfpStore", request_serializer=lfpstore.GetLfpStoreRequest.serialize, response_deserializer=lfpstore.LfpStore.deserialize, @@ -284,7 +370,7 @@ def insert_lfp_store( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "insert_lfp_store" not in self._stubs: - self._stubs["insert_lfp_store"] = self.grpc_channel.unary_unary( + self._stubs["insert_lfp_store"] = self._logged_channel.unary_unary( "/google.shopping.merchant.lfp.v1beta.LfpStoreService/InsertLfpStore", request_serializer=lfpstore.InsertLfpStoreRequest.serialize, response_deserializer=lfpstore.LfpStore.deserialize, @@ -310,7 +396,7 @@ def delete_lfp_store( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "delete_lfp_store" not in self._stubs: - self._stubs["delete_lfp_store"] = self.grpc_channel.unary_unary( + self._stubs["delete_lfp_store"] = self._logged_channel.unary_unary( "/google.shopping.merchant.lfp.v1beta.LfpStoreService/DeleteLfpStore", request_serializer=lfpstore.DeleteLfpStoreRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -337,7 +423,7 @@ def list_lfp_stores( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_lfp_stores" not in self._stubs: - self._stubs["list_lfp_stores"] = self.grpc_channel.unary_unary( + self._stubs["list_lfp_stores"] = self._logged_channel.unary_unary( "/google.shopping.merchant.lfp.v1beta.LfpStoreService/ListLfpStores", request_serializer=lfpstore.ListLfpStoresRequest.serialize, response_deserializer=lfpstore.ListLfpStoresResponse.deserialize, @@ -345,7 +431,7 @@ def list_lfp_stores( return self._stubs["list_lfp_stores"] def close(self): - self.grpc_channel.close() + self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/grpc_asyncio.py index f15ccebf5497..0911923e5dab 100644 --- a/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/grpc_asyncio.py @@ -14,6 +14,9 @@ # limitations under the License. # import inspect +import json +import logging as std_logging +import pickle from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -23,14 +26,93 @@ 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 from grpc.experimental import aio # type: ignore +import proto # type: ignore from google.shopping.merchant_lfp_v1beta.types import lfpstore from .base import DEFAULT_CLIENT_INFO, LfpStoreServiceTransport from .grpc import LfpStoreServiceGrpcTransport +try: + from google.api_core import client_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.lfp.v1beta.LfpStoreService", + "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.lfp.v1beta.LfpStoreService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + class LfpStoreServiceGrpcAsyncIOTransport(LfpStoreServiceTransport): """gRPC AsyncIO backend transport for LfpStoreService. @@ -229,10 +311,13 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -264,7 +349,7 @@ def get_lfp_store( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_lfp_store" not in self._stubs: - self._stubs["get_lfp_store"] = self.grpc_channel.unary_unary( + self._stubs["get_lfp_store"] = self._logged_channel.unary_unary( "/google.shopping.merchant.lfp.v1beta.LfpStoreService/GetLfpStore", request_serializer=lfpstore.GetLfpStoreRequest.serialize, response_deserializer=lfpstore.LfpStore.deserialize, @@ -292,7 +377,7 @@ def insert_lfp_store( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "insert_lfp_store" not in self._stubs: - self._stubs["insert_lfp_store"] = self.grpc_channel.unary_unary( + self._stubs["insert_lfp_store"] = self._logged_channel.unary_unary( "/google.shopping.merchant.lfp.v1beta.LfpStoreService/InsertLfpStore", request_serializer=lfpstore.InsertLfpStoreRequest.serialize, response_deserializer=lfpstore.LfpStore.deserialize, @@ -318,7 +403,7 @@ def delete_lfp_store( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "delete_lfp_store" not in self._stubs: - self._stubs["delete_lfp_store"] = self.grpc_channel.unary_unary( + self._stubs["delete_lfp_store"] = self._logged_channel.unary_unary( "/google.shopping.merchant.lfp.v1beta.LfpStoreService/DeleteLfpStore", request_serializer=lfpstore.DeleteLfpStoreRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -347,7 +432,7 @@ def list_lfp_stores( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_lfp_stores" not in self._stubs: - self._stubs["list_lfp_stores"] = self.grpc_channel.unary_unary( + self._stubs["list_lfp_stores"] = self._logged_channel.unary_unary( "/google.shopping.merchant.lfp.v1beta.LfpStoreService/ListLfpStores", request_serializer=lfpstore.ListLfpStoresRequest.serialize, response_deserializer=lfpstore.ListLfpStoresResponse.deserialize, @@ -385,7 +470,7 @@ def _wrap_method(self, func, *args, **kwargs): return gapic_v1.method_async.wrap_method(func, *args, **kwargs) def close(self): - return self.grpc_channel.close() + return self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/rest.py b/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/rest.py index 7a07da90e2c7..c9ef2b40314b 100644 --- a/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/rest.py +++ b/packages/google-shopping-merchant-lfp/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/transports/rest.py @@ -13,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import dataclasses import json # type: ignore +import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings @@ -38,6 +38,14 @@ 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, @@ -98,8 +106,8 @@ def post_list_lfp_stores(self, response): def pre_delete_lfp_store( self, request: lfpstore.DeleteLfpStoreRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[lfpstore.DeleteLfpStoreRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[lfpstore.DeleteLfpStoreRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for delete_lfp_store Override in a subclass to manipulate the request or metadata @@ -108,8 +116,10 @@ def pre_delete_lfp_store( return request, metadata def pre_get_lfp_store( - self, request: lfpstore.GetLfpStoreRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[lfpstore.GetLfpStoreRequest, Sequence[Tuple[str, str]]]: + self, + request: lfpstore.GetLfpStoreRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[lfpstore.GetLfpStoreRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for get_lfp_store Override in a subclass to manipulate the request or metadata @@ -129,8 +139,8 @@ def post_get_lfp_store(self, response: lfpstore.LfpStore) -> lfpstore.LfpStore: def pre_insert_lfp_store( self, request: lfpstore.InsertLfpStoreRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[lfpstore.InsertLfpStoreRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[lfpstore.InsertLfpStoreRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for insert_lfp_store Override in a subclass to manipulate the request or metadata @@ -150,8 +160,8 @@ def post_insert_lfp_store(self, response: lfpstore.LfpStore) -> lfpstore.LfpStor def pre_list_lfp_stores( self, request: lfpstore.ListLfpStoresRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[lfpstore.ListLfpStoresRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[lfpstore.ListLfpStoresRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for list_lfp_stores Override in a subclass to manipulate the request or metadata @@ -293,7 +303,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ): r"""Call the delete lfp store method over HTTP. @@ -304,13 +314,16 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 = ( _BaseLfpStoreServiceRestTransport._BaseDeleteLfpStore._get_http_options() ) + request, metadata = self._interceptor.pre_delete_lfp_store( request, metadata ) @@ -323,6 +336,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + 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.lfp_v1beta.LfpStoreServiceClient.DeleteLfpStore", + extra={ + "serviceName": "google.shopping.merchant.lfp.v1beta.LfpStoreService", + "rpcName": "DeleteLfpStore", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = LfpStoreServiceRestTransport._DeleteLfpStore._get_response( self._host, @@ -372,7 +412,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> lfpstore.LfpStore: r"""Call the get lfp store method over HTTP. @@ -382,8 +422,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.lfpstore.LfpStore: @@ -400,6 +442,7 @@ def __call__( http_options = ( _BaseLfpStoreServiceRestTransport._BaseGetLfpStore._get_http_options() ) + request, metadata = self._interceptor.pre_get_lfp_store(request, metadata) transcoded_request = _BaseLfpStoreServiceRestTransport._BaseGetLfpStore._get_transcoded_request( http_options, request @@ -410,6 +453,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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.lfp_v1beta.LfpStoreServiceClient.GetLfpStore", + extra={ + "serviceName": "google.shopping.merchant.lfp.v1beta.LfpStoreService", + "rpcName": "GetLfpStore", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = LfpStoreServiceRestTransport._GetLfpStore._get_response( self._host, @@ -430,7 +500,29 @@ def __call__( pb_resp = lfpstore.LfpStore.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_lfp_store(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = lfpstore.LfpStore.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.lfp_v1beta.LfpStoreServiceClient.get_lfp_store", + extra={ + "serviceName": "google.shopping.merchant.lfp.v1beta.LfpStoreService", + "rpcName": "GetLfpStore", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _InsertLfpStore( @@ -468,7 +560,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> lfpstore.LfpStore: r"""Call the insert lfp store method over HTTP. @@ -479,8 +571,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.lfpstore.LfpStore: @@ -497,6 +591,7 @@ def __call__( http_options = ( _BaseLfpStoreServiceRestTransport._BaseInsertLfpStore._get_http_options() ) + request, metadata = self._interceptor.pre_insert_lfp_store( request, metadata ) @@ -513,6 +608,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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.lfp_v1beta.LfpStoreServiceClient.InsertLfpStore", + extra={ + "serviceName": "google.shopping.merchant.lfp.v1beta.LfpStoreService", + "rpcName": "InsertLfpStore", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = LfpStoreServiceRestTransport._InsertLfpStore._get_response( self._host, @@ -534,7 +656,29 @@ def __call__( pb_resp = lfpstore.LfpStore.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_insert_lfp_store(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = lfpstore.LfpStore.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.lfp_v1beta.LfpStoreServiceClient.insert_lfp_store", + extra={ + "serviceName": "google.shopping.merchant.lfp.v1beta.LfpStoreService", + "rpcName": "InsertLfpStore", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _ListLfpStores( @@ -571,7 +715,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> lfpstore.ListLfpStoresResponse: r"""Call the list lfp stores method over HTTP. @@ -582,8 +726,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.lfpstore.ListLfpStoresResponse: @@ -595,6 +741,7 @@ def __call__( http_options = ( _BaseLfpStoreServiceRestTransport._BaseListLfpStores._get_http_options() ) + request, metadata = self._interceptor.pre_list_lfp_stores(request, metadata) transcoded_request = _BaseLfpStoreServiceRestTransport._BaseListLfpStores._get_transcoded_request( http_options, request @@ -605,6 +752,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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.lfp_v1beta.LfpStoreServiceClient.ListLfpStores", + extra={ + "serviceName": "google.shopping.merchant.lfp.v1beta.LfpStoreService", + "rpcName": "ListLfpStores", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = LfpStoreServiceRestTransport._ListLfpStores._get_response( self._host, @@ -625,7 +799,29 @@ def __call__( pb_resp = lfpstore.ListLfpStoresResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_lfp_stores(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = lfpstore.ListLfpStoresResponse.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.lfp_v1beta.LfpStoreServiceClient.list_lfp_stores", + extra={ + "serviceName": "google.shopping.merchant.lfp.v1beta.LfpStoreService", + "rpcName": "ListLfpStores", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp @property diff --git a/packages/google-shopping-merchant-lfp/samples/generated_samples/snippet_metadata_google.shopping.merchant.lfp.v1beta.json b/packages/google-shopping-merchant-lfp/samples/generated_samples/snippet_metadata_google.shopping.merchant.lfp.v1beta.json index e54573affeba..c88051dded42 100644 --- a/packages/google-shopping-merchant-lfp/samples/generated_samples/snippet_metadata_google.shopping.merchant.lfp.v1beta.json +++ b/packages/google-shopping-merchant-lfp/samples/generated_samples/snippet_metadata_google.shopping.merchant.lfp.v1beta.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-shopping-merchant-lfp", - "version": "0.1.5" + "version": "0.1.0" }, "snippets": [ { @@ -43,7 +43,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_lfp_v1beta.types.LfpInventory", @@ -119,7 +119,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_lfp_v1beta.types.LfpInventory", @@ -196,7 +196,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_lfp_v1beta.types.LfpSale", @@ -272,7 +272,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_lfp_v1beta.types.LfpSale", @@ -353,7 +353,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "shortName": "delete_lfp_store" @@ -430,7 +430,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "shortName": "delete_lfp_store" @@ -508,7 +508,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_lfp_v1beta.types.LfpStore", @@ -588,7 +588,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_lfp_v1beta.types.LfpStore", @@ -673,7 +673,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_lfp_v1beta.types.LfpStore", @@ -757,7 +757,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_lfp_v1beta.types.LfpStore", @@ -838,7 +838,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_lfp_v1beta.services.lfp_store_service.pagers.ListLfpStoresAsyncPager", @@ -918,7 +918,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_lfp_v1beta.services.lfp_store_service.pagers.ListLfpStoresPager", diff --git a/packages/google-shopping-merchant-lfp/tests/unit/gapic/merchant_lfp_v1beta/test_lfp_inventory_service.py b/packages/google-shopping-merchant-lfp/tests/unit/gapic/merchant_lfp_v1beta/test_lfp_inventory_service.py index 61cd7852171e..b5cd41e83d0e 100644 --- a/packages/google-shopping-merchant-lfp/tests/unit/gapic/merchant_lfp_v1beta/test_lfp_inventory_service.py +++ b/packages/google-shopping-merchant-lfp/tests/unit/gapic/merchant_lfp_v1beta/test_lfp_inventory_service.py @@ -1527,6 +1527,7 @@ def test_insert_lfp_inventory_rest_required_fields( response_value._content = json_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_lfp_inventory(request) @@ -1763,6 +1764,7 @@ def test_insert_lfp_inventory_rest_bad_request( 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_lfp_inventory(request) @@ -1892,6 +1894,7 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_lfp_inventory(request) # Establish that the response is the type that we expect. @@ -1943,6 +1946,7 @@ def test_insert_lfp_inventory_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = lfpinventory.LfpInventory.to_json(lfpinventory.LfpInventory()) req.return_value.content = return_value diff --git a/packages/google-shopping-merchant-lfp/tests/unit/gapic/merchant_lfp_v1beta/test_lfp_sale_service.py b/packages/google-shopping-merchant-lfp/tests/unit/gapic/merchant_lfp_v1beta/test_lfp_sale_service.py index 8f7272454743..4e59cae51f72 100644 --- a/packages/google-shopping-merchant-lfp/tests/unit/gapic/merchant_lfp_v1beta/test_lfp_sale_service.py +++ b/packages/google-shopping-merchant-lfp/tests/unit/gapic/merchant_lfp_v1beta/test_lfp_sale_service.py @@ -1443,6 +1443,7 @@ def test_insert_lfp_sale_rest_required_fields( response_value._content = json_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_lfp_sale(request) @@ -1671,6 +1672,7 @@ def test_insert_lfp_sale_rest_bad_request(request_type=lfpsale.InsertLfpSaleRequ 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_lfp_sale(request) @@ -1796,6 +1798,7 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_lfp_sale(request) # Establish that the response is the type that we expect. @@ -1843,6 +1846,7 @@ def test_insert_lfp_sale_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 = lfpsale.LfpSale.to_json(lfpsale.LfpSale()) req.return_value.content = return_value diff --git a/packages/google-shopping-merchant-lfp/tests/unit/gapic/merchant_lfp_v1beta/test_lfp_store_service.py b/packages/google-shopping-merchant-lfp/tests/unit/gapic/merchant_lfp_v1beta/test_lfp_store_service.py index 4942ba55ec06..69f3e26da8b8 100644 --- a/packages/google-shopping-merchant-lfp/tests/unit/gapic/merchant_lfp_v1beta/test_lfp_store_service.py +++ b/packages/google-shopping-merchant-lfp/tests/unit/gapic/merchant_lfp_v1beta/test_lfp_store_service.py @@ -2758,6 +2758,7 @@ def test_get_lfp_store_rest_required_fields(request_type=lfpstore.GetLfpStoreReq response_value._content = json_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_lfp_store(request) @@ -2803,6 +2804,7 @@ def test_get_lfp_store_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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_lfp_store(**mock_args) @@ -2936,6 +2938,7 @@ def test_insert_lfp_store_rest_required_fields( response_value._content = json_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_lfp_store(request) @@ -2990,6 +2993,7 @@ def test_insert_lfp_store_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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.insert_lfp_store(**mock_args) @@ -3121,6 +3125,7 @@ def test_delete_lfp_store_rest_required_fields( response_value._content = json_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_lfp_store(request) @@ -3164,6 +3169,7 @@ def test_delete_lfp_store_rest_flattened(): 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_lfp_store(**mock_args) @@ -3309,6 +3315,7 @@ def test_list_lfp_stores_rest_required_fields( response_value._content = json_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_lfp_stores(request) @@ -3374,6 +3381,7 @@ def test_list_lfp_stores_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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_lfp_stores(**mock_args) @@ -3817,6 +3825,7 @@ def test_get_lfp_store_rest_bad_request(request_type=lfpstore.GetLfpStoreRequest 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_lfp_store(request) @@ -3862,6 +3871,7 @@ def test_get_lfp_store_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_lfp_store(request) # Establish that the response is the type that we expect. @@ -3913,6 +3923,7 @@ def test_get_lfp_store_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 = lfpstore.LfpStore.to_json(lfpstore.LfpStore()) req.return_value.content = return_value @@ -3955,6 +3966,7 @@ def test_insert_lfp_store_rest_bad_request(request_type=lfpstore.InsertLfpStoreR 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_lfp_store(request) @@ -4080,6 +4092,7 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_lfp_store(request) # Establish that the response is the type that we expect. @@ -4131,6 +4144,7 @@ def test_insert_lfp_store_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 = lfpstore.LfpStore.to_json(lfpstore.LfpStore()) req.return_value.content = return_value @@ -4173,6 +4187,7 @@ def test_delete_lfp_store_rest_bad_request(request_type=lfpstore.DeleteLfpStoreR 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_lfp_store(request) @@ -4203,6 +4218,7 @@ def test_delete_lfp_store_rest_call_success(request_type): 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_lfp_store(request) # Establish that the response is the type that we expect. @@ -4237,6 +4253,7 @@ def test_delete_lfp_store_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"} request = lfpstore.DeleteLfpStoreRequest() metadata = [ @@ -4275,6 +4292,7 @@ def test_list_lfp_stores_rest_bad_request(request_type=lfpstore.ListLfpStoresReq 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_lfp_stores(request) @@ -4310,6 +4328,7 @@ def test_list_lfp_stores_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_lfp_stores(request) # Establish that the response is the type that we expect. @@ -4348,6 +4367,7 @@ def test_list_lfp_stores_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 = lfpstore.ListLfpStoresResponse.to_json( lfpstore.ListLfpStoresResponse() ) diff --git a/packages/google-shopping-merchant-notifications/google/shopping/merchant_notifications/gapic_version.py b/packages/google-shopping-merchant-notifications/google/shopping/merchant_notifications/gapic_version.py index 937ede8823ef..558c8aab67c5 100644 --- a/packages/google-shopping-merchant-notifications/google/shopping/merchant_notifications/gapic_version.py +++ b/packages/google-shopping-merchant-notifications/google/shopping/merchant_notifications/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.4" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-shopping-merchant-notifications/google/shopping/merchant_notifications_v1beta/gapic_version.py b/packages/google-shopping-merchant-notifications/google/shopping/merchant_notifications_v1beta/gapic_version.py index 937ede8823ef..558c8aab67c5 100644 --- a/packages/google-shopping-merchant-notifications/google/shopping/merchant_notifications_v1beta/gapic_version.py +++ b/packages/google-shopping-merchant-notifications/google/shopping/merchant_notifications_v1beta/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.4" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-shopping-merchant-notifications/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/async_client.py b/packages/google-shopping-merchant-notifications/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/async_client.py index f9dd01b3f3df..3ef11b63724d 100644 --- a/packages/google-shopping-merchant-notifications/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/async_client.py +++ b/packages/google-shopping-merchant-notifications/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/async_client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import re from typing import ( Callable, @@ -55,6 +56,15 @@ from .transports.base import DEFAULT_CLIENT_INFO, NotificationsApiServiceTransport from .transports.grpc_asyncio import NotificationsApiServiceGrpcAsyncIOTransport +try: + from google.api_core import client_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 NotificationsApiServiceAsyncClient: """Service to manage notification subscriptions for merchants""" @@ -274,6 +284,28 @@ def __init__( client_info=client_info, ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.shopping.merchant.notifications_v1beta.NotificationsApiServiceAsyncClient`.", + extra={ + "serviceName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", + "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.notifications.v1beta.NotificationsApiService", + "credentialsType": None, + }, + ) + async def get_notification_subscription( self, request: Optional[ @@ -283,7 +315,7 @@ async def get_notification_subscription( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> notificationsapi.NotificationSubscription: r"""Gets notification subscriptions for an account. @@ -325,8 +357,10 @@ async def sample_get_notification_subscription(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_notifications_v1beta.types.NotificationSubscription: @@ -393,7 +427,7 @@ async def create_notification_subscription( ] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> notificationsapi.NotificationSubscription: r"""Creates a notification subscription for a merchant. We will allow the following types of notification @@ -466,8 +500,10 @@ async def sample_create_notification_subscription(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_notifications_v1beta.types.NotificationSubscription: @@ -538,7 +574,7 @@ async def update_notification_subscription( 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, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> notificationsapi.NotificationSubscription: r"""Updates an existing notification subscription for a merchant. @@ -592,8 +628,10 @@ async def sample_update_notification_subscription(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_notifications_v1beta.types.NotificationSubscription: @@ -668,7 +706,7 @@ async def delete_notification_subscription( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: r"""Deletes a notification subscription for a merchant. @@ -709,8 +747,10 @@ async def sample_delete_notification_subscription(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 @@ -766,7 +806,7 @@ async def list_notification_subscriptions( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListNotificationSubscriptionsAsyncPager: r"""Gets all the notification subscriptions for a merchant. @@ -812,8 +852,10 @@ async def sample_list_notification_subscriptions(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_notifications_v1beta.services.notifications_api_service.pagers.ListNotificationSubscriptionsAsyncPager: diff --git a/packages/google-shopping-merchant-notifications/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/client.py b/packages/google-shopping-merchant-notifications/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/client.py index 17c59d6fc6a0..a19c1a2b6a62 100644 --- a/packages/google-shopping-merchant-notifications/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/client.py +++ b/packages/google-shopping-merchant-notifications/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import os import re from typing import ( @@ -50,6 +51,15 @@ 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_notifications_v1beta.services.notifications_api_service import ( @@ -590,6 +600,10 @@ def __init__( # 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( @@ -656,6 +670,29 @@ def __init__( 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.notifications_v1beta.NotificationsApiServiceClient`.", + extra={ + "serviceName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", + "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.notifications.v1beta.NotificationsApiService", + "credentialsType": None, + }, + ) + def get_notification_subscription( self, request: Optional[ @@ -665,7 +702,7 @@ def get_notification_subscription( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> notificationsapi.NotificationSubscription: r"""Gets notification subscriptions for an account. @@ -707,8 +744,10 @@ def sample_get_notification_subscription(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_notifications_v1beta.types.NotificationSubscription: @@ -774,7 +813,7 @@ def create_notification_subscription( ] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> notificationsapi.NotificationSubscription: r"""Creates a notification subscription for a merchant. We will allow the following types of notification @@ -847,8 +886,10 @@ def sample_create_notification_subscription(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_notifications_v1beta.types.NotificationSubscription: @@ -918,7 +959,7 @@ def update_notification_subscription( 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, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> notificationsapi.NotificationSubscription: r"""Updates an existing notification subscription for a merchant. @@ -972,8 +1013,10 @@ def sample_update_notification_subscription(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_notifications_v1beta.types.NotificationSubscription: @@ -1047,7 +1090,7 @@ def delete_notification_subscription( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: r"""Deletes a notification subscription for a merchant. @@ -1088,8 +1131,10 @@ def sample_delete_notification_subscription(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 @@ -1144,7 +1189,7 @@ def list_notification_subscriptions( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListNotificationSubscriptionsPager: r"""Gets all the notification subscriptions for a merchant. @@ -1190,8 +1235,10 @@ def sample_list_notification_subscriptions(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_notifications_v1beta.services.notifications_api_service.pagers.ListNotificationSubscriptionsPager: diff --git a/packages/google-shopping-merchant-notifications/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/pagers.py b/packages/google-shopping-merchant-notifications/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/pagers.py index b7ae9fe7a99c..38db2200e582 100644 --- a/packages/google-shopping-merchant-notifications/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/pagers.py +++ b/packages/google-shopping-merchant-notifications/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/pagers.py @@ -67,7 +67,7 @@ def __init__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiate the pager. @@ -81,8 +81,10 @@ def __init__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 = notificationsapi.ListNotificationSubscriptionsRequest(request) @@ -143,7 +145,7 @@ def __init__( *, retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiates the pager. @@ -157,8 +159,10 @@ def __init__( 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 = notificationsapi.ListNotificationSubscriptionsRequest(request) diff --git a/packages/google-shopping-merchant-notifications/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/grpc.py b/packages/google-shopping-merchant-notifications/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/grpc.py index 4dbf53f3f4a2..382cdae4c6d0 100644 --- a/packages/google-shopping-merchant-notifications/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/grpc.py +++ b/packages/google-shopping-merchant-notifications/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/grpc.py @@ -13,6 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import json +import logging as std_logging +import pickle from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -21,12 +24,90 @@ 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.shopping.merchant_notifications_v1beta.types import notificationsapi from .base import DEFAULT_CLIENT_INFO, NotificationsApiServiceTransport +try: + from google.api_core import client_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.notifications.v1beta.NotificationsApiService", + "rpcName": 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.notifications.v1beta.NotificationsApiService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + class NotificationsApiServiceGrpcTransport(NotificationsApiServiceTransport): """gRPC backend transport for NotificationsApiService. @@ -180,7 +261,12 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -259,7 +345,7 @@ def get_notification_subscription( if "get_notification_subscription" not in self._stubs: self._stubs[ "get_notification_subscription" - ] = self.grpc_channel.unary_unary( + ] = self._logged_channel.unary_unary( "/google.shopping.merchant.notifications.v1beta.NotificationsApiService/GetNotificationSubscription", request_serializer=notificationsapi.GetNotificationSubscriptionRequest.serialize, response_deserializer=notificationsapi.NotificationSubscription.deserialize, @@ -308,7 +394,7 @@ def create_notification_subscription( if "create_notification_subscription" not in self._stubs: self._stubs[ "create_notification_subscription" - ] = self.grpc_channel.unary_unary( + ] = self._logged_channel.unary_unary( "/google.shopping.merchant.notifications.v1beta.NotificationsApiService/CreateNotificationSubscription", request_serializer=notificationsapi.CreateNotificationSubscriptionRequest.serialize, response_deserializer=notificationsapi.NotificationSubscription.deserialize, @@ -341,7 +427,7 @@ def update_notification_subscription( if "update_notification_subscription" not in self._stubs: self._stubs[ "update_notification_subscription" - ] = self.grpc_channel.unary_unary( + ] = self._logged_channel.unary_unary( "/google.shopping.merchant.notifications.v1beta.NotificationsApiService/UpdateNotificationSubscription", request_serializer=notificationsapi.UpdateNotificationSubscriptionRequest.serialize, response_deserializer=notificationsapi.NotificationSubscription.deserialize, @@ -372,7 +458,7 @@ def delete_notification_subscription( if "delete_notification_subscription" not in self._stubs: self._stubs[ "delete_notification_subscription" - ] = self.grpc_channel.unary_unary( + ] = self._logged_channel.unary_unary( "/google.shopping.merchant.notifications.v1beta.NotificationsApiService/DeleteNotificationSubscription", request_serializer=notificationsapi.DeleteNotificationSubscriptionRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -405,7 +491,7 @@ def list_notification_subscriptions( if "list_notification_subscriptions" not in self._stubs: self._stubs[ "list_notification_subscriptions" - ] = self.grpc_channel.unary_unary( + ] = self._logged_channel.unary_unary( "/google.shopping.merchant.notifications.v1beta.NotificationsApiService/ListNotificationSubscriptions", request_serializer=notificationsapi.ListNotificationSubscriptionsRequest.serialize, response_deserializer=notificationsapi.ListNotificationSubscriptionsResponse.deserialize, @@ -413,7 +499,7 @@ def list_notification_subscriptions( return self._stubs["list_notification_subscriptions"] def close(self): - self.grpc_channel.close() + self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-notifications/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-notifications/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/grpc_asyncio.py index fce42dccdbf0..141c6502c858 100644 --- a/packages/google-shopping-merchant-notifications/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-notifications/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/grpc_asyncio.py @@ -14,6 +14,9 @@ # limitations under the License. # import inspect +import json +import logging as std_logging +import pickle from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -23,14 +26,93 @@ 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 from grpc.experimental import aio # type: ignore +import proto # type: ignore from google.shopping.merchant_notifications_v1beta.types import notificationsapi from .base import DEFAULT_CLIENT_INFO, NotificationsApiServiceTransport from .grpc import NotificationsApiServiceGrpcTransport +try: + from google.api_core import client_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.notifications.v1beta.NotificationsApiService", + "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.notifications.v1beta.NotificationsApiService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + class NotificationsApiServiceGrpcAsyncIOTransport(NotificationsApiServiceTransport): """gRPC AsyncIO backend transport for NotificationsApiService. @@ -227,10 +309,13 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -267,7 +352,7 @@ def get_notification_subscription( if "get_notification_subscription" not in self._stubs: self._stubs[ "get_notification_subscription" - ] = self.grpc_channel.unary_unary( + ] = self._logged_channel.unary_unary( "/google.shopping.merchant.notifications.v1beta.NotificationsApiService/GetNotificationSubscription", request_serializer=notificationsapi.GetNotificationSubscriptionRequest.serialize, response_deserializer=notificationsapi.NotificationSubscription.deserialize, @@ -316,7 +401,7 @@ def create_notification_subscription( if "create_notification_subscription" not in self._stubs: self._stubs[ "create_notification_subscription" - ] = self.grpc_channel.unary_unary( + ] = self._logged_channel.unary_unary( "/google.shopping.merchant.notifications.v1beta.NotificationsApiService/CreateNotificationSubscription", request_serializer=notificationsapi.CreateNotificationSubscriptionRequest.serialize, response_deserializer=notificationsapi.NotificationSubscription.deserialize, @@ -349,7 +434,7 @@ def update_notification_subscription( if "update_notification_subscription" not in self._stubs: self._stubs[ "update_notification_subscription" - ] = self.grpc_channel.unary_unary( + ] = self._logged_channel.unary_unary( "/google.shopping.merchant.notifications.v1beta.NotificationsApiService/UpdateNotificationSubscription", request_serializer=notificationsapi.UpdateNotificationSubscriptionRequest.serialize, response_deserializer=notificationsapi.NotificationSubscription.deserialize, @@ -381,7 +466,7 @@ def delete_notification_subscription( if "delete_notification_subscription" not in self._stubs: self._stubs[ "delete_notification_subscription" - ] = self.grpc_channel.unary_unary( + ] = self._logged_channel.unary_unary( "/google.shopping.merchant.notifications.v1beta.NotificationsApiService/DeleteNotificationSubscription", request_serializer=notificationsapi.DeleteNotificationSubscriptionRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -414,7 +499,7 @@ def list_notification_subscriptions( if "list_notification_subscriptions" not in self._stubs: self._stubs[ "list_notification_subscriptions" - ] = self.grpc_channel.unary_unary( + ] = self._logged_channel.unary_unary( "/google.shopping.merchant.notifications.v1beta.NotificationsApiService/ListNotificationSubscriptions", request_serializer=notificationsapi.ListNotificationSubscriptionsRequest.serialize, response_deserializer=notificationsapi.ListNotificationSubscriptionsResponse.deserialize, @@ -457,7 +542,7 @@ def _wrap_method(self, func, *args, **kwargs): return gapic_v1.method_async.wrap_method(func, *args, **kwargs) def close(self): - return self.grpc_channel.close() + return self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-notifications/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/rest.py b/packages/google-shopping-merchant-notifications/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/rest.py index 7c61a8e38280..5eedb5916c07 100644 --- a/packages/google-shopping-merchant-notifications/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/rest.py +++ b/packages/google-shopping-merchant-notifications/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/transports/rest.py @@ -13,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import dataclasses import json # type: ignore +import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings @@ -38,6 +38,14 @@ 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, @@ -106,10 +114,10 @@ def post_update_notification_subscription(self, response): def pre_create_notification_subscription( self, request: notificationsapi.CreateNotificationSubscriptionRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ notificationsapi.CreateNotificationSubscriptionRequest, - Sequence[Tuple[str, str]], + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for create_notification_subscription @@ -132,10 +140,10 @@ def post_create_notification_subscription( def pre_delete_notification_subscription( self, request: notificationsapi.DeleteNotificationSubscriptionRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ notificationsapi.DeleteNotificationSubscriptionRequest, - Sequence[Tuple[str, str]], + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for delete_notification_subscription @@ -147,9 +155,10 @@ def pre_delete_notification_subscription( def pre_get_notification_subscription( self, request: notificationsapi.GetNotificationSubscriptionRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - notificationsapi.GetNotificationSubscriptionRequest, Sequence[Tuple[str, str]] + notificationsapi.GetNotificationSubscriptionRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for get_notification_subscription @@ -172,9 +181,10 @@ def post_get_notification_subscription( def pre_list_notification_subscriptions( self, request: notificationsapi.ListNotificationSubscriptionsRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - notificationsapi.ListNotificationSubscriptionsRequest, Sequence[Tuple[str, str]] + notificationsapi.ListNotificationSubscriptionsRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for list_notification_subscriptions @@ -197,10 +207,10 @@ def post_list_notification_subscriptions( def pre_update_notification_subscription( self, request: notificationsapi.UpdateNotificationSubscriptionRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ notificationsapi.UpdateNotificationSubscriptionRequest, - Sequence[Tuple[str, str]], + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for update_notification_subscription @@ -345,7 +355,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> notificationsapi.NotificationSubscription: r"""Call the create notification subscription method over HTTP. @@ -357,8 +367,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.notificationsapi.NotificationSubscription: @@ -371,6 +383,7 @@ def __call__( http_options = ( _BaseNotificationsApiServiceRestTransport._BaseCreateNotificationSubscription._get_http_options() ) + request, metadata = self._interceptor.pre_create_notification_subscription( request, metadata ) @@ -387,6 +400,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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.notifications_v1beta.NotificationsApiServiceClient.CreateNotificationSubscription", + extra={ + "serviceName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", + "rpcName": "CreateNotificationSubscription", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = NotificationsApiServiceRestTransport._CreateNotificationSubscription._get_response( self._host, @@ -408,7 +448,31 @@ def __call__( pb_resp = notificationsapi.NotificationSubscription.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_notification_subscription(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + notificationsapi.NotificationSubscription.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.notifications_v1beta.NotificationsApiServiceClient.create_notification_subscription", + extra={ + "serviceName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", + "rpcName": "CreateNotificationSubscription", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _DeleteNotificationSubscription( @@ -448,7 +512,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ): r"""Call the delete notification subscription method over HTTP. @@ -460,13 +524,16 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 = ( _BaseNotificationsApiServiceRestTransport._BaseDeleteNotificationSubscription._get_http_options() ) + request, metadata = self._interceptor.pre_delete_notification_subscription( request, metadata ) @@ -479,6 +546,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + 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.notifications_v1beta.NotificationsApiServiceClient.DeleteNotificationSubscription", + extra={ + "serviceName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", + "rpcName": "DeleteNotificationSubscription", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = NotificationsApiServiceRestTransport._DeleteNotificationSubscription._get_response( self._host, @@ -531,7 +625,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> notificationsapi.NotificationSubscription: r"""Call the get notification subscription method over HTTP. @@ -543,8 +637,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.notificationsapi.NotificationSubscription: @@ -557,6 +653,7 @@ def __call__( http_options = ( _BaseNotificationsApiServiceRestTransport._BaseGetNotificationSubscription._get_http_options() ) + request, metadata = self._interceptor.pre_get_notification_subscription( request, metadata ) @@ -569,6 +666,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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.notifications_v1beta.NotificationsApiServiceClient.GetNotificationSubscription", + extra={ + "serviceName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", + "rpcName": "GetNotificationSubscription", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = NotificationsApiServiceRestTransport._GetNotificationSubscription._get_response( self._host, @@ -589,7 +713,31 @@ def __call__( pb_resp = notificationsapi.NotificationSubscription.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_notification_subscription(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + notificationsapi.NotificationSubscription.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.notifications_v1beta.NotificationsApiServiceClient.get_notification_subscription", + extra={ + "serviceName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", + "rpcName": "GetNotificationSubscription", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _ListNotificationSubscriptions( @@ -629,7 +777,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> notificationsapi.ListNotificationSubscriptionsResponse: r"""Call the list notification subscriptions method over HTTP. @@ -641,8 +789,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.notificationsapi.ListNotificationSubscriptionsResponse: @@ -654,6 +804,7 @@ def __call__( http_options = ( _BaseNotificationsApiServiceRestTransport._BaseListNotificationSubscriptions._get_http_options() ) + request, metadata = self._interceptor.pre_list_notification_subscriptions( request, metadata ) @@ -666,6 +817,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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.notifications_v1beta.NotificationsApiServiceClient.ListNotificationSubscriptions", + extra={ + "serviceName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", + "rpcName": "ListNotificationSubscriptions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = NotificationsApiServiceRestTransport._ListNotificationSubscriptions._get_response( self._host, @@ -686,7 +864,33 @@ def __call__( pb_resp = notificationsapi.ListNotificationSubscriptionsResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_notification_subscriptions(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + notificationsapi.ListNotificationSubscriptionsResponse.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.notifications_v1beta.NotificationsApiServiceClient.list_notification_subscriptions", + extra={ + "serviceName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", + "rpcName": "ListNotificationSubscriptions", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _UpdateNotificationSubscription( @@ -727,7 +931,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> notificationsapi.NotificationSubscription: r"""Call the update notification subscription method over HTTP. @@ -739,8 +943,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.notificationsapi.NotificationSubscription: @@ -753,6 +959,7 @@ def __call__( http_options = ( _BaseNotificationsApiServiceRestTransport._BaseUpdateNotificationSubscription._get_http_options() ) + request, metadata = self._interceptor.pre_update_notification_subscription( request, metadata ) @@ -769,6 +976,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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.notifications_v1beta.NotificationsApiServiceClient.UpdateNotificationSubscription", + extra={ + "serviceName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", + "rpcName": "UpdateNotificationSubscription", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = NotificationsApiServiceRestTransport._UpdateNotificationSubscription._get_response( self._host, @@ -790,7 +1024,31 @@ def __call__( pb_resp = notificationsapi.NotificationSubscription.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_notification_subscription(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + notificationsapi.NotificationSubscription.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.notifications_v1beta.NotificationsApiServiceClient.update_notification_subscription", + extra={ + "serviceName": "google.shopping.merchant.notifications.v1beta.NotificationsApiService", + "rpcName": "UpdateNotificationSubscription", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp @property diff --git a/packages/google-shopping-merchant-notifications/samples/generated_samples/snippet_metadata_google.shopping.merchant.notifications.v1beta.json b/packages/google-shopping-merchant-notifications/samples/generated_samples/snippet_metadata_google.shopping.merchant.notifications.v1beta.json index 8ef25b049d98..b27b3eb2144a 100644 --- a/packages/google-shopping-merchant-notifications/samples/generated_samples/snippet_metadata_google.shopping.merchant.notifications.v1beta.json +++ b/packages/google-shopping-merchant-notifications/samples/generated_samples/snippet_metadata_google.shopping.merchant.notifications.v1beta.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-shopping-merchant-notifications", - "version": "0.1.4" + "version": "0.1.0" }, "snippets": [ { @@ -51,7 +51,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_notifications_v1beta.types.NotificationSubscription", @@ -135,7 +135,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_notifications_v1beta.types.NotificationSubscription", @@ -216,7 +216,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "shortName": "delete_notification_subscription" @@ -293,7 +293,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "shortName": "delete_notification_subscription" @@ -371,7 +371,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_notifications_v1beta.types.NotificationSubscription", @@ -451,7 +451,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_notifications_v1beta.types.NotificationSubscription", @@ -532,7 +532,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_notifications_v1beta.services.notifications_api_service.pagers.ListNotificationSubscriptionsAsyncPager", @@ -612,7 +612,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_notifications_v1beta.services.notifications_api_service.pagers.ListNotificationSubscriptionsPager", @@ -697,7 +697,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_notifications_v1beta.types.NotificationSubscription", @@ -781,7 +781,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_notifications_v1beta.types.NotificationSubscription", diff --git a/packages/google-shopping-merchant-notifications/tests/unit/gapic/merchant_notifications_v1beta/test_notifications_api_service.py b/packages/google-shopping-merchant-notifications/tests/unit/gapic/merchant_notifications_v1beta/test_notifications_api_service.py index 539113224bb4..4c80bffc3327 100644 --- a/packages/google-shopping-merchant-notifications/tests/unit/gapic/merchant_notifications_v1beta/test_notifications_api_service.py +++ b/packages/google-shopping-merchant-notifications/tests/unit/gapic/merchant_notifications_v1beta/test_notifications_api_service.py @@ -3222,6 +3222,7 @@ def test_get_notification_subscription_rest_required_fields( response_value._content = json_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_notification_subscription(request) @@ -3269,6 +3270,7 @@ def test_get_notification_subscription_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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_notification_subscription(**mock_args) @@ -3406,6 +3408,7 @@ def test_create_notification_subscription_rest_required_fields( response_value._content = json_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_notification_subscription(request) @@ -3464,6 +3467,7 @@ def test_create_notification_subscription_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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_notification_subscription(**mock_args) @@ -3601,6 +3605,7 @@ def test_update_notification_subscription_rest_required_fields( response_value._content = json_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_notification_subscription(request) @@ -3657,6 +3662,7 @@ def test_update_notification_subscription_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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_notification_subscription(**mock_args) @@ -3793,6 +3799,7 @@ def test_delete_notification_subscription_rest_required_fields( response_value._content = json_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_notification_subscription(request) @@ -3838,6 +3845,7 @@ def test_delete_notification_subscription_rest_flattened(): 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_notification_subscription(**mock_args) @@ -3983,6 +3991,7 @@ def test_list_notification_subscriptions_rest_required_fields( response_value._content = json_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_notification_subscriptions(request) @@ -4040,6 +4049,7 @@ def test_list_notification_subscriptions_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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_notification_subscriptions(**mock_args) @@ -4547,6 +4557,7 @@ def test_get_notification_subscription_rest_bad_request( 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_notification_subscription(request) @@ -4585,6 +4596,7 @@ def test_get_notification_subscription_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_notification_subscription(request) # Establish that the response is the type that we expect. @@ -4632,6 +4644,7 @@ def test_get_notification_subscription_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 = notificationsapi.NotificationSubscription.to_json( notificationsapi.NotificationSubscription() ) @@ -4678,6 +4691,7 @@ def test_create_notification_subscription_rest_bad_request( 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_notification_subscription(request) @@ -4796,6 +4810,7 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_notification_subscription(request) # Establish that the response is the type that we expect. @@ -4843,6 +4858,7 @@ def test_create_notification_subscription_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 = notificationsapi.NotificationSubscription.to_json( notificationsapi.NotificationSubscription() ) @@ -4893,6 +4909,7 @@ def test_update_notification_subscription_rest_bad_request( 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_notification_subscription(request) @@ -5015,6 +5032,7 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_notification_subscription(request) # Establish that the response is the type that we expect. @@ -5062,6 +5080,7 @@ def test_update_notification_subscription_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 = notificationsapi.NotificationSubscription.to_json( notificationsapi.NotificationSubscription() ) @@ -5108,6 +5127,7 @@ def test_delete_notification_subscription_rest_bad_request( 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_notification_subscription(request) @@ -5138,6 +5158,7 @@ def test_delete_notification_subscription_rest_call_success(request_type): 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_notification_subscription(request) # Establish that the response is the type that we expect. @@ -5175,6 +5196,7 @@ def test_delete_notification_subscription_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"} request = notificationsapi.DeleteNotificationSubscriptionRequest() metadata = [ @@ -5215,6 +5237,7 @@ def test_list_notification_subscriptions_rest_bad_request( 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_notification_subscriptions(request) @@ -5252,6 +5275,7 @@ def test_list_notification_subscriptions_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_notification_subscriptions(request) # Establish that the response is the type that we expect. @@ -5294,6 +5318,7 @@ def test_list_notification_subscriptions_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 = notificationsapi.ListNotificationSubscriptionsResponse.to_json( notificationsapi.ListNotificationSubscriptionsResponse() ) diff --git a/packages/google-shopping-merchant-promotions/google/shopping/merchant_promotions/gapic_version.py b/packages/google-shopping-merchant-promotions/google/shopping/merchant_promotions/gapic_version.py index 937ede8823ef..558c8aab67c5 100644 --- a/packages/google-shopping-merchant-promotions/google/shopping/merchant_promotions/gapic_version.py +++ b/packages/google-shopping-merchant-promotions/google/shopping/merchant_promotions/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.4" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-shopping-merchant-promotions/google/shopping/merchant_promotions_v1beta/gapic_version.py b/packages/google-shopping-merchant-promotions/google/shopping/merchant_promotions_v1beta/gapic_version.py index 937ede8823ef..558c8aab67c5 100644 --- a/packages/google-shopping-merchant-promotions/google/shopping/merchant_promotions_v1beta/gapic_version.py +++ b/packages/google-shopping-merchant-promotions/google/shopping/merchant_promotions_v1beta/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.4" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-shopping-merchant-promotions/google/shopping/merchant_promotions_v1beta/services/promotions_service/async_client.py b/packages/google-shopping-merchant-promotions/google/shopping/merchant_promotions_v1beta/services/promotions_service/async_client.py index 70670bb806fb..6a80990a8530 100644 --- a/packages/google-shopping-merchant-promotions/google/shopping/merchant_promotions_v1beta/services/promotions_service/async_client.py +++ b/packages/google-shopping-merchant-promotions/google/shopping/merchant_promotions_v1beta/services/promotions_service/async_client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import re from typing import ( Callable, @@ -56,6 +57,15 @@ from .transports.base import DEFAULT_CLIENT_INFO, PromotionsServiceTransport from .transports.grpc_asyncio import PromotionsServiceGrpcAsyncIOTransport +try: + from google.api_core import client_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 PromotionsServiceAsyncClient: """Service to manage promotions for products.""" @@ -265,13 +275,35 @@ def __init__( client_info=client_info, ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.shopping.merchant.promotions_v1beta.PromotionsServiceAsyncClient`.", + extra={ + "serviceName": "google.shopping.merchant.promotions.v1beta.PromotionsService", + "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.promotions.v1beta.PromotionsService", + "credentialsType": None, + }, + ) + async def insert_promotion( self, request: Optional[Union[promotions.InsertPromotionRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> promotions.Promotion: r"""Inserts a promotion for your Merchant Center account. If the promotion already exists, then it updates the @@ -317,8 +349,10 @@ async def sample_insert_promotion(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_promotions_v1beta.types.Promotion: @@ -377,7 +411,7 @@ async def get_promotion( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> promotions.Promotion: r"""Retrieves the promotion from your Merchant Center account. @@ -424,8 +458,10 @@ async def sample_get_promotion(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_promotions_v1beta.types.Promotion: @@ -498,7 +534,7 @@ async def list_promotions( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListPromotionsAsyncPager: r"""Lists the promotions in your Merchant Center account. The response might contain fewer items than specified by @@ -548,8 +584,10 @@ async def sample_list_promotions(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_promotions_v1beta.services.promotions_service.pagers.ListPromotionsAsyncPager: diff --git a/packages/google-shopping-merchant-promotions/google/shopping/merchant_promotions_v1beta/services/promotions_service/client.py b/packages/google-shopping-merchant-promotions/google/shopping/merchant_promotions_v1beta/services/promotions_service/client.py index bd9a6634ccab..c589b0e7f7a0 100644 --- a/packages/google-shopping-merchant-promotions/google/shopping/merchant_promotions_v1beta/services/promotions_service/client.py +++ b/packages/google-shopping-merchant-promotions/google/shopping/merchant_promotions_v1beta/services/promotions_service/client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import os import re from typing import ( @@ -48,6 +49,15 @@ 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.type.types import types from google.shopping.merchant_promotions_v1beta.services.promotions_service import ( @@ -584,6 +594,10 @@ def __init__( # 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( @@ -650,13 +664,36 @@ def __init__( 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.promotions_v1beta.PromotionsServiceClient`.", + extra={ + "serviceName": "google.shopping.merchant.promotions.v1beta.PromotionsService", + "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.promotions.v1beta.PromotionsService", + "credentialsType": None, + }, + ) + def insert_promotion( self, request: Optional[Union[promotions.InsertPromotionRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> promotions.Promotion: r"""Inserts a promotion for your Merchant Center account. If the promotion already exists, then it updates the @@ -702,8 +739,10 @@ def sample_insert_promotion(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_promotions_v1beta.types.Promotion: @@ -760,7 +799,7 @@ def get_promotion( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> promotions.Promotion: r"""Retrieves the promotion from your Merchant Center account. @@ -807,8 +846,10 @@ def sample_get_promotion(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_promotions_v1beta.types.Promotion: @@ -878,7 +919,7 @@ def list_promotions( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListPromotionsPager: r"""Lists the promotions in your Merchant Center account. The response might contain fewer items than specified by @@ -928,8 +969,10 @@ def sample_list_promotions(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_promotions_v1beta.services.promotions_service.pagers.ListPromotionsPager: diff --git a/packages/google-shopping-merchant-promotions/google/shopping/merchant_promotions_v1beta/services/promotions_service/pagers.py b/packages/google-shopping-merchant-promotions/google/shopping/merchant_promotions_v1beta/services/promotions_service/pagers.py index cdcafe41830b..87b1030c4243 100644 --- a/packages/google-shopping-merchant-promotions/google/shopping/merchant_promotions_v1beta/services/promotions_service/pagers.py +++ b/packages/google-shopping-merchant-promotions/google/shopping/merchant_promotions_v1beta/services/promotions_service/pagers.py @@ -67,7 +67,7 @@ def __init__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiate the pager. @@ -81,8 +81,10 @@ def __init__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 = promotions.ListPromotionsRequest(request) @@ -141,7 +143,7 @@ def __init__( *, retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiates the pager. @@ -155,8 +157,10 @@ def __init__( 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 = promotions.ListPromotionsRequest(request) diff --git a/packages/google-shopping-merchant-promotions/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/grpc.py b/packages/google-shopping-merchant-promotions/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/grpc.py index c60167c4515f..ea7eea1058af 100644 --- a/packages/google-shopping-merchant-promotions/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/grpc.py +++ b/packages/google-shopping-merchant-promotions/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/grpc.py @@ -13,6 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import json +import logging as std_logging +import pickle from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -20,12 +23,90 @@ 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_promotions_v1beta.types import promotions from .base import DEFAULT_CLIENT_INFO, PromotionsServiceTransport +try: + from google.api_core import client_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.promotions.v1beta.PromotionsService", + "rpcName": 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.promotions.v1beta.PromotionsService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + class PromotionsServiceGrpcTransport(PromotionsServiceTransport): """gRPC backend transport for PromotionsService. @@ -179,7 +260,12 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -255,7 +341,7 @@ def insert_promotion( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "insert_promotion" not in self._stubs: - self._stubs["insert_promotion"] = self.grpc_channel.unary_unary( + self._stubs["insert_promotion"] = self._logged_channel.unary_unary( "/google.shopping.merchant.promotions.v1beta.PromotionsService/InsertPromotion", request_serializer=promotions.InsertPromotionRequest.serialize, response_deserializer=promotions.Promotion.deserialize, @@ -285,7 +371,7 @@ def get_promotion( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_promotion" not in self._stubs: - self._stubs["get_promotion"] = self.grpc_channel.unary_unary( + self._stubs["get_promotion"] = self._logged_channel.unary_unary( "/google.shopping.merchant.promotions.v1beta.PromotionsService/GetPromotion", request_serializer=promotions.GetPromotionRequest.serialize, response_deserializer=promotions.Promotion.deserialize, @@ -319,7 +405,7 @@ def list_promotions( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_promotions" not in self._stubs: - self._stubs["list_promotions"] = self.grpc_channel.unary_unary( + self._stubs["list_promotions"] = self._logged_channel.unary_unary( "/google.shopping.merchant.promotions.v1beta.PromotionsService/ListPromotions", request_serializer=promotions.ListPromotionsRequest.serialize, response_deserializer=promotions.ListPromotionsResponse.deserialize, @@ -327,7 +413,7 @@ def list_promotions( return self._stubs["list_promotions"] def close(self): - self.grpc_channel.close() + self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-promotions/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-promotions/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/grpc_asyncio.py index 75776592ea82..8f428255c35c 100644 --- a/packages/google-shopping-merchant-promotions/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-promotions/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/grpc_asyncio.py @@ -14,6 +14,9 @@ # limitations under the License. # import inspect +import json +import logging as std_logging +import pickle from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -22,14 +25,93 @@ 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 from grpc.experimental import aio # type: ignore +import proto # type: ignore from google.shopping.merchant_promotions_v1beta.types import promotions from .base import DEFAULT_CLIENT_INFO, PromotionsServiceTransport from .grpc import PromotionsServiceGrpcTransport +try: + from google.api_core import client_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.promotions.v1beta.PromotionsService", + "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.promotions.v1beta.PromotionsService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + class PromotionsServiceGrpcAsyncIOTransport(PromotionsServiceTransport): """gRPC AsyncIO backend transport for PromotionsService. @@ -226,10 +308,13 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -263,7 +348,7 @@ def insert_promotion( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "insert_promotion" not in self._stubs: - self._stubs["insert_promotion"] = self.grpc_channel.unary_unary( + self._stubs["insert_promotion"] = self._logged_channel.unary_unary( "/google.shopping.merchant.promotions.v1beta.PromotionsService/InsertPromotion", request_serializer=promotions.InsertPromotionRequest.serialize, response_deserializer=promotions.Promotion.deserialize, @@ -293,7 +378,7 @@ def get_promotion( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_promotion" not in self._stubs: - self._stubs["get_promotion"] = self.grpc_channel.unary_unary( + self._stubs["get_promotion"] = self._logged_channel.unary_unary( "/google.shopping.merchant.promotions.v1beta.PromotionsService/GetPromotion", request_serializer=promotions.GetPromotionRequest.serialize, response_deserializer=promotions.Promotion.deserialize, @@ -327,7 +412,7 @@ def list_promotions( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_promotions" not in self._stubs: - self._stubs["list_promotions"] = self.grpc_channel.unary_unary( + self._stubs["list_promotions"] = self._logged_channel.unary_unary( "/google.shopping.merchant.promotions.v1beta.PromotionsService/ListPromotions", request_serializer=promotions.ListPromotionsRequest.serialize, response_deserializer=promotions.ListPromotionsResponse.deserialize, @@ -360,7 +445,7 @@ def _wrap_method(self, func, *args, **kwargs): return gapic_v1.method_async.wrap_method(func, *args, **kwargs) def close(self): - return self.grpc_channel.close() + return self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-promotions/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/rest.py b/packages/google-shopping-merchant-promotions/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/rest.py index efd1401a514c..1cea05241158 100644 --- a/packages/google-shopping-merchant-promotions/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/rest.py +++ b/packages/google-shopping-merchant-promotions/google/shopping/merchant_promotions_v1beta/services/promotions_service/transports/rest.py @@ -13,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import dataclasses import json # type: ignore +import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings @@ -37,6 +37,14 @@ 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, @@ -93,8 +101,8 @@ def post_list_promotions(self, response): def pre_get_promotion( self, request: promotions.GetPromotionRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[promotions.GetPromotionRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[promotions.GetPromotionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for get_promotion Override in a subclass to manipulate the request or metadata @@ -116,8 +124,10 @@ def post_get_promotion( def pre_insert_promotion( self, request: promotions.InsertPromotionRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[promotions.InsertPromotionRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + promotions.InsertPromotionRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for insert_promotion Override in a subclass to manipulate the request or metadata @@ -139,8 +149,10 @@ def post_insert_promotion( def pre_list_promotions( self, request: promotions.ListPromotionsRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[promotions.ListPromotionsRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + promotions.ListPromotionsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for list_promotions Override in a subclass to manipulate the request or metadata @@ -280,7 +292,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> promotions.Promotion: r"""Call the get promotion method over HTTP. @@ -290,8 +302,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.promotions.Promotion: @@ -315,6 +329,7 @@ def __call__( http_options = ( _BasePromotionsServiceRestTransport._BaseGetPromotion._get_http_options() ) + request, metadata = self._interceptor.pre_get_promotion(request, metadata) transcoded_request = _BasePromotionsServiceRestTransport._BaseGetPromotion._get_transcoded_request( http_options, request @@ -325,6 +340,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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.promotions_v1beta.PromotionsServiceClient.GetPromotion", + extra={ + "serviceName": "google.shopping.merchant.promotions.v1beta.PromotionsService", + "rpcName": "GetPromotion", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = PromotionsServiceRestTransport._GetPromotion._get_response( self._host, @@ -345,7 +387,29 @@ def __call__( pb_resp = promotions.Promotion.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_promotion(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = promotions.Promotion.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.promotions_v1beta.PromotionsServiceClient.get_promotion", + extra={ + "serviceName": "google.shopping.merchant.promotions.v1beta.PromotionsService", + "rpcName": "GetPromotion", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _InsertPromotion( @@ -384,7 +448,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> promotions.Promotion: r"""Call the insert promotion method over HTTP. @@ -394,8 +458,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.promotions.Promotion: @@ -419,6 +485,7 @@ def __call__( http_options = ( _BasePromotionsServiceRestTransport._BaseInsertPromotion._get_http_options() ) + request, metadata = self._interceptor.pre_insert_promotion( request, metadata ) @@ -435,6 +502,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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.promotions_v1beta.PromotionsServiceClient.InsertPromotion", + extra={ + "serviceName": "google.shopping.merchant.promotions.v1beta.PromotionsService", + "rpcName": "InsertPromotion", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = PromotionsServiceRestTransport._InsertPromotion._get_response( self._host, @@ -456,7 +550,29 @@ def __call__( pb_resp = promotions.Promotion.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_insert_promotion(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = promotions.Promotion.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.promotions_v1beta.PromotionsServiceClient.insert_promotion", + extra={ + "serviceName": "google.shopping.merchant.promotions.v1beta.PromotionsService", + "rpcName": "InsertPromotion", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _ListPromotions( @@ -494,7 +610,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> promotions.ListPromotionsResponse: r"""Call the list promotions method over HTTP. @@ -504,8 +620,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.promotions.ListPromotionsResponse: @@ -515,6 +633,7 @@ def __call__( http_options = ( _BasePromotionsServiceRestTransport._BaseListPromotions._get_http_options() ) + request, metadata = self._interceptor.pre_list_promotions(request, metadata) transcoded_request = _BasePromotionsServiceRestTransport._BaseListPromotions._get_transcoded_request( http_options, request @@ -525,6 +644,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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.promotions_v1beta.PromotionsServiceClient.ListPromotions", + extra={ + "serviceName": "google.shopping.merchant.promotions.v1beta.PromotionsService", + "rpcName": "ListPromotions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = PromotionsServiceRestTransport._ListPromotions._get_response( self._host, @@ -545,7 +691,31 @@ def __call__( pb_resp = promotions.ListPromotionsResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_promotions(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = promotions.ListPromotionsResponse.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.promotions_v1beta.PromotionsServiceClient.list_promotions", + extra={ + "serviceName": "google.shopping.merchant.promotions.v1beta.PromotionsService", + "rpcName": "ListPromotions", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp @property diff --git a/packages/google-shopping-merchant-promotions/samples/generated_samples/snippet_metadata_google.shopping.merchant.promotions.v1beta.json b/packages/google-shopping-merchant-promotions/samples/generated_samples/snippet_metadata_google.shopping.merchant.promotions.v1beta.json index d0f8cb6bfc9d..35c4091b4ca2 100644 --- a/packages/google-shopping-merchant-promotions/samples/generated_samples/snippet_metadata_google.shopping.merchant.promotions.v1beta.json +++ b/packages/google-shopping-merchant-promotions/samples/generated_samples/snippet_metadata_google.shopping.merchant.promotions.v1beta.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-shopping-merchant-promotions", - "version": "0.1.4" + "version": "0.1.0" }, "snippets": [ { @@ -47,7 +47,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_promotions_v1beta.types.Promotion", @@ -127,7 +127,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_promotions_v1beta.types.Promotion", @@ -204,7 +204,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_promotions_v1beta.types.Promotion", @@ -280,7 +280,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_promotions_v1beta.types.Promotion", @@ -361,7 +361,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_promotions_v1beta.services.promotions_service.pagers.ListPromotionsAsyncPager", @@ -441,7 +441,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_promotions_v1beta.services.promotions_service.pagers.ListPromotionsPager", diff --git a/packages/google-shopping-merchant-promotions/tests/unit/gapic/merchant_promotions_v1beta/test_promotions_service.py b/packages/google-shopping-merchant-promotions/tests/unit/gapic/merchant_promotions_v1beta/test_promotions_service.py index d04c440dbc01..f103f5757a16 100644 --- a/packages/google-shopping-merchant-promotions/tests/unit/gapic/merchant_promotions_v1beta/test_promotions_service.py +++ b/packages/google-shopping-merchant-promotions/tests/unit/gapic/merchant_promotions_v1beta/test_promotions_service.py @@ -2348,6 +2348,7 @@ def test_insert_promotion_rest_required_fields( response_value._content = json_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_promotion(request) @@ -2476,6 +2477,7 @@ def test_get_promotion_rest_required_fields( response_value._content = json_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_promotion(request) @@ -2521,6 +2523,7 @@ def test_get_promotion_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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_promotion(**mock_args) @@ -2659,6 +2662,7 @@ def test_list_promotions_rest_required_fields( response_value._content = json_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_promotions(request) @@ -2712,6 +2716,7 @@ def test_list_promotions_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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_promotions(**mock_args) @@ -3106,6 +3111,7 @@ def test_insert_promotion_rest_bad_request( 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_promotion(request) @@ -3147,6 +3153,7 @@ def test_insert_promotion_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_promotion(request) # Establish that the response is the type that we expect. @@ -3193,6 +3200,7 @@ def test_insert_promotion_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 = promotions.Promotion.to_json(promotions.Promotion()) req.return_value.content = return_value @@ -3235,6 +3243,7 @@ def test_get_promotion_rest_bad_request(request_type=promotions.GetPromotionRequ 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_promotion(request) @@ -3276,6 +3285,7 @@ def test_get_promotion_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_promotion(request) # Establish that the response is the type that we expect. @@ -3320,6 +3330,7 @@ def test_get_promotion_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 = promotions.Promotion.to_json(promotions.Promotion()) req.return_value.content = return_value @@ -3364,6 +3375,7 @@ def test_list_promotions_rest_bad_request( 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_promotions(request) @@ -3399,6 +3411,7 @@ def test_list_promotions_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_promotions(request) # Establish that the response is the type that we expect. @@ -3439,6 +3452,7 @@ def test_list_promotions_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 = promotions.ListPromotionsResponse.to_json( promotions.ListPromotionsResponse() ) diff --git a/packages/google-shopping-merchant-quota/google/shopping/merchant_quota/gapic_version.py b/packages/google-shopping-merchant-quota/google/shopping/merchant_quota/gapic_version.py index 937ede8823ef..558c8aab67c5 100644 --- a/packages/google-shopping-merchant-quota/google/shopping/merchant_quota/gapic_version.py +++ b/packages/google-shopping-merchant-quota/google/shopping/merchant_quota/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.4" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-shopping-merchant-quota/google/shopping/merchant_quota_v1beta/gapic_version.py b/packages/google-shopping-merchant-quota/google/shopping/merchant_quota_v1beta/gapic_version.py index 937ede8823ef..558c8aab67c5 100644 --- a/packages/google-shopping-merchant-quota/google/shopping/merchant_quota_v1beta/gapic_version.py +++ b/packages/google-shopping-merchant-quota/google/shopping/merchant_quota_v1beta/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.4" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-shopping-merchant-quota/google/shopping/merchant_quota_v1beta/services/quota_service/async_client.py b/packages/google-shopping-merchant-quota/google/shopping/merchant_quota_v1beta/services/quota_service/async_client.py index 3e89516cd556..18514ce5acb6 100644 --- a/packages/google-shopping-merchant-quota/google/shopping/merchant_quota_v1beta/services/quota_service/async_client.py +++ b/packages/google-shopping-merchant-quota/google/shopping/merchant_quota_v1beta/services/quota_service/async_client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import re from typing import ( Callable, @@ -49,6 +50,15 @@ from .transports.base import DEFAULT_CLIENT_INFO, QuotaServiceTransport from .transports.grpc_asyncio import QuotaServiceGrpcAsyncIOTransport +try: + from google.api_core import client_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 QuotaServiceAsyncClient: """Service to get method call quota information per Merchant API @@ -252,6 +262,28 @@ def __init__( client_info=client_info, ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.shopping.merchant.quota_v1beta.QuotaServiceAsyncClient`.", + extra={ + "serviceName": "google.shopping.merchant.quota.v1beta.QuotaService", + "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.quota.v1beta.QuotaService", + "credentialsType": None, + }, + ) + async def list_quota_groups( self, request: Optional[Union[quota.ListQuotaGroupsRequest, dict]] = None, @@ -259,7 +291,7 @@ async def list_quota_groups( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListQuotaGroupsAsyncPager: r"""Lists the daily call quota and usage per group for your Merchant Center account. @@ -306,8 +338,10 @@ async def sample_list_quota_groups(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_quota_v1beta.services.quota_service.pagers.ListQuotaGroupsAsyncPager: diff --git a/packages/google-shopping-merchant-quota/google/shopping/merchant_quota_v1beta/services/quota_service/client.py b/packages/google-shopping-merchant-quota/google/shopping/merchant_quota_v1beta/services/quota_service/client.py index b590cbd9bf64..ef3f0a2b9e34 100644 --- a/packages/google-shopping-merchant-quota/google/shopping/merchant_quota_v1beta/services/quota_service/client.py +++ b/packages/google-shopping-merchant-quota/google/shopping/merchant_quota_v1beta/services/quota_service/client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import os import re from typing import ( @@ -48,6 +49,15 @@ 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_quota_v1beta.services.quota_service import pagers from google.shopping.merchant_quota_v1beta.types import quota @@ -573,6 +583,10 @@ def __init__( # 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( @@ -635,6 +649,29 @@ def __init__( 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.quota_v1beta.QuotaServiceClient`.", + extra={ + "serviceName": "google.shopping.merchant.quota.v1beta.QuotaService", + "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.quota.v1beta.QuotaService", + "credentialsType": None, + }, + ) + def list_quota_groups( self, request: Optional[Union[quota.ListQuotaGroupsRequest, dict]] = None, @@ -642,7 +679,7 @@ def list_quota_groups( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListQuotaGroupsPager: r"""Lists the daily call quota and usage per group for your Merchant Center account. @@ -689,8 +726,10 @@ def sample_list_quota_groups(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_quota_v1beta.services.quota_service.pagers.ListQuotaGroupsPager: diff --git a/packages/google-shopping-merchant-quota/google/shopping/merchant_quota_v1beta/services/quota_service/pagers.py b/packages/google-shopping-merchant-quota/google/shopping/merchant_quota_v1beta/services/quota_service/pagers.py index fcb1ce134f0d..5359d0205a80 100644 --- a/packages/google-shopping-merchant-quota/google/shopping/merchant_quota_v1beta/services/quota_service/pagers.py +++ b/packages/google-shopping-merchant-quota/google/shopping/merchant_quota_v1beta/services/quota_service/pagers.py @@ -67,7 +67,7 @@ def __init__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiate the pager. @@ -81,8 +81,10 @@ def __init__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 = quota.ListQuotaGroupsRequest(request) @@ -141,7 +143,7 @@ def __init__( *, retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiates the pager. @@ -155,8 +157,10 @@ def __init__( 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 = quota.ListQuotaGroupsRequest(request) diff --git a/packages/google-shopping-merchant-quota/google/shopping/merchant_quota_v1beta/services/quota_service/transports/grpc.py b/packages/google-shopping-merchant-quota/google/shopping/merchant_quota_v1beta/services/quota_service/transports/grpc.py index 99b13679bca4..2f50b1db9685 100644 --- a/packages/google-shopping-merchant-quota/google/shopping/merchant_quota_v1beta/services/quota_service/transports/grpc.py +++ b/packages/google-shopping-merchant-quota/google/shopping/merchant_quota_v1beta/services/quota_service/transports/grpc.py @@ -13,6 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import json +import logging as std_logging +import pickle from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -20,12 +23,90 @@ 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_quota_v1beta.types import quota from .base import DEFAULT_CLIENT_INFO, QuotaServiceTransport +try: + from google.api_core import client_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.quota.v1beta.QuotaService", + "rpcName": 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.quota.v1beta.QuotaService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + class QuotaServiceGrpcTransport(QuotaServiceTransport): """gRPC backend transport for QuotaService. @@ -180,7 +261,12 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -255,7 +341,7 @@ def list_quota_groups( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_quota_groups" not in self._stubs: - self._stubs["list_quota_groups"] = self.grpc_channel.unary_unary( + self._stubs["list_quota_groups"] = self._logged_channel.unary_unary( "/google.shopping.merchant.quota.v1beta.QuotaService/ListQuotaGroups", request_serializer=quota.ListQuotaGroupsRequest.serialize, response_deserializer=quota.ListQuotaGroupsResponse.deserialize, @@ -263,7 +349,7 @@ def list_quota_groups( return self._stubs["list_quota_groups"] def close(self): - self.grpc_channel.close() + self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-quota/google/shopping/merchant_quota_v1beta/services/quota_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-quota/google/shopping/merchant_quota_v1beta/services/quota_service/transports/grpc_asyncio.py index 7e3d06377006..0e8cd43684fd 100644 --- a/packages/google-shopping-merchant-quota/google/shopping/merchant_quota_v1beta/services/quota_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-quota/google/shopping/merchant_quota_v1beta/services/quota_service/transports/grpc_asyncio.py @@ -14,6 +14,9 @@ # limitations under the License. # import inspect +import json +import logging as std_logging +import pickle from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -22,14 +25,93 @@ 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 from grpc.experimental import aio # type: ignore +import proto # type: ignore from google.shopping.merchant_quota_v1beta.types import quota from .base import DEFAULT_CLIENT_INFO, QuotaServiceTransport from .grpc import QuotaServiceGrpcTransport +try: + from google.api_core import client_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.quota.v1beta.QuotaService", + "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.quota.v1beta.QuotaService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + class QuotaServiceGrpcAsyncIOTransport(QuotaServiceTransport): """gRPC AsyncIO backend transport for QuotaService. @@ -227,10 +309,13 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -265,7 +350,7 @@ def list_quota_groups( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_quota_groups" not in self._stubs: - self._stubs["list_quota_groups"] = self.grpc_channel.unary_unary( + self._stubs["list_quota_groups"] = self._logged_channel.unary_unary( "/google.shopping.merchant.quota.v1beta.QuotaService/ListQuotaGroups", request_serializer=quota.ListQuotaGroupsRequest.serialize, response_deserializer=quota.ListQuotaGroupsResponse.deserialize, @@ -288,7 +373,7 @@ def _wrap_method(self, func, *args, **kwargs): return gapic_v1.method_async.wrap_method(func, *args, **kwargs) def close(self): - return self.grpc_channel.close() + return self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-quota/google/shopping/merchant_quota_v1beta/services/quota_service/transports/rest.py b/packages/google-shopping-merchant-quota/google/shopping/merchant_quota_v1beta/services/quota_service/transports/rest.py index b4b942f6e478..7ed3514e74c5 100644 --- a/packages/google-shopping-merchant-quota/google/shopping/merchant_quota_v1beta/services/quota_service/transports/rest.py +++ b/packages/google-shopping-merchant-quota/google/shopping/merchant_quota_v1beta/services/quota_service/transports/rest.py @@ -13,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import dataclasses import json # type: ignore +import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings @@ -37,6 +37,14 @@ 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, @@ -75,8 +83,10 @@ def post_list_quota_groups(self, response): """ def pre_list_quota_groups( - self, request: quota.ListQuotaGroupsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[quota.ListQuotaGroupsRequest, Sequence[Tuple[str, str]]]: + self, + request: quota.ListQuotaGroupsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[quota.ListQuotaGroupsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for list_quota_groups Override in a subclass to manipulate the request or metadata @@ -217,7 +227,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> quota.ListQuotaGroupsResponse: r"""Call the list quota groups method over HTTP. @@ -228,8 +238,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.quota.ListQuotaGroupsResponse: @@ -241,6 +253,7 @@ def __call__( http_options = ( _BaseQuotaServiceRestTransport._BaseListQuotaGroups._get_http_options() ) + request, metadata = self._interceptor.pre_list_quota_groups( request, metadata ) @@ -253,6 +266,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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.quota_v1beta.QuotaServiceClient.ListQuotaGroups", + extra={ + "serviceName": "google.shopping.merchant.quota.v1beta.QuotaService", + "rpcName": "ListQuotaGroups", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = QuotaServiceRestTransport._ListQuotaGroups._get_response( self._host, @@ -273,7 +313,29 @@ def __call__( pb_resp = quota.ListQuotaGroupsResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_quota_groups(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = quota.ListQuotaGroupsResponse.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.quota_v1beta.QuotaServiceClient.list_quota_groups", + extra={ + "serviceName": "google.shopping.merchant.quota.v1beta.QuotaService", + "rpcName": "ListQuotaGroups", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp @property diff --git a/packages/google-shopping-merchant-quota/samples/generated_samples/snippet_metadata_google.shopping.merchant.quota.v1beta.json b/packages/google-shopping-merchant-quota/samples/generated_samples/snippet_metadata_google.shopping.merchant.quota.v1beta.json index bae6584d26a7..48037ddf7f53 100644 --- a/packages/google-shopping-merchant-quota/samples/generated_samples/snippet_metadata_google.shopping.merchant.quota.v1beta.json +++ b/packages/google-shopping-merchant-quota/samples/generated_samples/snippet_metadata_google.shopping.merchant.quota.v1beta.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-shopping-merchant-quota", - "version": "0.1.4" + "version": "0.1.0" }, "snippets": [ { @@ -47,7 +47,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_quota_v1beta.services.quota_service.pagers.ListQuotaGroupsAsyncPager", @@ -127,7 +127,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_quota_v1beta.services.quota_service.pagers.ListQuotaGroupsPager", diff --git a/packages/google-shopping-merchant-quota/tests/unit/gapic/merchant_quota_v1beta/test_quota_service.py b/packages/google-shopping-merchant-quota/tests/unit/gapic/merchant_quota_v1beta/test_quota_service.py index 6c89da5d8846..134ab619ae82 100644 --- a/packages/google-shopping-merchant-quota/tests/unit/gapic/merchant_quota_v1beta/test_quota_service.py +++ b/packages/google-shopping-merchant-quota/tests/unit/gapic/merchant_quota_v1beta/test_quota_service.py @@ -1691,6 +1691,7 @@ def test_list_quota_groups_rest_required_fields( response_value._content = json_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_quota_groups(request) @@ -1744,6 +1745,7 @@ def test_list_quota_groups_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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_quota_groups(**mock_args) @@ -2031,6 +2033,7 @@ def test_list_quota_groups_rest_bad_request(request_type=quota.ListQuotaGroupsRe 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_quota_groups(request) @@ -2066,6 +2069,7 @@ def test_list_quota_groups_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_quota_groups(request) # Establish that the response is the type that we expect. @@ -2104,6 +2108,7 @@ def test_list_quota_groups_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 = quota.ListQuotaGroupsResponse.to_json( quota.ListQuotaGroupsResponse() ) diff --git a/packages/google-shopping-merchant-reports/google/shopping/merchant_reports/gapic_version.py b/packages/google-shopping-merchant-reports/google/shopping/merchant_reports/gapic_version.py index 4b834789ba9e..558c8aab67c5 100644 --- a/packages/google-shopping-merchant-reports/google/shopping/merchant_reports/gapic_version.py +++ b/packages/google-shopping-merchant-reports/google/shopping/merchant_reports/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.11" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-shopping-merchant-reports/google/shopping/merchant_reports_v1beta/gapic_version.py b/packages/google-shopping-merchant-reports/google/shopping/merchant_reports_v1beta/gapic_version.py index 4b834789ba9e..558c8aab67c5 100644 --- a/packages/google-shopping-merchant-reports/google/shopping/merchant_reports_v1beta/gapic_version.py +++ b/packages/google-shopping-merchant-reports/google/shopping/merchant_reports_v1beta/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.11" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-shopping-merchant-reports/google/shopping/merchant_reports_v1beta/services/report_service/async_client.py b/packages/google-shopping-merchant-reports/google/shopping/merchant_reports_v1beta/services/report_service/async_client.py index f43a77eca125..722e7e68fbf0 100644 --- a/packages/google-shopping-merchant-reports/google/shopping/merchant_reports_v1beta/services/report_service/async_client.py +++ b/packages/google-shopping-merchant-reports/google/shopping/merchant_reports_v1beta/services/report_service/async_client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import re from typing import ( Callable, @@ -49,6 +50,15 @@ from .transports.base import DEFAULT_CLIENT_INFO, ReportServiceTransport from .transports.grpc_asyncio import ReportServiceGrpcAsyncIOTransport +try: + from google.api_core import client_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 ReportServiceAsyncClient: """Service for retrieving reports and insights about your @@ -255,6 +265,28 @@ def __init__( client_info=client_info, ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.shopping.merchant.reports_v1beta.ReportServiceAsyncClient`.", + extra={ + "serviceName": "google.shopping.merchant.reports.v1beta.ReportService", + "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.reports.v1beta.ReportService", + "credentialsType": None, + }, + ) + async def search( self, request: Optional[Union[reports.SearchRequest, dict]] = None, @@ -262,7 +294,7 @@ async def search( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.SearchAsyncPager: r"""Retrieves a report defined by a search query. The response might contain fewer rows than specified by ``page_size``. Rely on @@ -312,8 +344,10 @@ async def sample_search(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_reports_v1beta.services.report_service.pagers.SearchAsyncPager: diff --git a/packages/google-shopping-merchant-reports/google/shopping/merchant_reports_v1beta/services/report_service/client.py b/packages/google-shopping-merchant-reports/google/shopping/merchant_reports_v1beta/services/report_service/client.py index 9f4d0d3f14f6..a80610a97821 100644 --- a/packages/google-shopping-merchant-reports/google/shopping/merchant_reports_v1beta/services/report_service/client.py +++ b/packages/google-shopping-merchant-reports/google/shopping/merchant_reports_v1beta/services/report_service/client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import os import re from typing import ( @@ -48,6 +49,15 @@ 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_reports_v1beta.services.report_service import pagers from google.shopping.merchant_reports_v1beta.types import reports @@ -557,6 +567,10 @@ def __init__( # 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( @@ -622,6 +636,29 @@ def __init__( 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.reports_v1beta.ReportServiceClient`.", + extra={ + "serviceName": "google.shopping.merchant.reports.v1beta.ReportService", + "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.reports.v1beta.ReportService", + "credentialsType": None, + }, + ) + def search( self, request: Optional[Union[reports.SearchRequest, dict]] = None, @@ -629,7 +666,7 @@ def search( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.SearchPager: r"""Retrieves a report defined by a search query. The response might contain fewer rows than specified by ``page_size``. Rely on @@ -679,8 +716,10 @@ def sample_search(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.shopping.merchant_reports_v1beta.services.report_service.pagers.SearchPager: diff --git a/packages/google-shopping-merchant-reports/google/shopping/merchant_reports_v1beta/services/report_service/pagers.py b/packages/google-shopping-merchant-reports/google/shopping/merchant_reports_v1beta/services/report_service/pagers.py index 3fef73be964b..53493a567e5d 100644 --- a/packages/google-shopping-merchant-reports/google/shopping/merchant_reports_v1beta/services/report_service/pagers.py +++ b/packages/google-shopping-merchant-reports/google/shopping/merchant_reports_v1beta/services/report_service/pagers.py @@ -67,7 +67,7 @@ def __init__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiate the pager. @@ -81,8 +81,10 @@ def __init__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 = reports.SearchRequest(request) @@ -141,7 +143,7 @@ def __init__( *, retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiates the pager. @@ -155,8 +157,10 @@ def __init__( 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 = reports.SearchRequest(request) diff --git a/packages/google-shopping-merchant-reports/google/shopping/merchant_reports_v1beta/services/report_service/transports/grpc.py b/packages/google-shopping-merchant-reports/google/shopping/merchant_reports_v1beta/services/report_service/transports/grpc.py index 0e1635e22b97..dc64e334ca53 100644 --- a/packages/google-shopping-merchant-reports/google/shopping/merchant_reports_v1beta/services/report_service/transports/grpc.py +++ b/packages/google-shopping-merchant-reports/google/shopping/merchant_reports_v1beta/services/report_service/transports/grpc.py @@ -13,6 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import json +import logging as std_logging +import pickle from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -20,12 +23,90 @@ 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_reports_v1beta.types import reports from .base import DEFAULT_CLIENT_INFO, ReportServiceTransport +try: + from google.api_core import client_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.reports.v1beta.ReportService", + "rpcName": 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.reports.v1beta.ReportService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + class ReportServiceGrpcTransport(ReportServiceTransport): """gRPC backend transport for ReportService. @@ -181,7 +262,12 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -256,7 +342,7 @@ def search(self) -> Callable[[reports.SearchRequest], reports.SearchResponse]: # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "search" not in self._stubs: - self._stubs["search"] = self.grpc_channel.unary_unary( + self._stubs["search"] = self._logged_channel.unary_unary( "/google.shopping.merchant.reports.v1beta.ReportService/Search", request_serializer=reports.SearchRequest.serialize, response_deserializer=reports.SearchResponse.deserialize, @@ -264,7 +350,7 @@ def search(self) -> Callable[[reports.SearchRequest], reports.SearchResponse]: return self._stubs["search"] def close(self): - self.grpc_channel.close() + self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-reports/google/shopping/merchant_reports_v1beta/services/report_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-reports/google/shopping/merchant_reports_v1beta/services/report_service/transports/grpc_asyncio.py index 881e4604c9c7..90a6d38f3eae 100644 --- a/packages/google-shopping-merchant-reports/google/shopping/merchant_reports_v1beta/services/report_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-reports/google/shopping/merchant_reports_v1beta/services/report_service/transports/grpc_asyncio.py @@ -14,6 +14,9 @@ # limitations under the License. # import inspect +import json +import logging as std_logging +import pickle from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -22,14 +25,93 @@ 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 from grpc.experimental import aio # type: ignore +import proto # type: ignore from google.shopping.merchant_reports_v1beta.types import reports from .base import DEFAULT_CLIENT_INFO, ReportServiceTransport from .grpc import ReportServiceGrpcTransport +try: + from google.api_core import client_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.reports.v1beta.ReportService", + "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.reports.v1beta.ReportService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + class ReportServiceGrpcAsyncIOTransport(ReportServiceTransport): """gRPC AsyncIO backend transport for ReportService. @@ -228,10 +310,13 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -266,7 +351,7 @@ def search( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "search" not in self._stubs: - self._stubs["search"] = self.grpc_channel.unary_unary( + self._stubs["search"] = self._logged_channel.unary_unary( "/google.shopping.merchant.reports.v1beta.ReportService/Search", request_serializer=reports.SearchRequest.serialize, response_deserializer=reports.SearchResponse.deserialize, @@ -289,7 +374,7 @@ def _wrap_method(self, func, *args, **kwargs): return gapic_v1.method_async.wrap_method(func, *args, **kwargs) def close(self): - return self.grpc_channel.close() + return self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/google-shopping-merchant-reports/google/shopping/merchant_reports_v1beta/services/report_service/transports/rest.py b/packages/google-shopping-merchant-reports/google/shopping/merchant_reports_v1beta/services/report_service/transports/rest.py index 50a907ac8a5a..8d9fb0e16582 100644 --- a/packages/google-shopping-merchant-reports/google/shopping/merchant_reports_v1beta/services/report_service/transports/rest.py +++ b/packages/google-shopping-merchant-reports/google/shopping/merchant_reports_v1beta/services/report_service/transports/rest.py @@ -13,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import dataclasses import json # type: ignore +import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings @@ -37,6 +37,14 @@ 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, @@ -75,8 +83,10 @@ def post_search(self, response): """ def pre_search( - self, request: reports.SearchRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[reports.SearchRequest, Sequence[Tuple[str, str]]]: + self, + request: reports.SearchRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[reports.SearchRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for search Override in a subclass to manipulate the request or metadata @@ -215,7 +225,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> reports.SearchResponse: r"""Call the search method over HTTP. @@ -225,8 +235,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.reports.SearchResponse: @@ -238,6 +250,7 @@ def __call__( http_options = ( _BaseReportServiceRestTransport._BaseSearch._get_http_options() ) + request, metadata = self._interceptor.pre_search(request, metadata) transcoded_request = ( _BaseReportServiceRestTransport._BaseSearch._get_transcoded_request( @@ -256,6 +269,33 @@ def __call__( ) ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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.reports_v1beta.ReportServiceClient.Search", + extra={ + "serviceName": "google.shopping.merchant.reports.v1beta.ReportService", + "rpcName": "Search", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = ReportServiceRestTransport._Search._get_response( self._host, @@ -277,7 +317,29 @@ def __call__( pb_resp = reports.SearchResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_search(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = reports.SearchResponse.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.reports_v1beta.ReportServiceClient.search", + extra={ + "serviceName": "google.shopping.merchant.reports.v1beta.ReportService", + "rpcName": "Search", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp @property diff --git a/packages/google-shopping-merchant-reports/samples/generated_samples/snippet_metadata_google.shopping.merchant.reports.v1beta.json b/packages/google-shopping-merchant-reports/samples/generated_samples/snippet_metadata_google.shopping.merchant.reports.v1beta.json index 35302936be5d..145fa5b7eb46 100644 --- a/packages/google-shopping-merchant-reports/samples/generated_samples/snippet_metadata_google.shopping.merchant.reports.v1beta.json +++ b/packages/google-shopping-merchant-reports/samples/generated_samples/snippet_metadata_google.shopping.merchant.reports.v1beta.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-shopping-merchant-reports", - "version": "0.1.11" + "version": "0.1.0" }, "snippets": [ { @@ -47,7 +47,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_reports_v1beta.services.report_service.pagers.SearchAsyncPager", @@ -127,7 +127,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.shopping.merchant_reports_v1beta.services.report_service.pagers.SearchPager", diff --git a/packages/google-shopping-merchant-reports/tests/unit/gapic/merchant_reports_v1beta/test_report_service.py b/packages/google-shopping-merchant-reports/tests/unit/gapic/merchant_reports_v1beta/test_report_service.py index 4fd0b9e51eef..64cffda0a359 100644 --- a/packages/google-shopping-merchant-reports/tests/unit/gapic/merchant_reports_v1beta/test_report_service.py +++ b/packages/google-shopping-merchant-reports/tests/unit/gapic/merchant_reports_v1beta/test_report_service.py @@ -1678,6 +1678,7 @@ def test_search_rest_required_fields(request_type=reports.SearchRequest): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.search(request) @@ -1731,6 +1732,7 @@ def test_search_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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.search(**mock_args) @@ -2015,6 +2017,7 @@ def test_search_rest_bad_request(request_type=reports.SearchRequest): 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.search(request) @@ -2050,6 +2053,7 @@ def test_search_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.search(request) # Establish that the response is the type that we expect. @@ -2088,6 +2092,7 @@ def test_search_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 = reports.SearchResponse.to_json(reports.SearchResponse()) req.return_value.content = return_value diff --git a/packages/grafeas/grafeas/grafeas/gapic_version.py b/packages/grafeas/grafeas/grafeas/gapic_version.py index 49ddc22ee702..558c8aab67c5 100644 --- a/packages/grafeas/grafeas/grafeas/gapic_version.py +++ b/packages/grafeas/grafeas/grafeas/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.12.1" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/grafeas/grafeas/grafeas_v1/gapic_version.py b/packages/grafeas/grafeas/grafeas_v1/gapic_version.py index 49ddc22ee702..558c8aab67c5 100644 --- a/packages/grafeas/grafeas/grafeas_v1/gapic_version.py +++ b/packages/grafeas/grafeas/grafeas_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.12.1" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/async_client.py b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/async_client.py index f18d20debe1d..2c520c5a0b0d 100644 --- a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/async_client.py +++ b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/async_client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import re from typing import ( Callable, @@ -67,6 +68,15 @@ from .transports.base import DEFAULT_CLIENT_INFO, GrafeasTransport from .transports.grpc_asyncio import GrafeasGrpcAsyncIOTransport +try: + from google.api_core import client_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 GrafeasAsyncClient: """`Grafeas `__ API. @@ -165,6 +175,28 @@ def __init__( credentials=credentials, ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `grafeas_v1.GrafeasAsyncClient`.", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "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": "grafeas.v1.Grafeas", + "credentialsType": None, + }, + ) + async def get_occurrence( self, request: Optional[Union[grafeas.GetOccurrenceRequest, dict]] = None, @@ -172,7 +204,7 @@ async def get_occurrence( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> grafeas.Occurrence: r"""Gets the specified occurrence. @@ -215,8 +247,10 @@ async def sample_get_occurrence(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: grafeas.grafeas_v1.types.Occurrence: @@ -275,7 +309,7 @@ async def list_occurrences( filter: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListOccurrencesAsyncPager: r"""Lists occurrences for the specified project. @@ -324,8 +358,10 @@ async def sample_list_occurrences(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: grafeas.grafeas_v1.services.grafeas.pagers.ListOccurrencesAsyncPager: @@ -399,7 +435,7 @@ async def delete_occurrence( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: r"""Deletes the specified occurrence. For example, use this method to delete an occurrence when the occurrence @@ -441,8 +477,10 @@ async def sample_delete_occurrence(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 @@ -492,7 +530,7 @@ async def create_occurrence( occurrence: Optional[grafeas.Occurrence] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> grafeas.Occurrence: r"""Creates a new occurrence. @@ -541,8 +579,10 @@ async def sample_create_occurrence(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: grafeas.grafeas_v1.types.Occurrence: @@ -603,7 +643,7 @@ async def batch_create_occurrences( occurrences: Optional[MutableSequence[grafeas.Occurrence]] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> grafeas.BatchCreateOccurrencesResponse: r"""Creates new occurrences in batch. @@ -655,8 +695,10 @@ async def sample_batch_create_occurrences(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: grafeas.grafeas_v1.types.BatchCreateOccurrencesResponse: @@ -718,7 +760,7 @@ async def update_occurrence( 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, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> grafeas.Occurrence: r"""Updates the specified occurrence. @@ -771,8 +813,10 @@ async def sample_update_occurrence(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: grafeas.grafeas_v1.types.Occurrence: @@ -834,7 +878,7 @@ async def get_occurrence_note( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> grafeas.Note: r"""Gets the note attached to the specified occurrence. Consumer projects can use this method to get a note that @@ -880,8 +924,10 @@ async def sample_get_occurrence_note(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: grafeas.grafeas_v1.types.Note: @@ -939,7 +985,7 @@ async def get_note( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> grafeas.Note: r"""Gets the specified note. @@ -982,8 +1028,10 @@ async def sample_get_note(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: grafeas.grafeas_v1.types.Note: @@ -1040,7 +1088,7 @@ async def list_notes( filter: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListNotesAsyncPager: r"""Lists notes for the specified project. @@ -1089,8 +1137,10 @@ async def sample_list_notes(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: grafeas.grafeas_v1.services.grafeas.pagers.ListNotesAsyncPager: @@ -1164,7 +1214,7 @@ async def delete_note( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: r"""Deletes the specified note. @@ -1204,8 +1254,10 @@ async def sample_delete_note(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 @@ -1256,7 +1308,7 @@ async def create_note( note: Optional[grafeas.Note] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> grafeas.Note: r"""Creates a new note. @@ -1311,8 +1363,10 @@ async def sample_create_note(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: grafeas.grafeas_v1.types.Note: @@ -1375,7 +1429,7 @@ async def batch_create_notes( notes: Optional[MutableMapping[str, grafeas.Note]] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> grafeas.BatchCreateNotesResponse: r"""Creates new notes in batch. @@ -1426,8 +1480,10 @@ async def sample_batch_create_notes(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: grafeas.grafeas_v1.types.BatchCreateNotesResponse: @@ -1488,7 +1544,7 @@ async def update_note( 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, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> grafeas.Note: r"""Updates the specified note. @@ -1541,8 +1597,10 @@ async def sample_update_note(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: grafeas.grafeas_v1.types.Note: @@ -1605,7 +1663,7 @@ async def list_note_occurrences( filter: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListNoteOccurrencesAsyncPager: r"""Lists occurrences referencing the specified note. Provider projects can use this method to get all @@ -1658,8 +1716,10 @@ async def sample_list_note_occurrences(): 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: grafeas.grafeas_v1.services.grafeas.pagers.ListNoteOccurrencesAsyncPager: diff --git a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/client.py b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/client.py index 1e3d2e5b01fc..b74edcbb9d46 100644 --- a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/client.py +++ b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import os import re from typing import ( @@ -48,6 +49,15 @@ 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 timestamp_pb2 # type: ignore @@ -314,6 +324,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} + def __init__( self, *, @@ -349,7 +360,7 @@ def get_occurrence( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> grafeas.Occurrence: r"""Gets the specified occurrence. @@ -392,8 +403,10 @@ def sample_get_occurrence(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: grafeas.grafeas_v1.types.Occurrence: @@ -449,7 +462,7 @@ def list_occurrences( filter: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListOccurrencesPager: r"""Lists occurrences for the specified project. @@ -498,8 +511,10 @@ def sample_list_occurrences(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: grafeas.grafeas_v1.services.grafeas.pagers.ListOccurrencesPager: @@ -570,7 +585,7 @@ def delete_occurrence( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: r"""Deletes the specified occurrence. For example, use this method to delete an occurrence when the occurrence @@ -612,8 +627,10 @@ def sample_delete_occurrence(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 @@ -660,7 +677,7 @@ def create_occurrence( occurrence: Optional[grafeas.Occurrence] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> grafeas.Occurrence: r"""Creates a new occurrence. @@ -709,8 +726,10 @@ def sample_create_occurrence(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: grafeas.grafeas_v1.types.Occurrence: @@ -768,7 +787,7 @@ def batch_create_occurrences( occurrences: Optional[MutableSequence[grafeas.Occurrence]] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> grafeas.BatchCreateOccurrencesResponse: r"""Creates new occurrences in batch. @@ -820,8 +839,10 @@ def sample_batch_create_occurrences(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: grafeas.grafeas_v1.types.BatchCreateOccurrencesResponse: @@ -880,7 +901,7 @@ def update_occurrence( 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, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> grafeas.Occurrence: r"""Updates the specified occurrence. @@ -933,8 +954,10 @@ def sample_update_occurrence(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: grafeas.grafeas_v1.types.Occurrence: @@ -993,7 +1016,7 @@ def get_occurrence_note( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> grafeas.Note: r"""Gets the note attached to the specified occurrence. Consumer projects can use this method to get a note that @@ -1039,8 +1062,10 @@ def sample_get_occurrence_note(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: grafeas.grafeas_v1.types.Note: @@ -1095,7 +1120,7 @@ def get_note( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> grafeas.Note: r"""Gets the specified note. @@ -1138,8 +1163,10 @@ def sample_get_note(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: grafeas.grafeas_v1.types.Note: @@ -1195,7 +1222,7 @@ def list_notes( filter: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListNotesPager: r"""Lists notes for the specified project. @@ -1244,8 +1271,10 @@ def sample_list_notes(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: grafeas.grafeas_v1.services.grafeas.pagers.ListNotesPager: @@ -1316,7 +1345,7 @@ def delete_note( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: r"""Deletes the specified note. @@ -1356,8 +1385,10 @@ def sample_delete_note(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 @@ -1405,7 +1436,7 @@ def create_note( note: Optional[grafeas.Note] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> grafeas.Note: r"""Creates a new note. @@ -1460,8 +1491,10 @@ def sample_create_note(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: grafeas.grafeas_v1.types.Note: @@ -1521,7 +1554,7 @@ def batch_create_notes( notes: Optional[MutableMapping[str, grafeas.Note]] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> grafeas.BatchCreateNotesResponse: r"""Creates new notes in batch. @@ -1572,8 +1605,10 @@ def sample_batch_create_notes(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: grafeas.grafeas_v1.types.BatchCreateNotesResponse: @@ -1630,7 +1665,7 @@ def update_note( 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, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> grafeas.Note: r"""Updates the specified note. @@ -1683,8 +1718,10 @@ def sample_update_note(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: grafeas.grafeas_v1.types.Note: @@ -1744,7 +1781,7 @@ def list_note_occurrences( filter: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListNoteOccurrencesPager: r"""Lists occurrences referencing the specified note. Provider projects can use this method to get all @@ -1797,8 +1834,10 @@ def sample_list_note_occurrences(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: grafeas.grafeas_v1.services.grafeas.pagers.ListNoteOccurrencesPager: diff --git a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/pagers.py b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/pagers.py index 04365d168fdc..35de58effe78 100644 --- a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/pagers.py +++ b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/pagers.py @@ -67,7 +67,7 @@ def __init__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiate the pager. @@ -81,8 +81,10 @@ def __init__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 = grafeas.ListOccurrencesRequest(request) @@ -141,7 +143,7 @@ def __init__( *, retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiates the pager. @@ -155,8 +157,10 @@ def __init__( 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 = grafeas.ListOccurrencesRequest(request) @@ -219,7 +223,7 @@ def __init__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiate the pager. @@ -233,8 +237,10 @@ def __init__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 = grafeas.ListNotesRequest(request) @@ -293,7 +299,7 @@ def __init__( *, retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiates the pager. @@ -307,8 +313,10 @@ def __init__( 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 = grafeas.ListNotesRequest(request) @@ -371,7 +379,7 @@ def __init__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiate the pager. @@ -385,8 +393,10 @@ def __init__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 = grafeas.ListNoteOccurrencesRequest(request) @@ -445,7 +455,7 @@ def __init__( *, retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiates the pager. @@ -459,8 +469,10 @@ def __init__( 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, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 = grafeas.ListNoteOccurrencesRequest(request) diff --git a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/grpc.py b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/grpc.py index 7ebadac51ede..079acc044c88 100644 --- a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/grpc.py +++ b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/grpc.py @@ -13,6 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import json +import logging as std_logging +import pickle from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -21,12 +24,90 @@ 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 grafeas.grafeas_v1.types import grafeas from .base import DEFAULT_CLIENT_INFO, GrafeasTransport +try: + from google.api_core import client_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": "grafeas.v1.Grafeas", + "rpcName": 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": "grafeas.v1.Grafeas", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + class GrafeasGrpcTransport(GrafeasTransport): """gRPC backend transport for Grafeas. @@ -195,7 +276,12 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -269,7 +355,7 @@ def get_occurrence( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_occurrence" not in self._stubs: - self._stubs["get_occurrence"] = self.grpc_channel.unary_unary( + self._stubs["get_occurrence"] = self._logged_channel.unary_unary( "/grafeas.v1.Grafeas/GetOccurrence", request_serializer=grafeas.GetOccurrenceRequest.serialize, response_deserializer=grafeas.Occurrence.deserialize, @@ -295,7 +381,7 @@ def list_occurrences( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_occurrences" not in self._stubs: - self._stubs["list_occurrences"] = self.grpc_channel.unary_unary( + self._stubs["list_occurrences"] = self._logged_channel.unary_unary( "/grafeas.v1.Grafeas/ListOccurrences", request_serializer=grafeas.ListOccurrencesRequest.serialize, response_deserializer=grafeas.ListOccurrencesResponse.deserialize, @@ -323,7 +409,7 @@ def delete_occurrence( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "delete_occurrence" not in self._stubs: - self._stubs["delete_occurrence"] = self.grpc_channel.unary_unary( + self._stubs["delete_occurrence"] = self._logged_channel.unary_unary( "/grafeas.v1.Grafeas/DeleteOccurrence", request_serializer=grafeas.DeleteOccurrenceRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -349,7 +435,7 @@ def create_occurrence( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "create_occurrence" not in self._stubs: - self._stubs["create_occurrence"] = self.grpc_channel.unary_unary( + self._stubs["create_occurrence"] = self._logged_channel.unary_unary( "/grafeas.v1.Grafeas/CreateOccurrence", request_serializer=grafeas.CreateOccurrenceRequest.serialize, response_deserializer=grafeas.Occurrence.deserialize, @@ -377,7 +463,7 @@ def batch_create_occurrences( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "batch_create_occurrences" not in self._stubs: - self._stubs["batch_create_occurrences"] = self.grpc_channel.unary_unary( + self._stubs["batch_create_occurrences"] = self._logged_channel.unary_unary( "/grafeas.v1.Grafeas/BatchCreateOccurrences", request_serializer=grafeas.BatchCreateOccurrencesRequest.serialize, response_deserializer=grafeas.BatchCreateOccurrencesResponse.deserialize, @@ -403,7 +489,7 @@ def update_occurrence( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "update_occurrence" not in self._stubs: - self._stubs["update_occurrence"] = self.grpc_channel.unary_unary( + self._stubs["update_occurrence"] = self._logged_channel.unary_unary( "/grafeas.v1.Grafeas/UpdateOccurrence", request_serializer=grafeas.UpdateOccurrenceRequest.serialize, response_deserializer=grafeas.Occurrence.deserialize, @@ -431,7 +517,7 @@ def get_occurrence_note( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_occurrence_note" not in self._stubs: - self._stubs["get_occurrence_note"] = self.grpc_channel.unary_unary( + self._stubs["get_occurrence_note"] = self._logged_channel.unary_unary( "/grafeas.v1.Grafeas/GetOccurrenceNote", request_serializer=grafeas.GetOccurrenceNoteRequest.serialize, response_deserializer=grafeas.Note.deserialize, @@ -455,7 +541,7 @@ def get_note(self) -> Callable[[grafeas.GetNoteRequest], grafeas.Note]: # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_note" not in self._stubs: - self._stubs["get_note"] = self.grpc_channel.unary_unary( + self._stubs["get_note"] = self._logged_channel.unary_unary( "/grafeas.v1.Grafeas/GetNote", request_serializer=grafeas.GetNoteRequest.serialize, response_deserializer=grafeas.Note.deserialize, @@ -481,7 +567,7 @@ def list_notes( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_notes" not in self._stubs: - self._stubs["list_notes"] = self.grpc_channel.unary_unary( + self._stubs["list_notes"] = self._logged_channel.unary_unary( "/grafeas.v1.Grafeas/ListNotes", request_serializer=grafeas.ListNotesRequest.serialize, response_deserializer=grafeas.ListNotesResponse.deserialize, @@ -505,7 +591,7 @@ def delete_note(self) -> Callable[[grafeas.DeleteNoteRequest], empty_pb2.Empty]: # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "delete_note" not in self._stubs: - self._stubs["delete_note"] = self.grpc_channel.unary_unary( + self._stubs["delete_note"] = self._logged_channel.unary_unary( "/grafeas.v1.Grafeas/DeleteNote", request_serializer=grafeas.DeleteNoteRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -529,7 +615,7 @@ def create_note(self) -> Callable[[grafeas.CreateNoteRequest], grafeas.Note]: # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "create_note" not in self._stubs: - self._stubs["create_note"] = self.grpc_channel.unary_unary( + self._stubs["create_note"] = self._logged_channel.unary_unary( "/grafeas.v1.Grafeas/CreateNote", request_serializer=grafeas.CreateNoteRequest.serialize, response_deserializer=grafeas.Note.deserialize, @@ -555,7 +641,7 @@ def batch_create_notes( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "batch_create_notes" not in self._stubs: - self._stubs["batch_create_notes"] = self.grpc_channel.unary_unary( + self._stubs["batch_create_notes"] = self._logged_channel.unary_unary( "/grafeas.v1.Grafeas/BatchCreateNotes", request_serializer=grafeas.BatchCreateNotesRequest.serialize, response_deserializer=grafeas.BatchCreateNotesResponse.deserialize, @@ -579,7 +665,7 @@ def update_note(self) -> Callable[[grafeas.UpdateNoteRequest], grafeas.Note]: # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "update_note" not in self._stubs: - self._stubs["update_note"] = self.grpc_channel.unary_unary( + self._stubs["update_note"] = self._logged_channel.unary_unary( "/grafeas.v1.Grafeas/UpdateNote", request_serializer=grafeas.UpdateNoteRequest.serialize, response_deserializer=grafeas.Note.deserialize, @@ -610,7 +696,7 @@ def list_note_occurrences( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_note_occurrences" not in self._stubs: - self._stubs["list_note_occurrences"] = self.grpc_channel.unary_unary( + self._stubs["list_note_occurrences"] = self._logged_channel.unary_unary( "/grafeas.v1.Grafeas/ListNoteOccurrences", request_serializer=grafeas.ListNoteOccurrencesRequest.serialize, response_deserializer=grafeas.ListNoteOccurrencesResponse.deserialize, @@ -618,7 +704,7 @@ def list_note_occurrences( return self._stubs["list_note_occurrences"] def close(self): - self.grpc_channel.close() + self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/grpc_asyncio.py b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/grpc_asyncio.py index 4e5d15d67078..5e80e76ad90f 100644 --- a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/grpc_asyncio.py +++ b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/grpc_asyncio.py @@ -14,6 +14,9 @@ # limitations under the License. # import inspect +import json +import logging as std_logging +import pickle from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -23,14 +26,93 @@ 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 from grpc.experimental import aio # type: ignore +import proto # type: ignore from grafeas.grafeas_v1.types import grafeas from .base import DEFAULT_CLIENT_INFO, GrafeasTransport from .grpc import GrafeasGrpcTransport +try: + from google.api_core import client_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": "grafeas.v1.Grafeas", + "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": "grafeas.v1.Grafeas", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + class GrafeasGrpcAsyncIOTransport(GrafeasTransport): """gRPC AsyncIO backend transport for Grafeas. @@ -242,10 +324,13 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + 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 @@ -277,7 +362,7 @@ def get_occurrence( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_occurrence" not in self._stubs: - self._stubs["get_occurrence"] = self.grpc_channel.unary_unary( + self._stubs["get_occurrence"] = self._logged_channel.unary_unary( "/grafeas.v1.Grafeas/GetOccurrence", request_serializer=grafeas.GetOccurrenceRequest.serialize, response_deserializer=grafeas.Occurrence.deserialize, @@ -305,7 +390,7 @@ def list_occurrences( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_occurrences" not in self._stubs: - self._stubs["list_occurrences"] = self.grpc_channel.unary_unary( + self._stubs["list_occurrences"] = self._logged_channel.unary_unary( "/grafeas.v1.Grafeas/ListOccurrences", request_serializer=grafeas.ListOccurrencesRequest.serialize, response_deserializer=grafeas.ListOccurrencesResponse.deserialize, @@ -333,7 +418,7 @@ def delete_occurrence( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "delete_occurrence" not in self._stubs: - self._stubs["delete_occurrence"] = self.grpc_channel.unary_unary( + self._stubs["delete_occurrence"] = self._logged_channel.unary_unary( "/grafeas.v1.Grafeas/DeleteOccurrence", request_serializer=grafeas.DeleteOccurrenceRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -359,7 +444,7 @@ def create_occurrence( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "create_occurrence" not in self._stubs: - self._stubs["create_occurrence"] = self.grpc_channel.unary_unary( + self._stubs["create_occurrence"] = self._logged_channel.unary_unary( "/grafeas.v1.Grafeas/CreateOccurrence", request_serializer=grafeas.CreateOccurrenceRequest.serialize, response_deserializer=grafeas.Occurrence.deserialize, @@ -388,7 +473,7 @@ def batch_create_occurrences( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "batch_create_occurrences" not in self._stubs: - self._stubs["batch_create_occurrences"] = self.grpc_channel.unary_unary( + self._stubs["batch_create_occurrences"] = self._logged_channel.unary_unary( "/grafeas.v1.Grafeas/BatchCreateOccurrences", request_serializer=grafeas.BatchCreateOccurrencesRequest.serialize, response_deserializer=grafeas.BatchCreateOccurrencesResponse.deserialize, @@ -414,7 +499,7 @@ def update_occurrence( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "update_occurrence" not in self._stubs: - self._stubs["update_occurrence"] = self.grpc_channel.unary_unary( + self._stubs["update_occurrence"] = self._logged_channel.unary_unary( "/grafeas.v1.Grafeas/UpdateOccurrence", request_serializer=grafeas.UpdateOccurrenceRequest.serialize, response_deserializer=grafeas.Occurrence.deserialize, @@ -442,7 +527,7 @@ def get_occurrence_note( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_occurrence_note" not in self._stubs: - self._stubs["get_occurrence_note"] = self.grpc_channel.unary_unary( + self._stubs["get_occurrence_note"] = self._logged_channel.unary_unary( "/grafeas.v1.Grafeas/GetOccurrenceNote", request_serializer=grafeas.GetOccurrenceNoteRequest.serialize, response_deserializer=grafeas.Note.deserialize, @@ -466,7 +551,7 @@ def get_note(self) -> Callable[[grafeas.GetNoteRequest], Awaitable[grafeas.Note] # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_note" not in self._stubs: - self._stubs["get_note"] = self.grpc_channel.unary_unary( + self._stubs["get_note"] = self._logged_channel.unary_unary( "/grafeas.v1.Grafeas/GetNote", request_serializer=grafeas.GetNoteRequest.serialize, response_deserializer=grafeas.Note.deserialize, @@ -492,7 +577,7 @@ def list_notes( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_notes" not in self._stubs: - self._stubs["list_notes"] = self.grpc_channel.unary_unary( + self._stubs["list_notes"] = self._logged_channel.unary_unary( "/grafeas.v1.Grafeas/ListNotes", request_serializer=grafeas.ListNotesRequest.serialize, response_deserializer=grafeas.ListNotesResponse.deserialize, @@ -518,7 +603,7 @@ def delete_note( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "delete_note" not in self._stubs: - self._stubs["delete_note"] = self.grpc_channel.unary_unary( + self._stubs["delete_note"] = self._logged_channel.unary_unary( "/grafeas.v1.Grafeas/DeleteNote", request_serializer=grafeas.DeleteNoteRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -544,7 +629,7 @@ def create_note( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "create_note" not in self._stubs: - self._stubs["create_note"] = self.grpc_channel.unary_unary( + self._stubs["create_note"] = self._logged_channel.unary_unary( "/grafeas.v1.Grafeas/CreateNote", request_serializer=grafeas.CreateNoteRequest.serialize, response_deserializer=grafeas.Note.deserialize, @@ -572,7 +657,7 @@ def batch_create_notes( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "batch_create_notes" not in self._stubs: - self._stubs["batch_create_notes"] = self.grpc_channel.unary_unary( + self._stubs["batch_create_notes"] = self._logged_channel.unary_unary( "/grafeas.v1.Grafeas/BatchCreateNotes", request_serializer=grafeas.BatchCreateNotesRequest.serialize, response_deserializer=grafeas.BatchCreateNotesResponse.deserialize, @@ -598,7 +683,7 @@ def update_note( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "update_note" not in self._stubs: - self._stubs["update_note"] = self.grpc_channel.unary_unary( + self._stubs["update_note"] = self._logged_channel.unary_unary( "/grafeas.v1.Grafeas/UpdateNote", request_serializer=grafeas.UpdateNoteRequest.serialize, response_deserializer=grafeas.Note.deserialize, @@ -630,7 +715,7 @@ def list_note_occurrences( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_note_occurrences" not in self._stubs: - self._stubs["list_note_occurrences"] = self.grpc_channel.unary_unary( + self._stubs["list_note_occurrences"] = self._logged_channel.unary_unary( "/grafeas.v1.Grafeas/ListNoteOccurrences", request_serializer=grafeas.ListNoteOccurrencesRequest.serialize, response_deserializer=grafeas.ListNoteOccurrencesResponse.deserialize, @@ -798,7 +883,7 @@ def _wrap_method(self, func, *args, **kwargs): return gapic_v1.method_async.wrap_method(func, *args, **kwargs) def close(self): - return self.grpc_channel.close() + return self._logged_channel.close() @property def kind(self) -> str: diff --git a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/rest.py b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/rest.py index 4403a5301af3..96821ab0a7ee 100644 --- a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/rest.py +++ b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/rest.py @@ -13,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import dataclasses import json # type: ignore +import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings @@ -38,6 +38,14 @@ 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, @@ -174,8 +182,10 @@ def post_update_occurrence(self, response): def pre_batch_create_notes( self, request: grafeas.BatchCreateNotesRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[grafeas.BatchCreateNotesRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + grafeas.BatchCreateNotesRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for batch_create_notes Override in a subclass to manipulate the request or metadata @@ -197,8 +207,10 @@ def post_batch_create_notes( def pre_batch_create_occurrences( self, request: grafeas.BatchCreateOccurrencesRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[grafeas.BatchCreateOccurrencesRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + grafeas.BatchCreateOccurrencesRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for batch_create_occurrences Override in a subclass to manipulate the request or metadata @@ -218,8 +230,10 @@ def post_batch_create_occurrences( return response def pre_create_note( - self, request: grafeas.CreateNoteRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[grafeas.CreateNoteRequest, Sequence[Tuple[str, str]]]: + self, + request: grafeas.CreateNoteRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[grafeas.CreateNoteRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for create_note Override in a subclass to manipulate the request or metadata @@ -239,8 +253,10 @@ def post_create_note(self, response: grafeas.Note) -> grafeas.Note: def pre_create_occurrence( self, request: grafeas.CreateOccurrenceRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[grafeas.CreateOccurrenceRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + grafeas.CreateOccurrenceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for create_occurrence Override in a subclass to manipulate the request or metadata @@ -260,8 +276,10 @@ def post_create_occurrence( return response def pre_delete_note( - self, request: grafeas.DeleteNoteRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[grafeas.DeleteNoteRequest, Sequence[Tuple[str, str]]]: + self, + request: grafeas.DeleteNoteRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[grafeas.DeleteNoteRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for delete_note Override in a subclass to manipulate the request or metadata @@ -272,8 +290,10 @@ def pre_delete_note( def pre_delete_occurrence( self, request: grafeas.DeleteOccurrenceRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[grafeas.DeleteOccurrenceRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + grafeas.DeleteOccurrenceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for delete_occurrence Override in a subclass to manipulate the request or metadata @@ -282,8 +302,10 @@ def pre_delete_occurrence( return request, metadata def pre_get_note( - self, request: grafeas.GetNoteRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[grafeas.GetNoteRequest, Sequence[Tuple[str, str]]]: + self, + request: grafeas.GetNoteRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[grafeas.GetNoteRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for get_note Override in a subclass to manipulate the request or metadata @@ -301,8 +323,10 @@ def post_get_note(self, response: grafeas.Note) -> grafeas.Note: return response def pre_get_occurrence( - self, request: grafeas.GetOccurrenceRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[grafeas.GetOccurrenceRequest, Sequence[Tuple[str, str]]]: + self, + request: grafeas.GetOccurrenceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[grafeas.GetOccurrenceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for get_occurrence Override in a subclass to manipulate the request or metadata @@ -322,8 +346,10 @@ def post_get_occurrence(self, response: grafeas.Occurrence) -> grafeas.Occurrenc def pre_get_occurrence_note( self, request: grafeas.GetOccurrenceNoteRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[grafeas.GetOccurrenceNoteRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + grafeas.GetOccurrenceNoteRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_occurrence_note Override in a subclass to manipulate the request or metadata @@ -343,8 +369,10 @@ def post_get_occurrence_note(self, response: grafeas.Note) -> grafeas.Note: def pre_list_note_occurrences( self, request: grafeas.ListNoteOccurrencesRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[grafeas.ListNoteOccurrencesRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + grafeas.ListNoteOccurrencesRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for list_note_occurrences Override in a subclass to manipulate the request or metadata @@ -364,8 +392,10 @@ def post_list_note_occurrences( return response def pre_list_notes( - self, request: grafeas.ListNotesRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[grafeas.ListNotesRequest, Sequence[Tuple[str, str]]]: + self, + request: grafeas.ListNotesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[grafeas.ListNotesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for list_notes Override in a subclass to manipulate the request or metadata @@ -387,8 +417,8 @@ def post_list_notes( def pre_list_occurrences( self, request: grafeas.ListOccurrencesRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[grafeas.ListOccurrencesRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[grafeas.ListOccurrencesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for list_occurrences Override in a subclass to manipulate the request or metadata @@ -408,8 +438,10 @@ def post_list_occurrences( return response def pre_update_note( - self, request: grafeas.UpdateNoteRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[grafeas.UpdateNoteRequest, Sequence[Tuple[str, str]]]: + self, + request: grafeas.UpdateNoteRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[grafeas.UpdateNoteRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for update_note Override in a subclass to manipulate the request or metadata @@ -429,8 +461,10 @@ def post_update_note(self, response: grafeas.Note) -> grafeas.Note: def pre_update_occurrence( self, request: grafeas.UpdateOccurrenceRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[grafeas.UpdateOccurrenceRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + grafeas.UpdateOccurrenceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for update_occurrence Override in a subclass to manipulate the request or metadata @@ -586,7 +620,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> grafeas.BatchCreateNotesResponse: r"""Call the batch create notes method over HTTP. @@ -596,8 +630,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.grafeas.BatchCreateNotesResponse: @@ -607,6 +643,7 @@ def __call__( http_options = ( _BaseGrafeasRestTransport._BaseBatchCreateNotes._get_http_options() ) + request, metadata = self._interceptor.pre_batch_create_notes( request, metadata ) @@ -629,6 +666,33 @@ def __call__( ) ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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 grafeas_v1.GrafeasClient.BatchCreateNotes", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "BatchCreateNotes", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = GrafeasRestTransport._BatchCreateNotes._get_response( self._host, @@ -650,7 +714,31 @@ def __call__( pb_resp = grafeas.BatchCreateNotesResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_batch_create_notes(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = grafeas.BatchCreateNotesResponse.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 grafeas_v1.GrafeasClient.batch_create_notes", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "BatchCreateNotes", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _BatchCreateOccurrences( @@ -688,7 +776,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> grafeas.BatchCreateOccurrencesResponse: r"""Call the batch create occurrences method over HTTP. @@ -699,8 +787,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.grafeas.BatchCreateOccurrencesResponse: @@ -712,6 +802,7 @@ def __call__( http_options = ( _BaseGrafeasRestTransport._BaseBatchCreateOccurrences._get_http_options() ) + request, metadata = self._interceptor.pre_batch_create_occurrences( request, metadata ) @@ -728,6 +819,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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 grafeas_v1.GrafeasClient.BatchCreateOccurrences", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "BatchCreateOccurrences", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = GrafeasRestTransport._BatchCreateOccurrences._get_response( self._host, @@ -749,7 +867,31 @@ def __call__( pb_resp = grafeas.BatchCreateOccurrencesResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_batch_create_occurrences(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = grafeas.BatchCreateOccurrencesResponse.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 grafeas_v1.GrafeasClient.batch_create_occurrences", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "BatchCreateOccurrences", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _CreateNote(_BaseGrafeasRestTransport._BaseCreateNote, GrafeasRestStub): @@ -785,7 +927,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> grafeas.Note: r"""Call the create note method over HTTP. @@ -795,8 +937,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.grafeas.Note: @@ -806,6 +950,7 @@ def __call__( """ http_options = _BaseGrafeasRestTransport._BaseCreateNote._get_http_options() + request, metadata = self._interceptor.pre_create_note(request, metadata) transcoded_request = ( _BaseGrafeasRestTransport._BaseCreateNote._get_transcoded_request( @@ -824,6 +969,33 @@ def __call__( ) ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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 grafeas_v1.GrafeasClient.CreateNote", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "CreateNote", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = GrafeasRestTransport._CreateNote._get_response( self._host, @@ -845,7 +1017,29 @@ def __call__( pb_resp = grafeas.Note.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_note(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = grafeas.Note.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 grafeas_v1.GrafeasClient.create_note", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "CreateNote", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _CreateOccurrence( @@ -883,7 +1077,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> grafeas.Occurrence: r"""Call the create occurrence method over HTTP. @@ -893,8 +1087,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.grafeas.Occurrence: @@ -906,6 +1102,7 @@ def __call__( http_options = ( _BaseGrafeasRestTransport._BaseCreateOccurrence._get_http_options() ) + request, metadata = self._interceptor.pre_create_occurrence( request, metadata ) @@ -928,6 +1125,33 @@ def __call__( ) ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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 grafeas_v1.GrafeasClient.CreateOccurrence", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "CreateOccurrence", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = GrafeasRestTransport._CreateOccurrence._get_response( self._host, @@ -949,7 +1173,29 @@ def __call__( pb_resp = grafeas.Occurrence.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_occurrence(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = grafeas.Occurrence.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 grafeas_v1.GrafeasClient.create_occurrence", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "CreateOccurrence", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _DeleteNote(_BaseGrafeasRestTransport._BaseDeleteNote, GrafeasRestStub): @@ -984,7 +1230,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ): r"""Call the delete note method over HTTP. @@ -994,11 +1240,14 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 = _BaseGrafeasRestTransport._BaseDeleteNote._get_http_options() + request, metadata = self._interceptor.pre_delete_note(request, metadata) transcoded_request = ( _BaseGrafeasRestTransport._BaseDeleteNote._get_transcoded_request( @@ -1013,6 +1262,33 @@ def __call__( ) ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + 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 grafeas_v1.GrafeasClient.DeleteNote", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "DeleteNote", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = GrafeasRestTransport._DeleteNote._get_response( self._host, @@ -1062,7 +1338,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ): r"""Call the delete occurrence method over HTTP. @@ -1072,13 +1348,16 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 = ( _BaseGrafeasRestTransport._BaseDeleteOccurrence._get_http_options() ) + request, metadata = self._interceptor.pre_delete_occurrence( request, metadata ) @@ -1095,6 +1374,33 @@ def __call__( ) ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + 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 grafeas_v1.GrafeasClient.DeleteOccurrence", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "DeleteOccurrence", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = GrafeasRestTransport._DeleteOccurrence._get_response( self._host, @@ -1142,7 +1448,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> grafeas.Note: r"""Call the get note method over HTTP. @@ -1152,8 +1458,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.grafeas.Note: @@ -1163,6 +1471,7 @@ def __call__( """ http_options = _BaseGrafeasRestTransport._BaseGetNote._get_http_options() + request, metadata = self._interceptor.pre_get_note(request, metadata) transcoded_request = ( _BaseGrafeasRestTransport._BaseGetNote._get_transcoded_request( @@ -1177,6 +1486,33 @@ def __call__( ) ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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 grafeas_v1.GrafeasClient.GetNote", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "GetNote", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = GrafeasRestTransport._GetNote._get_response( self._host, @@ -1197,7 +1533,29 @@ def __call__( pb_resp = grafeas.Note.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_note(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = grafeas.Note.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 grafeas_v1.GrafeasClient.get_note", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "GetNote", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _GetOccurrence(_BaseGrafeasRestTransport._BaseGetOccurrence, GrafeasRestStub): @@ -1232,7 +1590,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> grafeas.Occurrence: r"""Call the get occurrence method over HTTP. @@ -1242,8 +1600,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.grafeas.Occurrence: @@ -1255,6 +1615,7 @@ def __call__( http_options = ( _BaseGrafeasRestTransport._BaseGetOccurrence._get_http_options() ) + request, metadata = self._interceptor.pre_get_occurrence(request, metadata) transcoded_request = ( _BaseGrafeasRestTransport._BaseGetOccurrence._get_transcoded_request( @@ -1269,6 +1630,33 @@ def __call__( ) ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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 grafeas_v1.GrafeasClient.GetOccurrence", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "GetOccurrence", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = GrafeasRestTransport._GetOccurrence._get_response( self._host, @@ -1289,7 +1677,29 @@ def __call__( pb_resp = grafeas.Occurrence.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_occurrence(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = grafeas.Occurrence.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 grafeas_v1.GrafeasClient.get_occurrence", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "GetOccurrence", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _GetOccurrenceNote( @@ -1326,7 +1736,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> grafeas.Note: r"""Call the get occurrence note method over HTTP. @@ -1337,8 +1747,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.grafeas.Note: @@ -1350,6 +1762,7 @@ def __call__( http_options = ( _BaseGrafeasRestTransport._BaseGetOccurrenceNote._get_http_options() ) + request, metadata = self._interceptor.pre_get_occurrence_note( request, metadata ) @@ -1364,6 +1777,33 @@ def __call__( ) ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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 grafeas_v1.GrafeasClient.GetOccurrenceNote", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "GetOccurrenceNote", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = GrafeasRestTransport._GetOccurrenceNote._get_response( self._host, @@ -1384,7 +1824,29 @@ def __call__( pb_resp = grafeas.Note.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_occurrence_note(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = grafeas.Note.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 grafeas_v1.GrafeasClient.get_occurrence_note", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "GetOccurrenceNote", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _ListNoteOccurrences( @@ -1421,7 +1883,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> grafeas.ListNoteOccurrencesResponse: r"""Call the list note occurrences method over HTTP. @@ -1432,8 +1894,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.grafeas.ListNoteOccurrencesResponse: @@ -1445,6 +1909,7 @@ def __call__( http_options = ( _BaseGrafeasRestTransport._BaseListNoteOccurrences._get_http_options() ) + request, metadata = self._interceptor.pre_list_note_occurrences( request, metadata ) @@ -1457,6 +1922,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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 grafeas_v1.GrafeasClient.ListNoteOccurrences", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "ListNoteOccurrences", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = GrafeasRestTransport._ListNoteOccurrences._get_response( self._host, @@ -1477,7 +1969,31 @@ def __call__( pb_resp = grafeas.ListNoteOccurrencesResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_note_occurrences(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = grafeas.ListNoteOccurrencesResponse.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 grafeas_v1.GrafeasClient.list_note_occurrences", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "ListNoteOccurrences", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _ListNotes(_BaseGrafeasRestTransport._BaseListNotes, GrafeasRestStub): @@ -1512,7 +2028,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> grafeas.ListNotesResponse: r"""Call the list notes method over HTTP. @@ -1522,8 +2038,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.grafeas.ListNotesResponse: @@ -1531,6 +2049,7 @@ def __call__( """ http_options = _BaseGrafeasRestTransport._BaseListNotes._get_http_options() + request, metadata = self._interceptor.pre_list_notes(request, metadata) transcoded_request = ( _BaseGrafeasRestTransport._BaseListNotes._get_transcoded_request( @@ -1545,6 +2064,33 @@ def __call__( ) ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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 grafeas_v1.GrafeasClient.ListNotes", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "ListNotes", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = GrafeasRestTransport._ListNotes._get_response( self._host, @@ -1565,7 +2111,29 @@ def __call__( pb_resp = grafeas.ListNotesResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_notes(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = grafeas.ListNotesResponse.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 grafeas_v1.GrafeasClient.list_notes", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "ListNotes", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _ListOccurrences( @@ -1602,7 +2170,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> grafeas.ListOccurrencesResponse: r"""Call the list occurrences method over HTTP. @@ -1612,8 +2180,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.grafeas.ListOccurrencesResponse: @@ -1623,6 +2193,7 @@ def __call__( http_options = ( _BaseGrafeasRestTransport._BaseListOccurrences._get_http_options() ) + request, metadata = self._interceptor.pre_list_occurrences( request, metadata ) @@ -1639,6 +2210,33 @@ def __call__( ) ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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 grafeas_v1.GrafeasClient.ListOccurrences", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "ListOccurrences", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = GrafeasRestTransport._ListOccurrences._get_response( self._host, @@ -1659,7 +2257,29 @@ def __call__( pb_resp = grafeas.ListOccurrencesResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_occurrences(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = grafeas.ListOccurrencesResponse.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 grafeas_v1.GrafeasClient.list_occurrences", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "ListOccurrences", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _UpdateNote(_BaseGrafeasRestTransport._BaseUpdateNote, GrafeasRestStub): @@ -1695,7 +2315,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> grafeas.Note: r"""Call the update note method over HTTP. @@ -1705,8 +2325,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.grafeas.Note: @@ -1716,6 +2338,7 @@ def __call__( """ http_options = _BaseGrafeasRestTransport._BaseUpdateNote._get_http_options() + request, metadata = self._interceptor.pre_update_note(request, metadata) transcoded_request = ( _BaseGrafeasRestTransport._BaseUpdateNote._get_transcoded_request( @@ -1734,6 +2357,33 @@ def __call__( ) ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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 grafeas_v1.GrafeasClient.UpdateNote", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "UpdateNote", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = GrafeasRestTransport._UpdateNote._get_response( self._host, @@ -1755,7 +2405,29 @@ def __call__( pb_resp = grafeas.Note.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_note(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = grafeas.Note.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 grafeas_v1.GrafeasClient.update_note", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "UpdateNote", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _UpdateOccurrence( @@ -1793,7 +2465,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> grafeas.Occurrence: r"""Call the update occurrence method over HTTP. @@ -1803,8 +2475,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.grafeas.Occurrence: @@ -1816,6 +2490,7 @@ def __call__( http_options = ( _BaseGrafeasRestTransport._BaseUpdateOccurrence._get_http_options() ) + request, metadata = self._interceptor.pre_update_occurrence( request, metadata ) @@ -1838,6 +2513,33 @@ def __call__( ) ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + 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 grafeas_v1.GrafeasClient.UpdateOccurrence", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "UpdateOccurrence", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = GrafeasRestTransport._UpdateOccurrence._get_response( self._host, @@ -1859,7 +2561,29 @@ def __call__( pb_resp = grafeas.Occurrence.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_occurrence(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = grafeas.Occurrence.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 grafeas_v1.GrafeasClient.update_occurrence", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "UpdateOccurrence", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp @property diff --git a/packages/grafeas/samples/generated_samples/snippet_metadata_grafeas.v1.json b/packages/grafeas/samples/generated_samples/snippet_metadata_grafeas.v1.json index 94c1606b2cc5..290215d3171d 100644 --- a/packages/grafeas/samples/generated_samples/snippet_metadata_grafeas.v1.json +++ b/packages/grafeas/samples/generated_samples/snippet_metadata_grafeas.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "grafeas", - "version": "1.12.1" + "version": "0.1.0" }, "snippets": [ { @@ -51,7 +51,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "grafeas.grafeas_v1.types.BatchCreateNotesResponse", @@ -135,7 +135,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "grafeas.grafeas_v1.types.BatchCreateNotesResponse", @@ -220,7 +220,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "grafeas.grafeas_v1.types.BatchCreateOccurrencesResponse", @@ -304,7 +304,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "grafeas.grafeas_v1.types.BatchCreateOccurrencesResponse", @@ -393,7 +393,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "grafeas.grafeas_v1.types.Note", @@ -481,7 +481,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "grafeas.grafeas_v1.types.Note", @@ -566,7 +566,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "grafeas.grafeas_v1.types.Occurrence", @@ -650,7 +650,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "grafeas.grafeas_v1.types.Occurrence", @@ -731,7 +731,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "shortName": "delete_note" @@ -808,7 +808,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "shortName": "delete_note" @@ -886,7 +886,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "shortName": "delete_occurrence" @@ -963,7 +963,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "shortName": "delete_occurrence" @@ -1041,7 +1041,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "grafeas.grafeas_v1.types.Note", @@ -1121,7 +1121,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "grafeas.grafeas_v1.types.Note", @@ -1202,7 +1202,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "grafeas.grafeas_v1.types.Note", @@ -1282,7 +1282,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "grafeas.grafeas_v1.types.Note", @@ -1363,7 +1363,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "grafeas.grafeas_v1.types.Occurrence", @@ -1443,7 +1443,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "grafeas.grafeas_v1.types.Occurrence", @@ -1528,7 +1528,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "grafeas.grafeas_v1.services.grafeas.pagers.ListNoteOccurrencesAsyncPager", @@ -1612,7 +1612,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "grafeas.grafeas_v1.services.grafeas.pagers.ListNoteOccurrencesPager", @@ -1697,7 +1697,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "grafeas.grafeas_v1.services.grafeas.pagers.ListNotesAsyncPager", @@ -1781,7 +1781,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "grafeas.grafeas_v1.services.grafeas.pagers.ListNotesPager", @@ -1866,7 +1866,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "grafeas.grafeas_v1.services.grafeas.pagers.ListOccurrencesAsyncPager", @@ -1950,7 +1950,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "grafeas.grafeas_v1.services.grafeas.pagers.ListOccurrencesPager", @@ -2039,7 +2039,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "grafeas.grafeas_v1.types.Note", @@ -2127,7 +2127,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "grafeas.grafeas_v1.types.Note", @@ -2216,7 +2216,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "grafeas.grafeas_v1.types.Occurrence", @@ -2304,7 +2304,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "grafeas.grafeas_v1.types.Occurrence", diff --git a/packages/grafeas/tests/unit/gapic/grafeas_v1/test_grafeas.py b/packages/grafeas/tests/unit/gapic/grafeas_v1/test_grafeas.py index 13faaea9b42b..4cb82f78f551 100644 --- a/packages/grafeas/tests/unit/gapic/grafeas_v1/test_grafeas.py +++ b/packages/grafeas/tests/unit/gapic/grafeas_v1/test_grafeas.py @@ -5620,6 +5620,7 @@ def test_get_occurrence_rest_required_fields(request_type=grafeas.GetOccurrenceR response_value._content = json_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_occurrence(request) @@ -5665,6 +5666,7 @@ def test_get_occurrence_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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_occurrence(**mock_args) @@ -5804,6 +5806,7 @@ def test_list_occurrences_rest_required_fields( response_value._content = json_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_occurrences(request) @@ -5859,6 +5862,7 @@ def test_list_occurrences_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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_occurrences(**mock_args) @@ -6049,6 +6053,7 @@ def test_delete_occurrence_rest_required_fields( response_value._content = json_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_occurrence(request) @@ -6092,6 +6097,7 @@ def test_delete_occurrence_rest_flattened(): 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_occurrence(**mock_args) @@ -6224,6 +6230,7 @@ def test_create_occurrence_rest_required_fields( response_value._content = json_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_occurrence(request) @@ -6278,6 +6285,7 @@ def test_create_occurrence_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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_occurrence(**mock_args) @@ -6414,6 +6422,7 @@ def test_batch_create_occurrences_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.batch_create_occurrences(request) @@ -6468,6 +6477,7 @@ def test_batch_create_occurrences_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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.batch_create_occurrences(**mock_args) @@ -6605,6 +6615,7 @@ def test_update_occurrence_rest_required_fields( response_value._content = json_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_occurrence(request) @@ -6660,6 +6671,7 @@ def test_update_occurrence_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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_occurrence(**mock_args) @@ -6795,6 +6807,7 @@ def test_get_occurrence_note_rest_required_fields( response_value._content = json_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_occurrence_note(request) @@ -6840,6 +6853,7 @@ def test_get_occurrence_note_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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_occurrence_note(**mock_args) @@ -6968,6 +6982,7 @@ def test_get_note_rest_required_fields(request_type=grafeas.GetNoteRequest): response_value._content = json_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_note(request) @@ -7013,6 +7028,7 @@ def test_get_note_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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_note(**mock_args) @@ -7148,6 +7164,7 @@ def test_list_notes_rest_required_fields(request_type=grafeas.ListNotesRequest): response_value._content = json_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_notes(request) @@ -7203,6 +7220,7 @@ def test_list_notes_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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_notes(**mock_args) @@ -7389,6 +7407,7 @@ def test_delete_note_rest_required_fields(request_type=grafeas.DeleteNoteRequest response_value._content = json_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_note(request) @@ -7432,6 +7451,7 @@ def test_delete_note_rest_flattened(): 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_note(**mock_args) @@ -7569,6 +7589,7 @@ def test_create_note_rest_required_fields(request_type=grafeas.CreateNoteRequest response_value._content = json_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_note(request) @@ -7631,6 +7652,7 @@ def test_create_note_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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_note(**mock_args) @@ -7767,6 +7789,7 @@ def test_batch_create_notes_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.batch_create_notes(request) @@ -7821,6 +7844,7 @@ def test_batch_create_notes_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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.batch_create_notes(**mock_args) @@ -7953,6 +7977,7 @@ def test_update_note_rest_required_fields(request_type=grafeas.UpdateNoteRequest response_value._content = json_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_note(request) @@ -8008,6 +8033,7 @@ def test_update_note_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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_note(**mock_args) @@ -8152,6 +8178,7 @@ def test_list_note_occurrences_rest_required_fields( response_value._content = json_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_note_occurrences(request) @@ -8207,6 +8234,7 @@ def test_list_note_occurrences_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._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_note_occurrences(**mock_args) @@ -9109,6 +9137,7 @@ def test_get_occurrence_rest_bad_request(request_type=grafeas.GetOccurrenceReque 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_occurrence(request) @@ -9148,6 +9177,7 @@ def test_get_occurrence_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_occurrence(request) # Establish that the response is the type that we expect. @@ -9188,6 +9218,7 @@ def test_get_occurrence_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 = grafeas.Occurrence.to_json(grafeas.Occurrence()) req.return_value.content = return_value @@ -9230,6 +9261,7 @@ def test_list_occurrences_rest_bad_request(request_type=grafeas.ListOccurrencesR 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_occurrences(request) @@ -9265,6 +9297,7 @@ def test_list_occurrences_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_occurrences(request) # Establish that the response is the type that we expect. @@ -9301,6 +9334,7 @@ def test_list_occurrences_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 = grafeas.ListOccurrencesResponse.to_json( grafeas.ListOccurrencesResponse() ) @@ -9347,6 +9381,7 @@ def test_delete_occurrence_rest_bad_request( 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_occurrence(request) @@ -9377,6 +9412,7 @@ def test_delete_occurrence_rest_call_success(request_type): 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_occurrence(request) # Establish that the response is the type that we expect. @@ -9411,6 +9447,7 @@ def test_delete_occurrence_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"} request = grafeas.DeleteOccurrenceRequest() metadata = [ @@ -9451,6 +9488,7 @@ def test_create_occurrence_rest_bad_request( 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_occurrence(request) @@ -9927,6 +9965,7 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_occurrence(request) # Establish that the response is the type that we expect. @@ -9969,6 +10008,7 @@ def test_create_occurrence_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 = grafeas.Occurrence.to_json(grafeas.Occurrence()) req.return_value.content = return_value @@ -10013,6 +10053,7 @@ def test_batch_create_occurrences_rest_bad_request( 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.batch_create_occurrences(request) @@ -10046,6 +10087,7 @@ def test_batch_create_occurrences_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.batch_create_occurrences(request) # Establish that the response is the type that we expect. @@ -10083,6 +10125,7 @@ def test_batch_create_occurrences_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 = grafeas.BatchCreateOccurrencesResponse.to_json( grafeas.BatchCreateOccurrencesResponse() ) @@ -10129,6 +10172,7 @@ def test_update_occurrence_rest_bad_request( 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_occurrence(request) @@ -10605,6 +10649,7 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_occurrence(request) # Establish that the response is the type that we expect. @@ -10647,6 +10692,7 @@ def test_update_occurrence_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 = grafeas.Occurrence.to_json(grafeas.Occurrence()) req.return_value.content = return_value @@ -10691,6 +10737,7 @@ def test_get_occurrence_note_rest_bad_request( 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_occurrence_note(request) @@ -10730,6 +10777,7 @@ def test_get_occurrence_note_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_occurrence_note(request) # Establish that the response is the type that we expect. @@ -10772,6 +10820,7 @@ def test_get_occurrence_note_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 = grafeas.Note.to_json(grafeas.Note()) req.return_value.content = return_value @@ -10814,6 +10863,7 @@ def test_get_note_rest_bad_request(request_type=grafeas.GetNoteRequest): 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_note(request) @@ -10853,6 +10903,7 @@ def test_get_note_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_note(request) # Establish that the response is the type that we expect. @@ -10893,6 +10944,7 @@ def test_get_note_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 = grafeas.Note.to_json(grafeas.Note()) req.return_value.content = return_value @@ -10935,6 +10987,7 @@ def test_list_notes_rest_bad_request(request_type=grafeas.ListNotesRequest): 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_notes(request) @@ -10970,6 +11023,7 @@ def test_list_notes_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_notes(request) # Establish that the response is the type that we expect. @@ -11006,6 +11060,7 @@ def test_list_notes_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 = grafeas.ListNotesResponse.to_json(grafeas.ListNotesResponse()) req.return_value.content = return_value @@ -11048,6 +11103,7 @@ def test_delete_note_rest_bad_request(request_type=grafeas.DeleteNoteRequest): 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_note(request) @@ -11078,6 +11134,7 @@ def test_delete_note_rest_call_success(request_type): 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_note(request) # Establish that the response is the type that we expect. @@ -11110,6 +11167,7 @@ def test_delete_note_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"} request = grafeas.DeleteNoteRequest() metadata = [ @@ -11148,6 +11206,7 @@ def test_create_note_rest_bad_request(request_type=grafeas.CreateNoteRequest): 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_note(request) @@ -11447,6 +11506,7 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_note(request) # Establish that the response is the type that we expect. @@ -11487,6 +11547,7 @@ def test_create_note_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 = grafeas.Note.to_json(grafeas.Note()) req.return_value.content = return_value @@ -11531,6 +11592,7 @@ def test_batch_create_notes_rest_bad_request( 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.batch_create_notes(request) @@ -11564,6 +11626,7 @@ def test_batch_create_notes_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.batch_create_notes(request) # Establish that the response is the type that we expect. @@ -11601,6 +11664,7 @@ def test_batch_create_notes_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 = grafeas.BatchCreateNotesResponse.to_json( grafeas.BatchCreateNotesResponse() ) @@ -11645,6 +11709,7 @@ def test_update_note_rest_bad_request(request_type=grafeas.UpdateNoteRequest): 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_note(request) @@ -11944,6 +12009,7 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_note(request) # Establish that the response is the type that we expect. @@ -11984,6 +12050,7 @@ def test_update_note_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 = grafeas.Note.to_json(grafeas.Note()) req.return_value.content = return_value @@ -12028,6 +12095,7 @@ def test_list_note_occurrences_rest_bad_request( 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_note_occurrences(request) @@ -12063,6 +12131,7 @@ def test_list_note_occurrences_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_note_occurrences(request) # Establish that the response is the type that we expect. @@ -12101,6 +12170,7 @@ def test_list_note_occurrences_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 = grafeas.ListNoteOccurrencesResponse.to_json( grafeas.ListNoteOccurrencesResponse() ) From 1e395a4c300914763ba05b04622a5c6029fc2ee9 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Thu, 12 Dec 2024 20:05:15 +0000 Subject: [PATCH 4/4] lint --- packages/grafeas/grafeas/grafeas_v1/services/grafeas/client.py | 1 - scripts/client-post-processing/unique-grafeas-client.yaml | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/client.py b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/client.py index b74edcbb9d46..51567402e6b4 100644 --- a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/client.py +++ b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/client.py @@ -324,7 +324,6 @@ def parse_common_location_path(path: str) -> Dict[str, str]: m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} - def __init__( self, *, diff --git a/scripts/client-post-processing/unique-grafeas-client.yaml b/scripts/client-post-processing/unique-grafeas-client.yaml index 6c9a62a03ad6..26e2d17ed925 100644 --- a/scripts/client-post-processing/unique-grafeas-client.yaml +++ b/scripts/client-post-processing/unique-grafeas-client.yaml @@ -1515,7 +1515,7 @@ replacements: \ str: The universe domain used by the client instance. \ """ \ return self._universe_domain\n - after: "}\n" + after: "}" count: 1 - paths: [ packages/grafeas/grafeas/grafeas_v1/services/grafeas/client.py